<?php

namespace app\common\api;

use app\admin\model\User;
use app\admin\model\Enterprise;
use app\admin\model\Person;
use app\admin\model\Role;

const MAX_ERROR_TIMES = 5;
const FREEZETIME = 5;
const FREEZE_NO = 1;
const FREEZE_YES = 2;

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

    protected $username, $password, $usertype;
    public $info;

    public function __construct($username, $password, $usertype) {
        $this->username = $username;
        $this->password = $password;
        $this->usertype = $usertype;
        switch ($usertype) {
            case 2:
                //企业
                $where = [];
                $name1 = str_replace(["(", ")"], ["（", "）"], $username);
                $name2 = str_replace(["（", "）"], ["(", ")"], $username);
                $where[] = ["username", "=", $name1];
                $where[] = ["username", "=", $name2];
                $user = Enterprise::whereOr($where)->findOrEmpty();
                break;
            case 3:
                //个人
                $user = Person::where('username', $username)->findOrEmpty();
                break;
            default:
                //管理员
                $where[] = ["account", "=", $username];
                $where[] = ["status", "<>", 3];
                $user = User::where($where)->findOrEmpty();
                break;
        }
        $this->info = $user;
        return $this;
    }

    public function getRole() {
        $role = Role::findOrEmpty($this->info["roleid"]);
        return $role->toArray();
    }

    public function getCompany() {
        $company = \app\common\model\Company::findOrEmpty($this->info["companyId"])->toArray();
        return $company;
    }

    /**
     * 返回用户信息
     * @return type
     */
    public function getUserInfo() {
        return $this->info->toArray();
    }

    public function checkPwd() {
        if ($this->_checkPwd()) {
            return true;
        } else {
            if ($this->usertype == 2 && in_array($this->info["source"], [1, 2])) {
                //source3是新系统注册，企业号登录密码不正确时，验证一下是不是聚财账号
                if ($this->info["source"] == 1) {
                    if (!$this->info["jUsername"]) {
                        return false;
                    }
                }
                try {
                    $res = JucaiApi::login($this->username, $this->password, 1);
                    $resObj = json_decode($res);
                    if ($resObj->state == 1) {
                        return true;
                    }
                    return false;
                } catch (think\exception $e) {
                    return false;
                }
            }
            return false;
        }
    }

    /**
     * 检查密码
     * @return type
     */
    public function _checkPwd() {
        switch ($this->usertype) {
            case 1:
                $salt = hash("md5", $this->info["salt"], true);
                $password = simple_hash("md5", $this->password, $salt, 1024);
                break;
            case 2:
            case 3:
                $password = hash("md5", $this->password);
                break;
        }
        return $password == $this->info["password"];
    }

    public function checkState() {
        switch ($this->usertype) {
            case 1:
                return false;
                break;
            case 2:
                if ($this->info['active'] != 1) {
                    return "账号被冻结， 冻结原因为： {$this->info['activeMsg']}";
                }
                if ($this->info["checkState"] == 3) {
                    return false;
                } else if ($this->info["checkState"] == 6) {
                    //6是初审状态，待复审
                    return "您的账号正在审核中，请耐心等待!";
                } else if (in_array($this->info['checkState'], [1, 4])) {
                    return "账号需要后台管理人员审核通过后才能登陆，请耐心等待!";
                } else if (in_array($this->info['checkState'], [2, 5])) {
                    $temp = [];
                    $temp['uid'] = $this->info['id'];
                    $temp['msg'] = "账号审核不通过，原因是：{$this->info['checkMsg']}";
                    session('temp', $temp);
                    return "账号审核不通过，原因是：{$this->info['checkMsg']}";
                } else {
                    return "账户状态未知，登录失败";
                }
                break;
            case 3:
                return false;
                break;
        }
    }

    /**
     * 设置冻结与否
     * @param type $freezetype
     */
    public function setFreeze($freezetype = FREEZE_NO) {
        $this->info->freeze = $freezetype;
        if ($freezetype == FREEZE_NO) {
            $this->info->errorCount = null;
            $this->info->freezeTime = null;
        } else {
            $this->info->freezeTime = strtotime(sprintf("+%d minutes", FREEZETIME));
        }
        $this->info->save();
    }

    public function setSession() {
        session('temp', null);
        session("isCaptcha", null);
        session('login_fail', null);
        $user = $this->getUserInfo();
        switch ($this->usertype) {
            case 1:
                session("user", [
                    "uid" => $user["id"],
                    "roleid" => $user["roleid"],
                    "companyId" => $user["companyId"],
                    "companyName" => $this->getCompany()["name"],
                    "account" => $user["account"],
                    "name" => $user["name"],
                    "avatar" => $user["avatar"],
                    "sex" => $user["sex"],
                    "rolename" => $this->getRole()["name"],
                    "usertype" => $this->usertype,
                    "type" => $user['type']
                ]);
                $loginData = [];
                $loginData["logname"] = "登录日志";
                $loginData["userid"] = $user["id"];
                $loginData["createtime"] = date("Y-m-d H:i:s");
                $loginData["succeed"] = "成功";
                $loginData["ip"] = get_client_ip();
                \think\facade\Db::table("sys_login_log")->insert($loginData);
                break;
            case 2:
                session("user", [
                    "uid" => $user["id"],
                    "account" => $user["username"],
                    "name" => $user["name"],
                    "avatar" => $user["headPortrait"],
                    "rolename" => "企业用户",
                    "usertype" => $this->usertype,
                    "type" => $user["type"]
                ]);
                break;
            case 3:
                session("user", [
                    "uid" => $user["id"],
                    "account" => $user["username"],
                    "name" => $user["name"],
                    "avatar" => $user["headPortrait"],
                    "sex" => $user["sex"],
                    "rolename" => "个人用户",
                    "usertype" => $this->usertype,
                    "type" => $user["type"]
                ]);
                break;
        }
    }

}
