<?php

namespace app\admin\api;

use app\admin\model\User;

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

    public static function getOne($id) {
        $res = User::findOrEmpty($id);
        if ($res["companyId"]) {
            $company = \app\common\api\CompanyApi::getOne($res["companyId"]);
            $res["companyName"] = $company["name"];
        }
        if ($res["roleid"]) {
            $role = RoleApi::getOne($res["roleid"]);
            $res["roleName"] = $role["name"];
        }
        if ($res["avatar"]) {
            $res["originalAvatar"] = $res["avatar"];
            $res["avatar"] = getStoragePath($res["avatar"]);
        }
        return $res;
    }

    public static function getList($params) {
        $where = [];
        $limit = $params["limit"] ?: 10;
        $offset = $params["offset"] ?: 0;
        $order = $params["order"] ?: "desc";
        if ($params["name"]) {
            $where[] = ["u.name", "like", "%" . $params["name"] . "%"];
        }
        if ($params["account"]) {
            $where[] = ["u.account", "like", "%" . $params["account"] . "%"];
        }
        if ($params["sex"]) {
            $where[] = ["u.sex", "=", $params["sex"]];
        }
        if ($params["phone"]) {
            $where[] = ["u.phone", "like", "%" . $params["phone"] . "%"];
        }
        if ($params["status"]) {
            $where[] = ["u.status", "=", $params["status"]];
        }
        if ($params["companyId"]) {
            $where[] = ["u.companyId", "=", $params["companyId"]];
        }
        $count = User::alias("u")->where($where)->count();
        $list = User::alias("u")
                        ->field("u.*,c.name as companyName,r.name as roleName")
                        ->leftJoin("sys_company c", "c.id=u.companyId")
                        ->leftJoin("sys_role r", "r.id=u.roleId")
                        ->where($where)
                        ->limit($offset, $limit)->order("u.name " . $order)->select()->toArray();
        return ["total" => $count, "rows" => $list];
    }

    public static function create($params) {
        $data["account"] = $params["account"];
        $data["name"] = $params["name"];
        $data["type"] = $params["type"];
        $data["birthday"] = $params["birthday"];
        $data["sex"] = $params["sex"];
        $salt = self::getSalt(5);
        $data["salt"] = $salt;
        $data["status"] = 1;
        $data["password"] = self::getPwd($params["password"], $salt);
        $data["companyId"] = $params["companyId"];
        $data["roleid"] = $params["roleid"];
        $data["phone"] = $params["phone"];
        $data["email"] = $params["email"];
        $data["createTime"] = date("Y-m-d H:i:s");
        $data["createUser"] = session("user")["uid"];
        if (User::insert($data))
            return 10001;
        return 10009;
    }

    public static function update($params) {
        $id = $params["id"];
        $user = self::getOne($id);
        if (!$user || $user["status"] == 3)
            return 10002;
        $roleIds = explode(",", $user["roleid"]);
        if (in_array(1, $roleIds) && !self::isAdmin(session("user")["uid"]))
            return 10003;
        $data["id"] = $id;
        if ($params["account"]) {
            $data["account"] = $params["account"];
        }
        if ($params["type"]) {
            $data["type"] = $params["type"];
        }
        if ($params["companyId"]) {
            $data["companyId"] = $params["companyId"];
        }
        if ($params["avatar"] && $user["avatar"] != $params["avatar"]) {
            $data["avatar"] = $params["avatar"];
        }
        $data["name"] = $params["name"];
        $data["birthday"] = $params["birthday"];
        $data["sex"] = $params["sex"];
        $data["phone"] = $params["phone"];
        $data["email"] = $params["email"];
        $data["updateTime"] = date("Y-m-d H:i:s");
        $data["updateUser"] = session("user")["uid"];
        if (User::update($data))
            return 10001;
        return 10009;
    }

    public static function setRole($id, $roleIds) {
        if (self::isDelete($id))
            return 10002;
        if (self::isAdmin($id) && !self::isAdmin(session("user")["uid"]))
            return 10003;
        $data["id"] = $id;
        $data["roleid"] = $roleIds;
        $data["updateTime"] = date("Y-m-d H:i:s");
        $data["updateUser"] = session("user")["uid"];
        if (User::update($data))
            return 10001;
        return 10009;
    }

    /**
     * 重置密码
     * @param type $id
     * @param type $password
     * @return boolean
     */
    public static function reset($id, $password) {
        if (self::isDelete($id))
            return 10002;
        if (self::isAdmin($id) && !self::isAdmin(session("user")["uid"]))
            return 10003;
        $data["id"] = $id;
        $data["password"] = $password;
        if (User::update($data))
            return 10001;
        return 10009;
    }

    /**
     * 删除用户
     * @param type $id
     * @return boolean
     */
    public static function delete($id) {
        if (self::isDelete($id))
            return 10002;
        if (self::isAdmin($id) && !self::isAdmin(session("user")["uid"]))
            return 10003;
        $data["id"] = $id;
        $data["status"] = 3;
        $data["updateTime"] = date("Y-m-d H:i:s");
        $data["updateUser"] = session("user")["uid"];
        if (User::update($data))
            return 10001;
        return 10009;
    }

    public static function setPwd($id, $old_password, $new_password) {
        $user = self::getOne($id);
        if (!$user || $user["status"] == 3)
            return 10002;
        $roleIds = explode(",", $user["roleid"]);
        if (in_array(1, $roleIds) && !self::isAdmin(session("user")["uid"]))
            return 10003;
        if (self::getPwd($old_password, $user["salt"]) != $user["password"])
            return 10004;
        $data["id"] = $id;
        $data["password"] = self::getPwd($new_password, $user["salt"]);
        $data["updateTime"] = date("Y-m-d H:i:s");
        $data["updateUser"] = session("user")["uid"];
        if (User::update($data))
            return 10001;
        return 10009;
    }

    /**
     * 冻结解冻用户
     * @param type $id
     * @return boolean
     */
    public static function setFreeze($id, $status) {
        if (self::isDelete($id))
            return 10002;
        if (self::isAdmin($id) && !self::isAdmin(session("user")["uid"]))
            return 10003;
        $data["id"] = $id;
        $data["status"] = $status;
        $data["updateTime"] = date("Y-m-d H:i:s");
        $data["updateUser"] = session("user")["uid"];
        if (User::update($data))
            return 10001;
        return 10009;
    }

    /**
     * 检查删除
     * @param type $id
     * @return boolean
     */
    public static function isDelete($id) {
        $user = self::getOne($id);
        if (!$user || $user["status"] == 3)
            return true;
        return false;
    }

    /**
     * 检查是不是管理员
     * @param type $id
     * @return boolean
     */
    public static function isAdmin($id) {
        $user = self::getOne($id);
        $roleIds = explode(",", $user["roleid"]);
        if (in_array(1, $roleIds))
            return true;
        return false;
    }

    /**
     * 生成管理员密码
     * @return type
     */
    public static function getPwd($password, $salt) {
        $salt = hash("md5", $salt, true);
        $password = simple_hash("md5", $password, $salt, 1024);
        return $password;
    }

    /**
     * 生成加密盐
     * @param type $length
     * @return type
     */
    public static function getSalt($length) {
        $bytes = random_bytes($length);
        return substr(bin2hex($bytes), 0, $length);
    }

}
