<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\works;


use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\logic\RetentionMoneyLogic;
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\MasterWorkerRetentionMoneyLog;
use app\common\model\works\IssueWork;
use app\common\model\works\ReturnWork;
use app\common\logic\BaseLogic;
use app\common\model\works\ServiceWork;
use think\db\Query;
use think\facade\Db;


/**
 * ReturnWork逻辑
 * Class ReturnWorkLogic
 * @package app\adminapi\logic\works
 */
class ReturnWorkLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/10 15:06
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            ReturnWork::create([
                'work_sn' => $params['work_sn'],
                'service_work_id' => $params['service_work_id'],
                'issue_work_id' => $params['issue_work_id'],
                'return_work_status' => $params['return_work_status'],
                'dispatch_time' => $params['dispatch_time'],
                'appointment_time' => $params['appointment_time'],
                'finished_images' => $params['finished_images'],
                'finished_time' => $params['finished_time'],
                'master_worker_id' => $params['master_worker_id'],
            ]);

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


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/10 15:06
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            ReturnWork::where('id', $params['id'])->update([
                'work_sn' => $params['work_sn'],
                'service_work_id' => $params['service_work_id'],
                'issue_work_id' => $params['issue_work_id'],
                'return_work_status' => $params['return_work_status'],
                'dispatch_time' => $params['dispatch_time'],
                'appointment_time' => $params['appointment_time'],
                'finished_images' => $params['finished_images'],
                'finished_time' => $params['finished_time'],
                'master_worker_id' => $params['master_worker_id'],
            ]);

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


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/10 15:06
     */
    public static function delete(array $params): bool
    {
        return ReturnWork::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/07/10 15:06
     */
    public static function detail($params): array
    {
        if(isset($params['issue_work_id'])){
            return ReturnWork::with(['worker'=>function(Query $query) {
                $query->field("id,worker_number,real_name");
            },])->where('issue_work_id',$params['issue_work_id'])->append(['return_work_status_text'])->findOrEmpty()->toArray();
        }
        return ReturnWork::with(['worker'=>function(Query $query) {
            $query->field("id,worker_number,real_name");
        },])->append(['return_work_status_text'])->findOrEmpty($params['id'])->toArray();
    }


    public static function issueWorkData($params)
    {
        Db::startTrans();
        try {
            $model = ReturnWork::where('issue_work_id',$params['issue_work_id'])->findOrEmpty();
            $flag = true;
            if($model->isEmpty()){
                $flag = false;
                $model = new ReturnWork();
            } else {
                if($model->return_work_status !== 0){
                    //throw new \Exception('返修工单状态非待返修，无法修改'); 1111内测要求放开
                }
            }
            $issueWork = IssueWork::findOrEmpty($params['issue_work_id']);
            if($issueWork->isEmpty()){
                throw  new  \Exception('投诉工单不存在');
            }
            if($issueWork->complaint_status == 4){
                throw new \Exception('投诉工单投诉状态为已完结，无需生成返修工单');
            }
            $model->work_sn = generate_sn(ReturnWork::class,'work_sn');
            $model->service_work_id = $issueWork->service_work_id;
            $model->issue_work_id = $issueWork->id;
            if(empty($model->dispatch_time)){
                $model->dispatch_time = time();
            }
            $model->appointment_time = strtotime($params['appointment_time']);
            if($flag){
                MasterWorker::setWorktotal('dec',$model->master_worker_id);
            }
            $model->master_worker_id = $params['master_worker_id'];
            MasterWorker::setWorktotal('inc', $params['master_worker_id']);
            $model->user_id = $issueWork->user_id;
            $model->save();

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