<?php

namespace app\common\api;

use app\admin\model\Notice;

/**
 * Description of NoticeApi
 *
 * @author sgq
 */
class NoticeApi {

    public static function getOne($id) {
        return Notice::findOrEmpty($id);
    }

    public static function getList($params = []) {
        $where = [];
        $condition = $params["condition"];
        $order = $params["order"] ?: "desc";
        $offset = $params["offset"] ?: 0;
        $limit = $params["limit"] ?: 10;
        if ($condition) {
            $where[] = ["n.title", "like", "%{$condition}%"];
            $where[] = ["n.content", "like", "%{$condition}%"];
        }
        $count = Notice::alias("n")->whereOr($where)->count();
        $list = Notice::alias("n")->whereOr($where)
                        ->leftJoin("sys_user u", "u.id=n.creater")
                        ->leftJoin("sys_company c", "c.id=u.companyId")
                        ->order(["n.isTop" => "asc", "n.topTime" => $order, "n.createtime" => $order])
                        ->limit($offset, $limit)
                        ->field("n.*,concat(u.name,'（',c.name,'）') as createrName")
                        ->select()->toArray();
        return ["total" => $count, "rows" => $list];
    }

    public static function edit($params) {
        $data["title"] = $params["title"];
        $data["content"] = $params["content"];
        $data["batch"] = $params["batch"];
        $data["showWay"] = $params["showWay"];
        if ($params["id"]) {
            $data["id"] = $params["id"];
            return Notice::update($data);
        } else {
            $data["createtime"] = date("Y-m-d H:i:s");
            $data["creater"] = session("user")["uid"];
            $data["isTop"] = 2;
            return Notice::insert($data);
        }
    }

    public static function delete($id) {
        return Notice::where(["id" => $id])->delete();
    }

    public static function setTop($id) {
        $upd["id"] = $id;
        $upd["isTop"] = 1;
        $upd["topTime"] = date("Y-m-d H:i:s");
        return Notice::update($upd);
    }

}
