<?php
namespace app\workerapi\logic;
use app\common\model\works\ReturnWork;
use app\common\logic\BaseLogic;
use think\facade\Db;


/**
 * ReturnWork逻辑
 * Class ReturnWorkLogic
 * @package app\workerapi\logic\works
 */
class ReturnWorkLogic extends BaseLogic
{
    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author whitef
     * @date 2024/07/10 15:06
     */
    public static function detail($params): array
    {
        return ReturnWork::with(['service_work'=>function ($query) {
        }])->findOrEmpty($params['id'])->toArray();
    }


    /**
     * 工程师预约上门时间
     * @param $params
     * @return bool
     * @author 林海涛
     * @date 2024/7/30 上午10:50
     */
    public static function appointWork($params):bool
    {
        Db::startTrans();
        try {
            $work = ReturnWork::findOrEmpty($params['id']);
            if($work->isEmpty()){
                throw new \Exception('工单信息不存在');
            }
            if($work->return_work_status !== 0){
                throw new \Exception('工单状态不正确');
            }
            $work->appointment_time = strtotime($params['appointment_time']);
            $work->return_work_status = 1;
            $work->save();
            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 工程师确认上门
     * @param $params
     * @return bool
     * @author 林海涛
     * @date 2024/7/30 上午10:52
     */
    public static function confirmDoor($params):bool
    {
        Db::startTrans();
        try {
            $work = ReturnWork::where('work_sn',$params['work_sn'])->findOrEmpty();
            if($work->isEmpty()){
                throw new \Exception('工单信息不存在');
            }
            if($work->return_work_status !== 1 ){
                throw new \Exception('工单状态不正确');
            }
            $work->return_work_status = 2;
            $work->save();
            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 修改工单
     * @param $params
     * @return false|void
     */
    public static function updateReturn($params):bool
    {
        Db::startTrans();
        try {
            $work = ReturnWork::findOrEmpty($params['id']);
            if($work->isEmpty()){
                throw new \Exception('工单信息不存在');
            }
            if($work->return_work_status !== 2 ){
                throw new \Exception('工单状态不正确');
            }
            $work->return_work_status = 3;
            $work->finished_images = $params['finished_images'];
            $work->finished_time = time();
            $work->save();
            Db::commit();
           return true;
        }catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }
}