<?php
namespace app\api\logic;
use app\common\logic\BaseLogic;
use app\common\model\master_worker\MasterWorker;
use app\common\model\works\ReturnWork;
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')
            ->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);
            Db::commit();
            return true;
        }catch(\Exception $e){
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
}