<?php
/**
 * @Copyright (c) 2019  XIGU Inc. All rights reserved.
 * @Link https://www.vlcms.com
 * @License江苏溪谷网络科技有限公司版权所有
 */

namespace app\common\logic;

use app\common\model\Manager as mManager;
use app\common\model\ManagerBank as mManagerBank;
use app\common\model\Role as mRole;
use app\common\model\Honor as mHonor;
use app\common\model\Department as mDepartment;
use \app\common\validate\Manager as vManager;
use \app\common\validate\ManagerBank as vManagerBank;

class Manager extends Base
{

    /**
     * @登录接口
     *
     * @return array
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @since: 2019/3/30 16:05
     * @author: imdong
     */
    public function login()
    {
        $result = ['code' => 200, 'msg' => '', 'data' => []];
        $param = request() -> post();
        $validate = new vManager();
        if (!$validate -> scene('login') -> check($param)) {
            $result['code'] = 1001;
            $result['msg'] = $validate -> getError();
            return $result;
        }
        $mManager = new mManager();
        $field = 'id,name,nickname,mobile,password,status,activation';
        $managerInfo = $mManager -> field($field) -> where('name', '=', $param['name']) -> find();
        if ((empty($managerInfo) || $managerInfo -> status != 1) && $managerInfo['id'] != config('administrators_id')) {
            $result['code'] = 5005;
            $result['msg'] = $this -> errorCode(5005);
            return $result;
        }
        if (data_encrypt($param['password']) != $managerInfo -> password) {
            $result['code'] = 1003;
            $result['msg'] = $this -> errorCode(1003);
            return $result;
        }
        if ($managerInfo -> activation != 1) {
            $result['code'] = 1004;
            $result['msg'] = $this -> errorCode(1004);
            return $result;
        }
        $mRole = new mRole();
        $role_id = $managerInfo -> auth() -> value('role_id');
        $roleStatus = $mRole -> where(['id' => $role_id]) -> value('status');
        if ($roleStatus == '0' && $managerInfo['id'] != config('administrators_id')) {
            $result['code'] = 5004;
            $result['msg'] = $this -> errorCode(5004);
            return $result;
        }
        $managerItem = $managerInfo -> item() -> find();
        if (!empty($managerItem)) {
            //判断部门状态
            $mDepartment = new mDepartment();
            $where = [];
            $where[] = ['id', '=', $managerItem['department_id']];
            $departmentInfo = $mDepartment -> where($where) -> find();
            if ($departmentInfo['status'] === 0 || $departmentInfo['status'] === - 1) {
                $result['code'] = 5007;
                $result['msg'] = $this -> errorCode(5007);
                return $result;
            }
        }
        unset($managerInfo -> status, $managerInfo -> password);
        //荣誉等级
        $honor_id = $managerInfo -> honor() -> value('honor_id');
        $mHonor = new mHonor();
        $honorName = $mHonor -> where('id', '=', $honor_id) -> value('name');
        $result['data']['id'] = $managerInfo -> id;
        $result['data']['name'] = $managerInfo -> name;
        $result['data']['nickname'] = $managerInfo -> nickname;
        $result['data']['honor_name'] = empty($honorName) ? '' : $honorName;
        $result['data']['mobile'] = $managerInfo -> mobile;
        $result['data']['role_id'] = $managerInfo -> auth -> role_id;
        $result['data']['is_administrators'] = $managerInfo -> id == config('administrators_id') ? 1 : 0;
        //是否有设置权限的权限
        if ($managerInfo -> id == config('administrators_id')) {
            $result['data']['auth_setting'] = 1;
        } else {
            $mRole = new mRole();
            $roleMap = [];
            $roleMap[] = ['id', '=', $role_id];
            $auth_ids = $mRole -> where($roleMap) -> value('auth_ids');
            $auth_ids_arr = explode(',', $auth_ids);
            if (in_array('51', $auth_ids_arr)) {
                $result['data']['auth_setting'] = 1;
            } else {
                $result['data']['auth_setting'] = 0;
            }
        }
        $result['msg'] = '登录成功';
        $access_arr = $managerInfo -> getData();
        //生成token并写入缓存
        $token_arr = $this -> createManagerToken($access_arr);
        $result['data']['manager_access_token'] = $token_arr['manager_access_token'];
        $result['data']['manager_refresh_token'] = $token_arr['manager_refresh_token'];;
        //关联写入
        if (empty($managerInfo -> login)) {
            $managerInfo -> login() -> save(['login_num' => 1, 'login_ip' => request() -> ip(), 'login_time' => time()]);
        } else {
            //关联更新
            $managerInfo -> login -> login_num = $managerInfo -> login -> login_num + 1;
            $managerInfo -> login -> login_ip = request() -> ip();
            $managerInfo -> login -> login_time = time();
            $managerInfo -> login -> save();
        }
        $managerInfo -> log() -> save(['manager_id' => $managerInfo -> id, 'login_ip' => request() -> ip(), 'login_time' => time()]);
        return $result;
    }

    /**
     * @用户登出
     *
     * @author: zsl
     * @since: 2021/2/24 11:17
     */
    public function logout()
    {
        $result = ['code' => 200, 'msg' => '登出成功', 'data' => []];
        if ($user_id = $this -> getManagerId()) {
            file_cache('manager_access_' . $user_id, '', - 1);
            file_cache('manager_refresh_' . $user_id, '', - 1);
        }
        return $result;
    }

    /**
     * @刷新用户token
     *
     * @author: zsl
     * @since: 2019/5/8 11:59
     */
    public function refreshToken()
    {

        $result = ['code' => 200, 'msg' => '刷新成功', 'data' => []];
        $param = request() -> post();
        if (empty($param['manager_refresh_token'])) {
            $result['code'] = 1002;
            $result['msg'] = $this -> errorCode(1002);
            return $result;
        }
        $refresh_token_arr = json_decode(decrypt($param['manager_refresh_token']), true);
        if (!$refresh_token_arr) {
            $result['code'] = 1002;
            $result['msg'] = $this -> errorCode(1002);
            return $result;
        }
        //验证token
        $manager_refresh_token = file_cache('manager_refresh_' . $refresh_token_arr['id']);
        if ($manager_refresh_token != $param['manager_refresh_token']) {
            $result['code'] = 1002;
            $result['msg'] = $this -> errorCode(1002);
            return $result;
        }
        //重新生成token,并写入缓存
        $token_arr = $this -> createManagerToken($refresh_token_arr);
        $refresh_token_arr['manager_access_token'] = $token_arr['manager_access_token'];
        $refresh_token_arr['manager_refresh_token'] = $token_arr['manager_refresh_token'];
        unset($refresh_token_arr['id']);
        unset($refresh_token_arr['time']);
        $result['data'] = $refresh_token_arr;
        return $result;
    }

    /**
     * @验证当前token是否有效
     *
     * @return boolean
     * @author: zsl
     * @since: 2019/5/8 15:03
     */
    public function isLogin()
    {
        $user_id = $this -> getManagerId();
        return !!$user_id;
    }


    /**
     * @获取当前登录用户信息
     *
     * @author: zsl
     * @since: 2021/2/25 16:46
     */
    public function detail()
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $managerId = $this -> getManagerId();
        $lStaff = new Staff();
        $detail = $lStaff -> detail(['id' => $managerId]);
        $result['data'] = $detail ? $detail : [];
        return $result;
    }


    /**
     * @更新当前登录用户基础信息
     *
     * @author: zsl
     * @since: 2021/2/25 18:01
     */
    public function saveInfo($param = [])
    {
        $result = ['code' => 200, 'msg' => '修改成功', 'data' => []];
        $param['id'] = $this -> getManagerId();
        $validate = new vManager();
        if (!$validate -> scene('updateManager') -> check($param)) {
            $result['code'] = 1001;
            $result['msg'] = $validate -> getError();
            return $result;
        }
        $mManager = new mManager();
        $mManager -> id = $param['id'];
        $mManager -> realname = $param['realname'];
        $mManager -> mobile = $param['mobile'];
        $mManager -> qq = $param['qq'];
        $mManager -> duty = $param['duty'];
        $mManager -> nickname = $param['nickname'];
        $res = $mManager -> isUpdate(true) -> save();
        if (false === $res) {
            $result['code'] = 5003;
            $result['msg'] = $this -> errorCode(5003);
            return $result;
        }
        return $result;
    }

    /**
     * @保存当前登录用户银行卡信息
     *
     * @author: zsl
     * @since: 2021/2/25 19:54
     */
    public function saveBankInfo($param = [])
    {
        $result = ['code' => 200, 'msg' => '修改成功', 'data' => []];
        $param['id'] = $this -> getManagerId();
        if (empty($param['is_type']) || $param['is_type'] == '1') {
            $scene = 'updateBank'; //银行信息
        } else {
            $scene = 'updateAlipay'; //支付宝
        }
        $validate = new vManagerBank();
        if (!$validate -> scene($scene) -> check($param)) {
            $result['code'] = 1001;
            $result['msg'] = $validate -> getError();
            return $result;
        }
        $mManagerBank = new mManagerBank();
        $bankInfo = $mManagerBank -> where(['manager_id' => $param['id']]) -> find();
        $saveData['manager_id'] = !empty($param['id']) ? $param['id'] : '';
        $saveData['is_type'] = !empty($param['is_type']) ? $param['is_type'] : '';
        $saveData['mobile'] = !empty($param['mobile']) ? $param['mobile'] : '';
        $saveData['card_num'] = !empty($param['card_num']) ? $param['card_num'] : '';
        $saveData['bank_name'] = !empty($param['bank_name']) ? $param['bank_name'] : '';
        $saveData['card_name'] = !empty($param['card_name']) ? $param['card_name'] : '';
        $saveData['province'] = !empty($param['province']) ? $param['province'] : '';
        $saveData['city'] = !empty($param['city']) ? $param['city'] : '';
        $saveData['district'] = !empty($param['district']) ? $param['district'] : '';
        $saveData['branch'] = !empty($param['branch']) ? $param['branch'] : '';
        $saveData['alipay_account'] = !empty($param['alipay_account']) ? $param['alipay_account'] : '';
        $saveData['alipay_name'] = !empty($param['alipay_name']) ? $param['alipay_name'] : '';
        if (empty($bankInfo)) {
            $res = $mManagerBank -> isUpdate(false) -> save($saveData);
        } else {
            $res = $mManagerBank -> isUpdate(true) -> save($saveData, ['manager_id' => $param['id']]);
        }
        if (false === $res) {
            $result['code'] = 5003;
            $result['msg'] = $this -> errorCode(5003);
            return $result;
        }
        return $result;
    }


    /**
     * @修改密码
     *
     * @author: zsl
     * @since: 2019/5/18 10:19
     */
    public function modifypassword($param)
    {
        $result = ['code' => 200, 'msg' => '修改成功', 'data' => []];
        $vManager = new vManager();
        if (!$vManager -> scene('modifypassword') -> check($param)) {
            $result['code'] = 5001;
            $result['msg'] = $vManager -> getError();
            return $result;
        }
        $mManager = new mManager();
        $managerId = $this -> getManagerId();
        $field = 'id,name,nickname,mobile,password,status';
        $managerInfo = $mManager -> field($field) -> where('id', '=', $managerId) -> find();
        if (empty($managerInfo) || data_encrypt($param['old_password']) != $managerInfo -> password) {
            $result['code'] = 5002;
            $result['msg'] = $this -> errorCode(5002);
            return $result;
        }
        if ($param['old_password'] == $param['password']) {
            $result['code'] = 5008;
            $result['msg'] = $this -> errorCode(5008);
            return $result;
        }
        $managerInfo -> password = data_encrypt($param['password']);
        $managerInfo -> save();
        try {
            //发送短信
            if (!empty($managerInfo -> mobile)) {
                $service_mobile = get_option('sms_info')['service_mobile'];
                if (!empty($service_mobile)) {
                    $sendData = [
                            'account' => $managerInfo -> name,
                            'datetime' => date("m-d H:i:s"),
                            'number' => $service_mobile,
                    ];
                    send_change_password_msg($managerInfo -> mobile, json_encode($sendData));
                }
            }
        } catch (\Exception $e) {
            $result['e_info'] = $e -> getMessage();
        }
        return $result;
    }


    /**
     * @修改用户头像
     *
     * @author: zsl
     * @since: 2019/6/10 11:52
     */
    public function modifyavatar($param)
    {
        $result = ['code' => 200, 'msg' => '修改成功', 'data' => []];
        $managerId = $this -> getManagerId();
        $lStaff = new Staff();
        $mManager = $lStaff -> detail(['id' => $managerId]);
        try {
            $mManager -> avatar = $param['avatar'];
            $mManager -> save();
        } catch (\Exception $e) {
            $result['code'] = 5003;
            $result['msg'] = $this -> errorCode(5003);
        }
        return $result;
    }

    /**
     * @修改二级密码
     *
     * @author: zsl
     * @since: 2021/2/26 9:35
     */
    public function modifyVerifyPassword($param)
    {
        $result = ['code' => 200, 'msg' => '修改成功', 'data' => []];
        $vManager = new vManager();
        if (!$vManager -> scene('modifyVerifyPassword') -> check($param)) {
            $result['code'] = 5001;
            $result['msg'] = $vManager -> getError();
            return $result;
        }
        $mManager = new mManager();
        $managerId = $this -> getManagerId();
        $field = 'id,name,nickname,mobile,verify_password,status';
        $managerInfo = $mManager -> field($field) -> where('id', '=', $managerId) -> find();
        if (empty($managerInfo)) {
            $result['code'] = 4004;
            $result['msg'] = $this -> errorCode(4004);
            return $result;
        }
        try {
            $managerInfo -> verify_password = data_encrypt($param['verify_password']);
            $managerInfo -> save();
        } catch (\Exception $e) {
            $result['code'] = 5003;
            $result['msg'] = $this -> errorCode(5003);
        }
        return $result;
    }

    private function errorCode($code)
    {
        $errorCode = [
                1001 => '',
                1002 => '身份验证失败',
                1003 => '密码错误',
                1004 => '此账户还未激活，请联系管理员',
                4001 => '',
                4002 => '添加管理员失败',
                4003 => '缺少管理员标识',
                4004 => '管理员不存在或已被删除',
                4005 => '管理员权限修改成功',
                4006 => '修改管理员失败',
                4007 => '管理员启用失败',
                4008 => '管理员禁用失败',
                4009 => '管理员删除失败',
                5001 => '',
                5002 => '旧密码不正确',
                5003 => '修改失败',
                5004 => '该账号角色被禁用，请联系管理员',
                5005 => '账号不存在或被禁用',
                5006 => '该账号所在公会被禁用，请联系管理员',
                5007 => '该账号所在部门被禁用，请联系管理员',
                5008 => '新密码不能和旧密码相同',
        ];
        return empty($errorCode[$code]) ? '系统繁忙,请稍候再试' : $errorCode[$code];
    }

}
