<?php
namespace app\workerapi\logic;
use app\common\enum\LoginEnum;
use app\common\enum\notice\NoticeEnum;
use app\common\enum\user\UserTerminalEnum;
use app\common\logic\BaseLogic;
use app\common\model\master_worker\BankAccount;
use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker\MasterWorkerAgree;
use app\common\model\master_worker\MasterWorkerAuth;
use app\common\model\master_worker\MasterWorkerInfo;
use app\common\model\master_worker_register\MasterWorkerRegister;
use app\common\service\FileService;
use app\common\service\sms\SmsDriver;
use app\common\service\wechat\WeChatMnpService;
use app\common\service\wechat\WorkerWeChatMnpService;
use think\facade\Config;
use app\workerapi\service\MasterWokerTokenService;
use think\facade\Log;

/**
 * @author 林海涛
 * @date ${DATA}
 */
class LoginLogic extends BaseLogic
{

    /**
     * @notes 确认手机号
     * @param $params
     * @return bool
     * @author 段誉
     * @date 2022/9/21 17:28
     */
    public static function confirmMobile(array $params)
    {
        try {
            // 验证码请求
            $sceneId = NoticeEnum::GCSSJHM_CAPTCHA;
            // 校验短信
            $checkSmsCode = (new SmsDriver())->verify($params['mobile'], $params['code'], $sceneId);
            if (!$checkSmsCode) {
                throw new \Exception('验证码错误');
            }
            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }
    public static function confirmCredential(array $params)
    {
        try {
            if(isset($params['is_credential']) && $params['is_credential'] == 1){
                empty($params['credential_images']) && throw new \Exception('缺少证书');
            }
            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }
    public static function register(array $params)
    {
        try {
            $master = MasterWorkerRegister::where('mobile',$params['mobile'])->findOrEmpty();

            if(!$master->isEmpty() and $master->status==1){
                throw new \Exception('该手机号已入驻');
            }

            if(!$master->isEmpty() and $master->status==0){
                throw new \Exception('该手机号后台审核中');
            }

            if(!$master->isEmpty() and $master->status==2){
                $master->save([
                    'maintain_exp_type' => isset($params['maintain_exp_type'])?$params['maintain_exp_type']:0,
                    'other_exp_type' => isset($params['other_exp_type'])?$params['other_exp_type']:'',
                    'other_exp_name' => (isset($params['other_exp_name']) && isset($params['other_exp_type']) && $params['other_exp_type'] == 4)?$params['other_exp_name']:'',
                    'city' => $params['city'],
                    'vehicle_type' => $params['vehicle_type'],
                    'name' => $params['name'],
                    'age' => $params['age'],
                    'sex' => $params['sex']??0,
                    'mobile' => $params['mobile'],
                    'is_credential' => !empty($params['is_credential'])?$params['is_credential']:0,
                    'credential_name' => !empty($params['credential_name'])?$params['credential_name']:'',
                    'credential_images'=>!empty($params['credential_images'])?json_encode($params['credential_images'],JSON_UNESCAPED_UNICODE):'',
                    'lon' => !empty($params['lon'])?$params['lon']:0,
                    'lat' => !empty($params['lat'])?$params['lat']:0,
                    'address' => !empty($params['address'])?$params['address']:'',
                    'status'=>0
                ]);
            }else{
                MasterWorkerRegister::create([
                    'maintain_exp_type' => isset($params['maintain_exp_type'])?$params['maintain_exp_type']:0,
                    'other_exp_type' => isset($params['other_exp_type'])?$params['other_exp_type']:'',
                    'other_exp_name' => (isset($params['other_exp_name']) && isset($params['other_exp_type']) && $params['other_exp_type'] == 4)?$params['other_exp_name']:'',
                    'city' => $params['city'],
                    'vehicle_type' => $params['vehicle_type'],
                    'name' => $params['name'],
                    'age' => $params['age'],
                    'sex' => $params['sex']??0,
                    'mobile' => $params['mobile'],
                    'is_credential' => !empty($params['is_credential'])?$params['is_credential']:0,
                    'credential_name' => !empty($params['credential_name'])?$params['credential_name']:'',
                    'credential_images'=>!empty($params['credential_images'])?json_encode($params['credential_images'],JSON_UNESCAPED_UNICODE):'',
                    'lon' => !empty($params['lon'])?$params['lon']:0,
                    'lat' => !empty($params['lat'])?$params['lat']:0,
                    'address' => !empty($params['address'])?$params['address']:'',
                ]);
            }


            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function login($params)
    {
        try {
            // 账号/手机号 密码登录
            $where = ['account' => $params['account']];
            if ($params['scene'] == LoginEnum::MOBILE_CAPTCHA) {
                //手机验证码登录
                $where = ['mobile' => $params['account']];
            }

            $user = MasterWorker::where($where)->findOrEmpty();
            if ($user->isEmpty()) {
                $worker_register = MasterWorkerRegister::where('mobile',$params['account'])->findOrEmpty();
                if(!$worker_register->isEmpty() && $worker_register->status==0){
                    throw new \Exception('您的入驻信息正在审核中，客服将在1-2个工作日内联系您进行入驻操作');
                }
                throw new \Exception('请点击下方的工程师入驻');
            }

            //更新登录信息
            $user->login_time = time();
            $user->login_ip = request()->ip();
            $user->save();

            //设置token
            $userInfo = MasterWokerTokenService::setToken($user->id, 1);

            //返回登录信息
            $avatar = $user->avatar ?: Config::get('project.default_image.user_avatar');
            $avatar = FileService::getFileUrl($avatar);

            //验证是否上传身份证
            $is_id_card = MasterWorkerInfo::where('worker_id',$user->id)->findOrEmpty()->toArray();

            //判断是否填写银行信息
            $is_bank = BankAccount::where('worker_id',$user->id)->findOrEmpty()->toArray();

            //监测是否签署服务合作协议
            $pdf = MasterWorkerAgree::where(['agree_type'=>'master_service_content','worker_id'=>$user->id])->whereIn('audit_state','0,1')->value('pdf_url');

            return [
                'nickname' => $userInfo['nickname'],
                'sn' => $userInfo['sn'],
                'mobile' => $userInfo['mobile'],
                'avatar' => $avatar,
                'team_id' => $userInfo['team_id'],
                'team_role' => $userInfo['team_role'],
                'token' => $userInfo['token'],
                'is_id_card'=>!empty($is_id_card)?1:0,
                'is_bank'=>!empty($is_bank)?1:0,
                'is_service_agree'=>!empty($pdf)?1:0
            ];
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function logout($userInfo)
    {
        //token不存在，不注销
        if (!isset($userInfo['token'])) {
            return false;
        }
        //设置token过期
        return MasterWokerTokenService::expireToken($userInfo['token']);
    }

    public static function mnpAuthLogin($params)
    {
        try {
            //通过code获取微信openid
            $response = (new WorkerWeChatMnpService())->getMnpResByCode($params['code']);
            $response['user_id'] = $params['user_id'];
            $response['terminal'] = UserTerminalEnum::WECHAT_MMP;

            return self::createAuth($response);

        } catch (\Exception  $e) {
            self::$error = $e->getMessage();
            return false;
        }
    }

    /**
     * @notes 生成授权记录
     * @param $response
     * @return bool
     * @throws \Exception
     * @author 段誉
     * @date 2022/9/16 10:43
     */
    public static function createAuth($response)
    {
        //判定同一worker_id是否只有一个openid
        $userAuth = MasterWorkerAuth::where(['worker_id' => $response['user_id']])
            ->findOrEmpty();

        if(!$userAuth->isEmpty() && !empty($userAuth->openid) && $userAuth->openid != $response['openid']){
            throw new \Exception('该账号已绑定其他微信');
        }

        //先检查openid是否有记录
        $isAuth = MasterWorkerAuth::where('openid', '=', $response['openid'])->findOrEmpty();

        if (!$isAuth->isEmpty()) {
            if($isAuth->worker_id != $response['user_id']) {
                throw new \Exception('该微信已被绑定');
            }
            if($isAuth->worker_id == 0) {
                //更新操作
                $isAuth->worker_id = $response['user_id'];
                $isAuth->save();
                return true;
            }
            if($isAuth->worker_id == $response['user_id']) {
                return true;
            }
        }

        if (isset($response['unionid']) && !empty($response['unionid'])) {
            //在用unionid找记录，防止生成两个账号，同个unionid的问题
            $userAuth = MasterWorkerAuth::where(['unionid' => $response['unionid']])
                ->findOrEmpty();
            if (!$userAuth->isEmpty() && $userAuth->worker_id != $response['user_id']) {
                throw new \Exception('该微信已被绑定');
            }
        }



        //如果没有授权，直接生成一条微信授权记录
        MasterWorkerAuth::create([
            'worker_id' => $response['user_id'],
            'openid' => $response['openid'],
            'unionid' => $response['unionid'] ?? '',
            'terminal' => $response['terminal'],
        ]);
        return true;
    }
}