<?php

namespace frontend\modules\api\controllers;

use common\components\AjaxException;
use common\components\BaseAjaxController;
use common\models\BaseRole;
use common\models\BaseRoleClientRules;
use common\models\BaseRoleServerRules;
use common\models\BaseUser;
use common\services\AdminLogService;
use common\services\DictionaryService;
use common\services\RoleService;
use common\services\UserService;
use Yii;
use yii\base\InvalidConfigException;
use yii\db\Exception;
use yii\web\Response;

class LoginController extends BaseAjaxController
{
    /**
     * 获取登录信息
     * @param BaseUser $userInfo
     * @return array
     */
    protected function getLoginDataAndSaveServerRules(BaseUser $userInfo): array
    {
        $app_token = md5($userInfo->id . "_" . $this->uniqueNum());
        // 追加头像路径
        $imageBasePath = $this->getImageBasePath();
        // 填充数据
        $loginData = [
            "token" => $app_token,
            "id" => $userInfo->id,
            "status" => $userInfo->status,
            "username" => $userInfo->username,
            "path" => $userInfo->path,
            "imageBasePath" => $imageBasePath,
            "dic" => DictionaryService::getDictionaryObjShowData(),
        ];
        $userInfo->last_login_time = date('Y-m-d H:i:s');
        $userInfo->save();
        if ($userInfo->username == 'admin') {
            $loginData['rules'] = "*";
            $loginData["roles_code"] = 1;
            $loginData["roles_status"] = 1;
            //服务端rules
            $serverRules = "*";
        } else {
            //先找到user_role的所有角色
            $roles = explode(',', $userInfo->roles);
            $RoleClientRules = BaseRoleClientRules::findAll(["role_id" => $roles]);
            $clientRules = [];
            foreach ($RoleClientRules as $RoleClientRule) {
                $clientRules = array_merge($clientRules, json_decode($RoleClientRule->rules, true));
            }
            $loginData['rules'] = $clientRules;
            //服务端rules
            $serverRules = [];
            $RoleServerRules = BaseRoleServerRules::findAll(["role_id" => $roles]);
            foreach ($RoleServerRules as $RoleServerRule) {
                $serverRules = array_merge($serverRules, json_decode($RoleServerRule->rules, true));
            }
            $serverRules = array_values(array_unique($serverRules));
            $roleInfo = BaseRole::findOne(["id" => $roles]);
            $loginData["roles_code"] = $roleInfo->code;
            $loginData["roles_status"] = $roleInfo->status;
        }
        //保存服务端rules
        $redis = Yii::$app->redis;
        $redis->set($app_token, $userInfo->id); //  86400 *7
        $redis->expire($app_token, 604800); //  86400 *7
        if ($serverRules == "*") {
            $redis->set('rules_' . $userInfo->id, $serverRules);
        } else {
            $redis->set('rules_' . $userInfo->id, json_encode($serverRules));
        }
        $redis->expire('rules_' . $userInfo->id, 604800);
        return $loginData;
    }

    /**
     * 登录
     * @throws AjaxException
     * @throws InvalidConfigException
     */
    public function actionIndex()
    {
        // 获取传值
        $post = Yii::$app->request->post();
        $username = $post['username'];
        $password = $post['password'];
        // 定义返回值
//        $password = md5($password);
        // 检验玩家信息
        /** @var BaseUser $info */
        $info = UserService::getQuery()->andWhere(['username' => $username, "password" => $password])->one();
        if (!$info) {
            return $this->asJson([], 1, "没有该用户或者密码错误！"); //通知前端
        }
        $loginData = $this->getLoginDataAndSaveServerRules($info);
        // 返回
        $info->roleName = RoleService::getRoleNameById($info->roles);
        $info->realName = UserService::getRealNameByUserId($info->id);
        $adminLog = AdminLogService::saveLog($info, "/login/index", []);
        $_GET["adminLogId"] = $adminLog->id;
        $_GET["adminLogModel"] = $adminLog;
        $origin = AdminLogService::getOrigin($info, $this->getAllParams());
        AdminLogService::saveLogWithUpdateHistory($origin, $info, 0, "", $this->getAllParams());
        return $this->asJson($loginData);
    }

    /**
     * x5登录
     * @return Response
     * @throws Exception
     * @throws AjaxException
     */
    public function actionX5Login()
    {
        // 获取传值
        $post = Yii::$app->request->post();
        $userName = $post['userName'];
        $userCode = $post['userCode'];
        $posName = $post['posName'];
        $posCode = $post['posCode'];
        $deptName = $post['deptName'];
        $deptCode = $post['deptCode'];
        // 检验玩家信息
        if ($userCode === "admin") {
            return $this->asJson([], 1, "x5无法登陆管理员账号！"); //通知前端
        }
        /** @var BaseUser $info */
        $info = UserService::getQuery()->andWhere(['username' => $userCode])->one();
        if (!$info) {
            return $this->asJson([], 1, "当前用户无访问权限!"); //通知前端
//            $info = new BaseUser();
//            $info->password = md5("admin123456");
//            $info->username = $userCode;
//            $info->name = $userName;
//            $info->roles = "2";
//            //创建时间,更新时间
//            $info->create_time = date("Y-m-d H:i:s");
//            $info->update_time = date("Y-m-d H:i:s");
//            if (!$info->save()) {
//                throw new Exception($info->getErrorSummary(true)[0]);
//            }
//            //保存员工信息
//            $staffInfo = new Staff();
//            //数据录入
//            $staffInfo->name = $userName;
//            $staffInfo->phone = 111;
//            $staffInfo->seniority = 0;
//            $staffInfo->department = $deptName;
//            $staffInfo->employment = $posName;
//            $staffInfo->uid = $info->id;
//            $staffInfo->save();
//            $info = UserService::getQuery()->andWhere(['username' => $userCode])->one();
        }
        $loginData = $this->getLoginDataAndSaveServerRules($info);
        // 返回
        $info->roleName = RoleService::getRoleNameById($info->roles);
        $info->realName = UserService::getRealNameByUserId($info->id);
        AdminLogService::saveLog($info, "/login/x5Login", []);
        return $this->asJson($loginData);
    }

    /**
     * 校验昵称
     * @param $username
     * @return Response
     */
    public function actionCheckUsername($username)
    {
        // 定义返回值
        $loginData = [];
        $info = UserService::getQuery()->andWhere(['username' => $username])->one();
        if ($info) {
            return $this->asJson([], 1, "此昵称已存在！"); //通知前端
        }
        // 返回
        return $this->asJson($loginData);
    }
}
