<?php
namespace app\workerapi\logic;

use app\adminapi\logic\training\TrainingBlockConfigLogic;
use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\enum\YesNoEnum;
use app\common\logic\BaseLogic;
use app\common\model\bank_account\BankAccount;
use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker\MasterWorkerAccountLog;
use app\common\model\master_worker\MasterWorkerAgree;
use app\common\model\master_worker\MasterWorkerInfo;
use app\common\model\master_worker_register\MasterWorkerRegister;
use app\common\model\master_worker\MasterWorkerQuestion;
use app\common\model\master_worker\MasterWorkerInterview;
use app\common\model\training\TrainingWorkerTask;
use app\common\model\works\ServiceWork;
use app\common\service\FileService;
use app\workerapi\service\MasterWokerTaskRequiredService;
use think\Exception;
use think\facade\Config;
use think\facade\Log;
use think\facade\Db;


/**
 * @author 林海涛
 * @date 2024/7/10 下午1:45
 */
class MasterWorkerLogic extends  BaseLogic
{
    public static function changePassword(array $params, int $userId)
    {
        try {

            $user = MasterWorker::findOrEmpty($userId);
            if ($user->isEmpty()) {
                throw new \Exception('用户不存在');
            }
            // 密码盐
            $passwordSalt = Config::get('project.unique_identification');
            /*if (!empty($user['password'])) {
                if (empty($params['old_password'])) {
                    throw new \Exception('请填写旧密码');
                }
                $oldPassword = create_password($params['old_password'], $passwordSalt);
                if ($oldPassword != $user['password']) {
                    throw new \Exception('原密码不正确');
                }
            }*/
            // 保存密码
            $password = create_password($params['password'], $passwordSalt);
            $user->password = $password;
            $user->save();
            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function changeMobile(array $params, int $userId)
    {
        try {
            $user = MasterWorker::findOrEmpty($userId);
            if ($user->isEmpty()) {
                throw new \Exception('用户不存在');
            }
            if($user->mobile == $params['mobile']){
                throw new \Exception('输入的手机号相同');
            }
            $where = [['mobile', '=', $params['mobile']]];
            $existUser = MasterWorker::where($where)->findOrEmpty();
            if (!$existUser->isEmpty()) {
                throw new \Exception('该手机号已被使用');
            }
            $user->mobile= $params['mobile'];
            $user->save();

            //更新注册表手机号
            MasterWorkerRegister::where('worker_id',$userId)->update(['mobile'=>$params['mobile']]);
            //更新师傅信息表手机号
            MasterWorkerInfo::where('worker_id',$userId)->update(['mobile'=>$params['mobile']]);

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

    public static function logOff(int $userId)
    {
        try {
            $user = MasterWorker::findOrEmpty($userId);
            if ($user->isEmpty()) {
                throw new \Exception('用户不存在');
            }
            if($user->work_status == 0 ){
                throw new Exception('请先申请长期停单');
            }
            if($user->work_status == 1 ){
                throw new Exception('请等待长期停单审核');
            }
            $user->is_disable = YesNoEnum::YES;
            $user->save();
            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function stopWork(int $userId)
    {
        try {
            $user = MasterWorker::findOrEmpty($userId);
            if ($user->isEmpty()) {
                throw new \Exception('用户不存在');
            }
            if($user->work_status == 1 ){
                throw new Exception('请等待长期停单审核');
            }
            if($user->work_status == 2 ){
                throw new Exception('长期停单审核通过');
            }
            $user->work_status = 1;
            $user->accept_order_status = 0;
            $user->save();
            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

     public static function detail($userId): array
    {
        $worker = MasterWorker::field('id,team_id,team_role,sn,avatar,real_avatar,real_name,nickname,account,mobile,sex,estimate_money,user_money,earnest_money,exp,worker_number,work_status,accept_order_status,identity_source')
            ->findOrEmpty($userId)
            ->toArray();

        //验证是否上传身份证
        $is_id_card = MasterWorkerInfo::where('worker_id',$userId)->whereIn('audit_state','0,1')->findOrEmpty()->toArray();

        //判断是否填写银行信息
        $is_bank = BankAccount::where('worker_id',$userId)->whereIn('audit_state','0,1')->findOrEmpty()->toArray();

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

        $worker['is_id_card'] = !empty($is_id_card)?1:0;
        $worker['is_bank']  =   !empty($is_bank)?1:0;
        $worker['is_service_agree'] = !empty($pdf)?1:0;

        //今日退款
        $worker['refund_account_today'] = MasterWorkerAccountLog::where(['worker_id'=> $worker['id'],'action'=>2,'change_type'=>WorkerAccountLogEnum::UM_DEC_ADMIN])->whereTime('create_time', 'today')->sum('change_amount');
         //今日收益
        $worker['account_today'] = MasterWorkerAccountLog::where(['worker_id'=> $worker['id'],'action'=>1,'change_type'=>WorkerAccountLogEnum::UM_INC_ADMIN])->whereTime('create_time', 'today')->sum('change_amount')-$worker['refund_account_today'];
        //本月成功订单
        $worker['success_work'] = ServiceWork::where(['master_worker_id'=>$worker['id'],'service_status'=>3])->whereTime('create_time', 'month')->count();
        //本月失败单
        $worker['fail_work'] = ServiceWork::where(['master_worker_id'=>$worker['id']])->whereIn('service_status','4,5')->whereTime('create_time', 'month')->count();

        // 该工程师所有必须任务是否完成
        $worker['task_required'] = MasterWorkerLogic::taskRequired($worker['id'],$worker['identity_source'])?1:0;

        return $worker;
    }

    public static function setInfo(int $userId, array $params)
    {
        try {
            if ($params['field'] == "avatar" || $params['field'] == "real_avatar") {
                $params['value'] = FileService::setFileUrl($params['value']);
            }

            $upData = [
                'id' => $userId,
                $params['field'] => $params['value']
            ];
            if($params['field'] == 'accept_order_status'){
                $masterWorker = MasterWorker::where(['id'=>$userId])->findOrEmpty();
                if($masterWorker['work_status'] != 0 || $masterWorker['is_disable'] != 0){
                    throw new Exception('该账号已禁用或已长期停单');
                }
                $accept_status_time = $masterWorker['accept_status_time'];
                if($masterWorker['accept_order_status'] ==1 && $params['value'] == 0 && $accept_status_time > 0){
                    if(time() < ($accept_status_time+2*3600)){
                        throw new Exception('开启接单后两小时后才能关闭接单');
                    }
                }
                $upData['accept_status_time'] = time();
                //验证身份证信息是否审核通过
                $idCard = MasterWorkerInfo::where(['worker_id'=>$userId])->findOrEmpty();
                if ($idCard->isEmpty()) {
                    return ['code'=>20,'msg'=>'请先完善身份证信息'];
                }
                if($idCard->audit_state == 0){
                    return ['code'=>20,'msg'=>'身份证信息核验中，请等待核验完成'];
                }
                if($idCard->audit_state == 2){
                    return ['code'=>20,'msg'=>'身份证信息核验不通过，请重新填写'];
                }
                //验证银行卡信息是否审核通过
                $bank = BankAccount::where(['worker_id'=>$userId])->findOrEmpty();
                if ($bank->isEmpty()) {
                    return ['code'=>21,'msg'=>'请先完善银行卡信息'];
                }
                if($bank->audit_state == 0){
                    return ['code'=>21,'msg'=>'银行卡信息核验中，请等待核验完成'];
                }
                if($bank->audit_state == 2){
                    return ['code'=>21,'msg'=>'银行卡信息核验不通过，请重新填写'];
                }
                //验证协议信息是否审核通过
                $agree = MasterWorkerAgree::where(['worker_id'=>$userId])->findOrEmpty();
                if ($agree->isEmpty()) {
                    return ['code'=>22,'msg'=>'请先签写协议信息'];
                }
                if($agree->audit_state == 0){
                    return ['code'=>22,'msg'=>'协议信息核验中，请等待核验完成'];
                }
                if($agree->audit_state == 2){
                    return ['code'=>22,'msg'=>'协议信息核验不通过，请重新签写'];
                }

                // 该工程师所有必须任务是否完成
                if(!self::taskRequired($userId,$masterWorker['identity_source'])){
                    return ['code'=>23,'msg'=>'培训中心必须任务未完成'];
                }

            }

            MasterWorker::update($upData);
            return [];
        } catch (\Exception $e) {
            self::$error = $e->getMessage();
            self::$returnCode = $e->getCode();
            return false;
        }
    }

    public static function taskRequired($userId,$identity_source): bool
    {

        /*[{"block_key":1,"type":"shop_goods_id","type_value":1,"res_name":"operate_status","execute_function":"shop_goods","is_must":false},
        {"block_key":2,"type":"training_task_id","type_value":1,"res_name":"operate_status","execute_function":"operateStatus","is_must":true},
        {"block_key":3,"type":"task_list","type_value":["1","2","4"],"res_name":"operate_status","execute_function":"operateStatus","is_must":false}]*/


        $trainingWorkerTask = TrainingWorkerTask::where(['master_worker_id'=>$userId])->findOrEmpty();
        if($trainingWorkerTask->isEmpty()){
            return true;
        }
        $configs = TrainingBlockConfigLogic::getRequiredConfig($identity_source);
        foreach ($configs as $item) {
            if($item['is_must']){
                Log::info('taskRequired-1'.json_encode($item));
                if(empty($item['execute_function'])) continue;
                if(!class_exists(\app\workerapi\service\MasterWokerTaskRequiredService::class)){
                    continue;
                }
                if(!method_exists(\app\workerapi\service\MasterWokerTaskRequiredService::class,$item['execute_function'])){
                    continue;
                }
                $execute_function = $item['execute_function'];
                $res = (new MasterWokerTaskRequiredService())::$execute_function($userId);
                Log::info('taskRequired-2:'.$userId.'-'.$item['execute_function'].'-'.$res);
                if($res === false){
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 查询机器人面试结果
     */
    public static function getInterview(array $params)
    {
        if (empty($params['worker_id'])) {
            return false;
        }
        $info = MasterWorkerInterview::where('worker_register_id',$params['worker_id'])
                    ->field('id,worker_register_id,type,status,create_time')
                    ->findOrEmpty()
                    ->toArray();
        return $info;
    }
    /**
     * 机器人面试结果
     */
    public static function setInterview(array $params)
    {
        try {
            
            if (empty($params['worker_register_id']) || empty($params['answer']) || empty($params['answer1']) || empty($params['answer2']) ) {
                return false;
            }
            if (!empty($params['answer7'])) {
                //维修
                $type = 1;
            } else if (!empty($params['answer6'])) {
                //清洗
                $type = 2;
            } else if (!empty($params['answer5'])) {
                //安装
                $type = 3;
                $params['status'] = 1;
            } else {
                $type = 0;
                $params['status'] = 0;
            }

            //校验一下工程师注册ID是否有效
            $worker_register_id = $params['worker_register_id'];
            $worker_register_id = MasterWorkerRegister::where('id',$worker_register_id)->value('id');
            if (!$worker_register_id) {
                return false;
            }

            $info = MasterWorkerInterview::where('worker_register_id',$params['worker_register_id'])->value("id");
            if ($info) {
                return false;
            }
            $params['nickname'] = isset($params['nickname']) ?? '';
            $insertData = [
                'sys_uuid' => $params['sys_uuid'],
                'worker_register_id' => $params['worker_register_id'],
                'nickname' => $params['nickname'],
                'type' => $type,
                'status' => $params['status'],
            ];
            unset($params['sys_uuid']);
            unset($params['worker_register_id']);
            unset($params['nickname']);
            unset($params['status']);
            $insertData['content'] = json_encode($params);

            Db::startTrans();

            MasterWorkerInterview::create($insertData);
            MasterWorkerRegisterLogic::createMasterWorker(['worker_register_id' => $worker_register_id]);

            Db::commit();
            return [];
        } catch (\Exception $e) {
            Db::rollback();
            self::$error = $e->getMessage();
            self::$returnCode = $e->getCode();
            return false;
        }
    }

    /**
     * 查询工程师面试题库
     */
    public static function getQuestion(array $params)
    {
        if ($params['type'] == 1 || $params['type'] == 2) {

            $category = trim($params['category']);
            $category = str_replace('，', ',', $category);
            $category = explode(',', $category);
            $category = array_slice($category, 0, 5);
            $list = MasterWorkerQuestion::where('type',$params['type'])
                        ->whereIn('category', $category)
                        ->where('type',$params['type'])
                        ->where('question_type','<>',2)
                        ->limit(100)
                        ->select()
                        ->toArray();
            // 按 category 分组
            $grouped = [];
            foreach ($list as $item) {
                $category = $item['category'];
                if (!isset($grouped[$category])) {
                    $grouped[$category] = [];
                }
                $grouped[$category][] = $item;
            }

            // 从每组中随机取 5 个元素
            $result = [];
            foreach ($grouped as $category => $items) {
                $randomItems = [];
                $count = count($items);
                if ($count <= 5) {
                    $randomItems = $items;
                } else {
                    $keys = array_rand($items, 5);
                    foreach ($keys as $key) {
                        $randomItems[] = $items[$key];
                    }
                }
                $result = array_merge($result,$randomItems);
            }
            $text = '';
            $i = 0;
            foreach($result as $item) {
                $i++;
                $text .= $i.'.'.$item['title']."\r\n"."  ". str_replace(",","\r\n",$item['options'])."\r\n\r\n";
            }
            return [
                'list' => array_values($result),
                'text' => $text
            ];
        } 
        return false;
    }
    public static function getRegInfo(array $params)
    {
        if (empty($params['user'])){
            return 0;
        }
        $user = trim($params['user']);
        $pattern = '/(\d{11})/';
        if (preg_match($pattern, $user, $matches)) {
            // 提取手机号
            $mobile = $matches[1];
        } 

        $specialChars = array('.', ',', '。', '，', $mobile);
        $name = str_replace($specialChars,"",$user);
        return (int)MasterWorkerRegister::where('name',$name)->where('mobile',$mobile)->value('id');
    }
    
}
