<?php
namespace app\api\logic;
use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\logic\BaseLogic;
use app\common\logic\WorkerAccountLogLogic;
use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker\MasterWorkerAccountLog;
use app\common\model\master_worker\MasterWorkerFreezeAmountLog;
use app\common\model\master_worker\MasterWorkerRetentionMoneyLog;
use app\common\model\works\IssueWork;
use app\common\model\works\ReturnWork;
use app\common\model\works\ServiceWork;
use think\db\Query;
use think\facade\Db;

/**
 * @author 林海涛
 * @date 2024/7/29 下午4:26
 */
class ReturnWorkLogic extends BaseLogic
{
    public static function lists($params)
    {
        return ReturnWork::with(['serviceWork'=>function(Query $query){
            $query->field('id,address,title');
        }])
            ->where('user_id',$params['user_id'])
            ->field(['id', 'work_sn','service_work_id','return_work_status','dispatch_time','create_time','appointment_time'])
            ->append(['return_work_status_text'])
            ->order(['id' => 'desc'])
            ->select()
            ->toArray();
    }

    public static function detail($params)
    {
        $issue_work = ReturnWork::with(['serviceWork'=>function(Query $query){
            $query->field('id,address,title,real_name,mobile');
        },'worker'=>function(Query $query){
            $query->field('id,avatar,real_name,worker_number,mobile');
        }])
           ->where(['id'=>$params['id'],'user_id'=>$params['user_id']])
            ->where(['id'=>$params['id']])
            ->field('id,work_sn,service_work_id,return_work_status,dispatch_time,master_worker_id,create_time,appointment_time,finished_images')
            ->append(['return_work_status_text'])
            ->findOrEmpty()->toArray();
        return $issue_work;
    }

    public static function confirmFinish($params):bool
    {
        Db::startTrans();
        try{
            $work = ReturnWork::where('work_sn',$params['work_sn'])->findOrEmpty();
            if($work->isEmpty()){
                throw new \Exception('返修工单不存在');
            }
            if($work->user_id != $params['user_id']){
                throw new \Exception('用户不正确');
            }
            if($work->return_work_status != 3){
                throw new \Exception('等待工程师确认服务完成');
            }
            $work->return_work_status = 4;
            $work->save();
            MasterWorker::setWorktotal('inc',$work->master_worker_id);
            //更新投诉状态
            $issueWork = IssueWork::where('service_work_id',$work->service_work_id)->findOrEmpty();
            if(!$issueWork->isEmpty()){

                // 投诉完成-质保金可用金额 解冻
                if($issueWork->issue_approval != 4 &&  $issueWork->is_refunded_payment == 1){
                    $serviceWork = ServiceWork::where('id',$issueWork->service_work_id)->findOrEmpty();
                    if(!$serviceWork->isEmpty()){
                        $is_zero = false;
                        // 查询出该投诉的冻结金额 master_worker_freeze_amount_log  issue_work_id master_worker_id
                        $amount = MasterWorkerFreezeAmountLog::where([
                            'action'=>WorkerAccountLogEnum::INC,'source'=>1,
                            'issue_work_id'=>$issueWork->id,'master_worker_id'=>$issueWork->master_worker_id])->value('amount');

                        // 是否存在返修工单？
                        $work = ReturnWork::where('issue_work_id',$issueWork->id)->findOrEmpty();
                        if(!$work->isEmpty()){
                            // 最新师傅
                            if($issueWork->master_worker_id != $work->master_worker_id){
                                // 加账户余额 收益
                                $change_amount = MasterWorkerAccountLog::where([
                                    'change_object'=>WorkerAccountLogEnum::UM,'change_type'=>WorkerAccountLogEnum::UM_INC_ADMIN,
                                    'action'=>WorkerAccountLogEnum::INC,'worker_id'=>$issueWork->master_worker_id,
                                    'work_sn'=>$issueWork->work_sn])->value('change_amount');
                                // 存在则按返修工单中的最新师傅 计算收益
                                $extra['ReturnWorkInfo'] = ['id'=>$work->id,'master_worker_id'=>$work->master_worker_id,'service_work_id'=>$work->service_work_id,'issue_work_id'=>$work->issue_work_id];
                                $remark = '工单号：'.$issueWork->work_sn.'，返修单号：'.$work->work_sn.'，收益金额：'.$change_amount.'，原因：返修工单新工程师收益';
                                WorkerAccountLogLogic::addAccountLog($serviceWork,$change_amount,WorkerAccountLogEnum::UM_INC_ADMIN,WorkerAccountLogEnum::INC,$remark,$extra,$work->master_worker_id);
                                $is_zero = true;
                            }
                        }
                        /*to_freeze source remark work_id amount  worker_id issue_work_id*/
                        // 对原工程师的 质保金解冻质保金 / 清零
                        \app\common\logic\RetentionMoneyLogic::warrantyDepositRelease([
                            'to_freeze'=>2,
                            'source'=>1,
                            'remark'=>'对原工程师的质保金解冻质保金/清零',
                            'work_id'=>$work->service_work_id,'worker_id'=>$issueWork->master_worker_id,
                            'issue_work_id'=>$issueWork->id,
                            'amount'=>$amount,
                        ],$is_zero);
                    }
                }

                $issueWork->issue_approval = 4;
                $issueWork->complaint_status = 2;
                $issueWork->responsible = 2;
                $issueWork->finished_time = time();
                $issueWork->save();
            }

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