<?php
namespace app\workerapi\logic;
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\works\ServiceWork;
use app\common\service\FileService;
use think\Exception;
use think\facade\Config;

/**
 * @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();
            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,sn,avatar,real_avatar,real_name,nickname,account,mobile,sex,estimate_money,user_money,earnest_money,exp,worker_number,work_status,accept_order_status')
            ->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();
        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'=>'协议信息核验不通过，请重新签写'];
                }
            }

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