<?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\MasterWorkerAccountLog;
use app\common\model\master_worker\MasterWorkerFreezeAmountLog;
use app\common\model\works\IssueWork;
use app\common\logic\BaseLogic;
use app\common\model\works\ReturnWork;
use app\common\model\works\ServiceWork;
use think\facade\Db;
use think\facade\Log;


/**
 * IssueWork逻辑
 * Class IssueWorkLogic
 * @package app\adminapi\logic\works
 */
class IssueWorkLogic 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 {
            IssueWork::create([
                'work_sn' => $params['work_sn'],
                'service_work_id' => $params['service_work_id'],
                'master_worker_id' => $params['master_worker_id'],
                'issue_approval' => $params['issue_approval'],
                'complaint_status' => $params['complaint_status'],
                'responsible' => $params['responsible'],
                'complaint_details' => $params['complaint_details'],
                'complaint_images' => $params['complaint_images'],
                'finished_time' => strtotime($params['finished_time']),
                'approval_admin_id' => $params['approval_admin_id'],
                'approval_time' => strtotime($params['approval_time']),
            ]);

            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 {
            $issueWork = IssueWork::where('id', $params['id'])->findOrEmpty();
            IssueWork::where('id', $params['id'])->update([
                'work_sn' => $params['work_sn'],
                'service_work_id' => $params['service_work_id'],
                'master_worker_id' => $params['master_worker_id'],
                'issue_approval' => $params['issue_approval'],
                'complaint_status' => $params['complaint_status'],
                'responsible' => $params['responsible'],
                'complaint_details' => $params['complaint_details'],
                'complaint_images' => $params['complaint_images'],
                'finished_time' => strtotime($params['finished_time']),
                'approval_admin_id' =>$params['approval_admin_id'],
                'approval_time' => time(),
            ]);

            Log::info('IssueWorkLogic-edit-error:'.$issueWork);
            // 投诉- 非完成状态时工程师的质保金可用金额 被冻结
            if(!in_array($issueWork->issue_approval,[5,4]) && $issueWork->is_refunded_payment == 0 && !in_array($params['issue_approval'],[5,4])){
                if(RetentionMoneyLogic::warrantyDepositFreeze($issueWork)){
                    // 原工程师返修收成款是否被冻结 is_refunded_payment
                    $issueWork->is_refunded_payment = 1;
                    $issueWork->save();
                }
            }

            // 投诉完成-质保金可用金额 解冻
            if($issueWork->issue_approval != 4 &&  $issueWork->is_refunded_payment == 1 && $params['issue_approval'] == 4){
                $serviceWork = ServiceWork::where('id',$issueWork->service_work_id)->findOrEmpty();
                if(!$serviceWork->isEmpty()){
                    // 查询出该投诉的冻结金额 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()){
                        $work->finished_time = time();
                        $work->return_work_status = 4;
                        $work->save();
                    }
                    /*to_freeze source remark work_id amount  worker_id issue_work_id*/
                    // 对原工程师的 质保金解冻质保金 / 清零
                    RetentionMoneyLogic::warrantyDepositRelease([
                        'to_freeze'=>2,
                        'source'=>1,
                        'remark'=>'对原工程师的质保金解冻质保金/清零',
                        'work_id'=>$issueWork->service_work_id,'worker_id'=>$issueWork->master_worker_id,
                        'issue_work_id'=>$issueWork->id,
                        'amount'=>$amount,
                    ],false);
                }
            }

            Db::commit();
            // 受理中向工程师发微信通知
            if((int)$params['issue_approval'] === 1){
                $workDetail = ServiceWorkLogic::detail(['id'=>$issueWork->service_work_id]);
                event('Notice',  [
                    'scene_id' => 127,
                    'params' => [
                        'user_id' => $issueWork->master_worker_id,
                        'order_id' => $issueWork->service_work_id,
                        'thing13' => '投诉工单-'.$workDetail['title'],
                        'character_string2' => $workDetail['work_sn'],
                        'thing9' => $workDetail['real_name'],
                        'phone_number15' => asteriskString($workDetail['mobile']),
                    ]
                ]);
            }
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            Log::info('IssueWorkLogic-edit-error:'.$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 IssueWork::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/07/10 15:06
     */
    public static function detail($params): array
    {
        return IssueWork::with(['masterWorker','user'])->append(['complaint_type_text'])->findOrEmpty($params['id'])->toArray();
    }
}