<?php

namespace app\common\controller;


use app\api\logic\PerformanceLogic;
use app\api\logic\ServiceOrderLogic;
use app\common\enum\PayEnum;
use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\logic\PayNotifyLogic;
use app\common\logic\WorkerAccountLogLogic;
use app\common\model\external\ExternalPlatform;
use app\common\model\recharge\RechargeOrder;
use app\common\model\works\ServiceWork;
use app\common\model\works\ServiceWorkLog;
use think\facade\Config;
use think\facade\Log;

class InternalApiController extends BaseLikeAdminController
{
    public array $notNeedLogin = ['changeAppointment','confirmServiceFinish','paymentSuccessful','cancelOrder'];

    private function checkSign(){
        $params = $this->request->param();
        // 验证IP
        $sign = ExternalPlatform::getSign(env('internal_api.api_sign_key'),$params);
        Log::info('内部请求参数'.json_encode([$params,$sign]));
        return true;
        /*if ($sign && $sign === $params['sign']) {
            return true;
        }
        return false;*/
    }

    public function changeAppointment()
    {
        try {
            $params = $this->request->param();
            if(!$this->checkSign()) throw new \Exception('签名错误',404);
            //sn appointment_time
            if(!isset($params['appointment_time']) || empty($params['appointment_time'])){
                throw new \Exception('预约时间不能为空',404);
            }
            if(!isset($params['sn']) || empty($params['sn'])){
                throw new \Exception('订单号不能为空',404);
            }
            $result = ServiceOrderLogic::approvalChangeAppointment($params);
            if (false === $result) {
                throw new \Exception(ServiceOrderLogic::getError(),404);
            }
            return $this->success('内部重新预约完成', [], 0, 1);
        }catch(\Exception $e){
            return $this->fail($e->getMessage(),[],$e->getCode());
        }
    }

    public function confirmServiceFinish()
    {
        try {
            $params = $this->request->param();
            if(!$this->checkSign()) throw new \Exception('签名错误',404);

            // 工单信息
            $service_work = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
            if($service_work->isEmpty()) throw new \Exception('工单不存在',404);
            if($service_work->user_confirm_status < 3){
                //throw new \Exception('正在服务中，请稍后再试...',404);
            }
            if(in_array($service_work->service_status,[3,4,5])){
                return $this->success('内部确认服务完成', [], 0, 1);
            }
            $result = ServiceOrderLogic::confirmServiceFinish([
                'sn' => $params['sn'],
                'user_id' => $service_work->user_id,
                'user_info'=>['real_name' => $service_work->real_name],
            ]);
            if (false === $result) {
                throw new \Exception(ServiceOrderLogic::getError(),404);
            }
            // 工程师完单的时候设置该规则关闭，以及短信通知工程师
            ServiceOrderLogic::orderQuantityRule($params);
            return $this->success('内部确认服务完成', [], 0, 1);
        }catch(\Exception $e){
            return $this->fail($e->getMessage(),[],$e->getCode());
        }
    }

    public function paymentSuccessful()
    {
        try {
            $params = $this->request->param();
            if(!$this->checkSign()) throw new \Exception('签名错误',404);

            $params['sn'] = mb_substr($params['sn'], 0, 18);
            $order = RechargeOrder::where(['sn' => $params['sn']])->findOrEmpty();
            if($order->isEmpty()) {
                throw new \Exception('内部订单不存在：'.$params['sn'],404);
            }
            if($order->pay_status == PayEnum::ISPAID) {
                return $this->success('内部支付已完成', [], 0, 1);
            }
            $payNotifyLogic = PayNotifyLogic::handle('goods', $params['sn'], $params['extra']??[]);
            if($payNotifyLogic === true){
                return $this->success('内部支付完成', [], 0, 1);
            }
            throw new \Exception($payNotifyLogic,404);
        }catch(\Exception $e){
            return $this->fail($e->getMessage(),[],$e->getCode());
        }
    }

    public function cancelOrder()
    {
        try {
            $params = $this->request->param();
            if(!$this->checkSign()) throw new \Exception('签名错误',404);

            // 工单信息
            $service_work = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
            if($service_work->isEmpty()) throw new \Exception('工单不存在',404);

            // 取消工单
            if($service_work->work_status < 7){
                //更新工单状态为已取消
                $service_work->service_status = 4;
                // 是否存在退款
                if($service_work->work_pay_status == 1 && (int)$params['is_refund'] === 1){ //全退不分给工程师
                    $service_work->work_status = 7;
                    $service_work->service_status = 5;
                    $service_work->work_pay_status = 2;
                    //取消订单
                    RechargeOrder::where(['user_id'=>$service_work->user_id,'work_id'=>$service_work->id])->update([
                        'pay_status' => 2,
                    ]);
                }else if($service_work->work_pay_status == 1 && (int)$params['is_refund'] === 0){ // 上门费分给工程师
                    $paid_amount = RechargeOrder::where('work_id', $service_work->id)->where('payment_type', 1)->value('paid_amount');
                    if($paid_amount > 0){
                        // 存在上门费给工程师
                        Log::info('内部取消并终止结束服务工单'.$service_work->id.',上门费:'.$paid_amount);
                        WorkerAccountLogLogic::addAccountLog($service_work,$paid_amount,WorkerAccountLogEnum::UM_INC_ADMIN,WorkerAccountLogEnum::INC);
                    }
                    ServiceWork::where('id', $params['id'])->update([
                        'work_status' => 7,
                        'user_confirm_status' => 5,
                        'service_status' => 3,
                        'work_pay_status' => 2, // 已结算则不执行 onAfterUpdate
                        'settlement_amount' => $paid_amount??0,
                        'worker_price' => $paid_amount??0,
                        'remark' => ($service_work->remark?:'')." | 内部取消并终止结束服务:上门费-{$paid_amount}"
                    ]);
                }else{
                    $service_work->work_status = 9;
                }

                ServiceWorkLog::create([
                    'work_id' => $service_work->id,
                    'master_worker_id' => $service_work->master_worker_id,
                    'opera_log' => "工单:{$service_work->work_sn} 内部取消并终止结束服务"
                ]);

                $service_work->user_confirm_status = 5;
                $service_work->save();
            }
            /*else{
                // 若存在结算则先退回
            }*/
            return $this->success('内部取消工单完成', [], 0, 1);
        }catch(\Exception $e){
            return $this->fail($e->getMessage(),[],$e->getCode());
        }
    }

    /**
     * tmp - test
     * @return \think\response\Json
     * @author liugc <466014217@qq.com>
     * @date 2025/4/23 11:52
     */
    public function calculatePerformanceTmp()
    {
        try {
            $params = $this->request->param();
            $work = ServiceWork::find($params['work_id']);
            //dd($work->toArray());
            PerformanceLogic::calculatePerformanceTmp($work);

            return $this->success('tmp工单完成', [], 0, 1);
        }catch(\Exception $e){
            return $this->fail($e->getMessage(),[],$e->getCode());
        }
    }



}