<?php

namespace app\common\api;

use app\common\model\Company;

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

    public static function getOne($id) {
        return Company::findOrEmpty($id)->toArray();
    }

    public static function getList($params) {
        $order = $params["order"] ?: "desc";
        $offset = $params["offset"] ?: 0;
        $limit = $params["limit"] ?: 10;
        $where[] = ["delete", "=", 0];
        if ($params["name"]) {
            $where[] = ["name", "like", "%" . $params["name"] . "%"];
        }
        if ($params["code"]) {
            $where[] = ["code", "=", $params["code"]];
        }
        $count = Company::where($where)->count();
        $list = Company::where($where)->limit($offset, $limit)->order("sn " . $order)->select()->toArray();
        return ["total" => $count, "rows" => $list];
    }

    public static function getAll() {
        $where[] = ["delete", "=", 0];
        $list = Company::where($where)->order("sn asc")->select()->toArray();
        return $list;
    }

    public static function edit($params) {
        $company = new Company();
        $data["name"] = $params["name"];
        $data["shortName"] = $params["shortName"];
        $data["code"] = $params["code"];
        $data["sn"] = $params["sn"];
        $data["description"] = $params["description"];
        if ($params["id"]) {
            $item = $company->find($params["id"]);
            $data["updateTime"] = date("Y-m-d H:i:s");
            $data["updateUser"] = session("user")["uid"];
            return $item->save($data);
        } else {
            $data["id"] = getStringId();
            $data["createTime"] = date("Y-m-d H:i:s");
            $data["createUser"] = session("user")["uid"];
            return $company->save($data);
        }
    }

    public static function delete($id) {
        $data["id"] = $id;
        $data["delete"] = 1;
        $data["updateUser"] = session("user")["uid"];
        $data["updateTime"] = date("Y-m-d H:i:s");
        return Company::update($data);
    }

}
