<?php
namespace app\api\logic;


use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\logic\WorkerAccountLogLogic;
use app\common\model\dict\DictData;
use app\common\model\master_worker\MasterWorkerAccountLog;
use app\common\model\master_worker\MasterWorkerFreezeAmountLog;
use app\common\model\recharge\RechargeOrder;
use app\common\model\user\User;
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\Exception;
use think\facade\Db;


/**
 * IssueWork逻辑
 * Class IssueWorkLogic
 * @package app\api\logic\works
 */
class IssueWorkLogic extends BaseLogic
{

    /**
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function lists($params)
    {
        return IssueWork::where('user_id',$params['user_id'])
            ->field(['id', 'sn','title', 'issue_approval','create_time','complaint_status','responsible'])
            ->append(['issue_approval_text'])
            ->order(['id' => 'desc'])
            ->select()
            ->toArray();
    }

    /**
     * 检查是否投诉
     * @param array $params
     * @return array|false|int|string
     */
    public static function checkComplaint($params)
    {
        try {
            $data['is_issue'] = 0;
            $data['is_return'] = 0;
            $issue = IssueWork::where(['user_id'=>$params['user_id'],'sn'=>$params['sn']])->findOrEmpty();
            if(!$issue->isEmpty()){
                $data['is_issue'] = 1;
                $data['issue_id'] = $issue['id'];
                $return = ReturnWork::where('service_work_id',$issue->service_work_id)->findOrEmpty();
                if(!$return->isEmpty()){
                    $data['is_return'] = 1;
                    $data['return_id'] = $return['id'];
                }
            }
            return $data;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * 添加
     * @param array $params
     * @return false|int|string
     */
    public static function add(array $params)
    {
        Db::startTrans();
        try {
            $order = RechargeOrder::where(['sn'=>$params['sn'],'user_id'=>$params['user_id']])->findOrEmpty()->toArray();
            if(empty($order)){
                throw new Exception('订单错误');
            }
            $work = ServiceWork::findOrEmpty($order['work_id']);
            if($work['work_status']<7){
                throw new Exception('订单暂未结束，不允许投诉，请直接联系客服');
            }
            // 判断是否投诉时效过期
            if(strtotime($work['finished_time']) < (time()-86400*5)){
                throw new Exception('投诉时效已过');
            }
            $IssueWork = new IssueWork();
            $is_issue_work = $IssueWork->where(['user_id'=>$params['user_id'],'service_work_id'=>$work['id']])->findOrEmpty();
            if(!$is_issue_work->isEmpty()){
                throw new Exception('已提交投诉，不允许重复提交');
            }
            $id = $IssueWork->insertGetId([
                'sn' => $params['sn'],
                'work_sn' => $work['work_sn'],
                'service_work_id' => $work['id'],
                'title'=>$work['title'],
                'master_worker_id' => $work['master_worker_id'],
                'complaint_type' => !empty($params['complaint_type'])?json_encode($params['complaint_type']):'',
                'complaint_details' => $params['complaint_details'],
                'complaint_images' => !empty($params['complaint_images']) ? json_encode($params['complaint_images']):'',
                'complaint_mobile'=>$params['complaint_mobile'],
                'user_id'=>$params['user_id'],
                'create_time' => time(),
                'update_time' => time()
            ]);
            Db::commit();
            $userInfo = User::where('id',$params['user_id'])->findOrEmpty();
            event('Notice', [
                'scene_id' => 126,
                'params' => [
                    'user_id' => 0,
                    'thing4' => $work['title'],
                    'thing5' => $userInfo['real_name']?:$userInfo['nickname'],
                    'phone_number2' => asteriskString($userInfo['mobile']),
                    'time6' => date('Y-m-d H:i:s'),
                ]
            ]);
            return $id;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/07/10 15:06
     */
    public static function detail($params): array
    {
        $issue_work = IssueWork::where(['id'=>$params['id'],'user_id'=>$params['user_id']])
            ->field('sn,sn,title,issue_approval,complaint_type,complaint_details,complaint_images,complaint_mobile,approval_time,finished_time,create_time')
            ->append(['issue_approval_text'])
            ->findOrEmpty()->toArray();
        if(!empty($issue_work)){
            $issue_work['complaint_type'] = DictData::where(['type_value'=>'complaint_type','status'=>1])->whereIn('value',$issue_work['complaint_type'])->column('name');
        }
        return $issue_work;
    }

    /**
     * @notes 完结投诉
     * @param $params
     * @return array|false
     */
    public static function complaintComplete($params)
    {
        try {
            $issueWork = IssueWork::where(['user_id'=>$params['user_id'],'id'=>$params['id']])->findOrEmpty();
            if($issueWork->isEmpty()){
                throw new Exception('投诉不存在');
            }

            // 投诉完成-质保金可用金额 解冻
            if($issueWork->issue_approval != 4 &&  $issueWork->is_refunded_payment == 1){
                $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
                    // 对原工程师的 质保金解冻质保金 / 清零
                    \app\common\logic\RetentionMoneyLogic::warrantyDepositRelease([
                        'to_freeze'=>2,
                        'source'=>1,
                        'remark'=>'对原工程师的质保金解冻质保金/清零',
                        'work_id'=>$issueWork->service_work_id??0,'worker_id'=>$issueWork->master_worker_id,
                        'issue_work_id'=>$issueWork->id,
                        'amount'=>$amount,
                    ],false);
                }
            }

            $issueWork->issue_approval = 4;
            $issueWork->complaint_status = 2;
            $issueWork->responsible = 3;
            $issueWork->finished_time = time();
            $issueWork->save();
            return [];
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }
}