<?php

namespace app\api\controller\notify;

use app\api\controller\BaseApiController;
use app\common\enum\PayEnum;
use app\common\enum\ThirdTypeEnum;
use app\common\enum\WorkEnum;
use app\common\logic\ThirdOrderLogic;
use app\common\model\equity\UserEquity;
use app\common\model\orders\RechargeOrder;
use app\common\model\recharge\OrderGoods;
use app\common\model\third\ThirdOrders;
use app\common\model\works\ServiceWork;
use think\facade\Db;
use think\facade\Log;

/**
 *
 * Class MeiTuanNotifyController
 * @package app\api\controller\notify
 */
class MeiTuanNotifyController extends BaseApiController
{

    public array $notNeedLogin = ['changeresultcallback','finishedWork','bookresultcallback','notify5810099','notify5810005','notify5810007','notify5810009','notify5810013','notify5810023','notify5810027','notify5810029','notify5810031','notifyMapping','submitOrder','notifyAuth','notifyReviewAuth','get_sign','test','cancellation','bookingResults','booking','changeBooking','cancellation5910003','bookingResults5910005','booking5910011','booking5910015','booking5910017'];

    public function notifyAuth(): void
    {
        Log::write('店铺权限授权CODE:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    public function notifyReviewAuth()
    {
        Log::write('店铺权限解约授权CODE:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    /**
     * 门店映射
     * @return void
     */
    public function notifyMapping()
    {
        Log::write('门店映射:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }



    public function test()
    {
        $data = array("businessId"=>"58","charset" => "utf-8","code"=>"7355f0a0d01f31e7963f23f6e20519f5",  "developerId" => "114657","grantType"=>"authorization_code", "timestamp" => "1744107897");
//        $data = array("businessId"=>"58","charset" => "utf-8","appAuthToken"=>"V2-26f91ef8b515c59b97b9b4404e77dc2b2fc14b9715e3be7edb9f3f86178e193ec380e1ef5a9ab7a877120a94bcae4586707c51ab5e56cfeb4cd91d4fb2983babbbfd2fda0f77353eb21b105fd14299aea392a706589a422baec961b6cc255191",  "developerId" => "114657","version"=>"2", "timestamp" => "1741663560",'biz'=>'{  "orderId": "61427436",  "bookStatus": 2,  "code": 200,"type":2}');
        echo $this->get_sign("8471lgvnv0qcjpx6", $data);
    }

    public static function get_sign($sign_key, $data)
    {
        if ($data == null) {
            return null;
        }
        ksort($data);
        $result_str = "";
        foreach ($data as $key => $val) {
            if ($key != "sign" && $val != null && $val != "") {
                $result_str = $result_str . $key . $val;
            }
        }
        $result_str = $sign_key . $result_str;


        $ret = bin2hex(sha1($result_str, true));

        return $ret;
    }

    //到店综合
    /**
     * 取消预订
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cancellation()
    {
        return '';
        http_request('https://developer.kyjlkj.com/platf/kaidianbao/cancellationByUser',http_build_query($this->request->param()));
        Log::write('取消预订:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
        $order = $this->request->param();
        ThirdOrderLogic::cancelOrderHandle($order);
        return $this->success('取消预订成功');
    }

    /**
     * 预订结果同步
     * @return void
     */
    public function bookingResults()
    {
        return '';
        http_request('https://developer.kyjlkj.com/platf/kaidianbao/reservationResults',http_build_query($this->request->param()));
        Log::write('预订结果同步:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    /**
     * 开始预约
     * @return \think\response\Json
    */
    public function booking()
    {
        return '';
        http_request('https://developer.kyjlkj.com/platf/kaidianbao/reservation',http_build_query($this->request->param()));
        $order = $this->request->param();
        Log::write('开始预约:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
        //手动处理未配置的工单
//        $request_msg = ThirdOrders::where('id',51)->findOrEmpty()['request_msg'];
//        $order = json_decode($request_msg,true);
        ThirdOrderLogic::orderhandle($order);
        return $this->success('开始预约');
    }

    /**
     * 改约提交
     * @return \think\response\Json
     */
    public function changeBooking()
    {
        return '';
        http_request('https://developer.kyjlkj.com/platf/kaidianbao/reschedulingByUser',http_build_query($this->request->param()));
        $order = $this->request->param();
        Log::write('改约提交:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
        ThirdOrderLogic::updateOrderHandle($order);
        return $this->success('改约提交成功');
    }


    //到店综合（客服）-回调通知
    /**
     * 商品状态变更
     * @return void
     */
    public function cancellation5910003()
    {
        Log::write('商品状态变更:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    /**
     * 改约结果同步三方
     * @return void
     */
    public function bookingResults5910005()
    {
        Log::write('改约结果同步三方:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    /**
     * 取消同步三方接口
     * @return void
     */
    public function booking5910011()
    {
        Log::write('取消同步三方接口:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    /**
     * 创单同步三方接口
     * @return void
     */
    public function booking5910015()
    {
        Log::write('创单同步三方接口:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    /**
     * 用户改约
     * @return void
     */
    public function booking5910017()
    {
        Log::write('用户改约:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }


    /**
     * 手动提交美团订单
     * @return \think\response\Json
     */
    public function submitOrder()
    {
        $request = $this->request->param();
        if(empty($request['userName']) || empty($request['mobile']) || empty($request['userAddress']) || empty($request['appointment_time']) || empty($request['goods_id']) || empty($request['amount'])){
            return $this->fail('参数错误');
        }
        ThirdOrderLogic::submitOrders($request);
        return $this->success('下单成功');
    }

    /**
     * 用户撤销退款通知
     * @return void
     */
    public function notify5810005()
    {
        Log::write('用户撤销退款通知:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    /**
     * 改约结果通知三方
     * @return void
     */
    public function notify5810007()
    {
        return '';
        http_request('https://developer.kyjlkj.com/platf/kaidianbao/reschedulingResults',http_build_query($this->request->param()));
        Log::write('改约结果通知三方:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    public function notify5810009()
    {
        return '';
        http_request('https://developer.kyjlkj.com/platf/Kaidianbao/inventory',http_build_query($this->request->param()));
        Log::write('到家行业库存查询:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    public function notify5810013()
    {
        Log::write('取消预订审核:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    public function notify5810023()
    {
        return '';
        http_request('https://developer.kyjlkj.com/platf/Kaidianbao/completedDetails',http_build_query($this->request->param()));
        Log::write('核销状态查询:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    public function notify5810027()
    {
        return '';
        Log::write('通知三方核销:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    public function notify5810029()
    {
        return '';
        http_request('https://developer.kyjlkj.com/platf/Kaidianbao/completedByArrears',http_build_query($this->request->param()));
        //尾款结算2--维修的尾款订单信息增加
        //获取工单信息
        $request = $this->request->param();
//        $request = json_decode('{"opBizCode":"AE7MKOJAV67338LIC3UD0K5TGIO","msgType":"5810029","developerId":"114657","businessId":"58","sign":"7f936c6c65ee05fa50a105fdc7bbb2652ccfe9b6","msgId":"2993785907604100573","message":"{\"orderId\":\"62737288\",\"addPriceStatus\":\"0\",\"serialNumber\":\"5962563697\",\"amount\":\"9.90\"}","timestamp":"1742907755"}',true);
        Log::write('补价支付结果:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
        if(!empty($request['message'])){
            Db::startTrans();
            try {
                $message = json_decode($request['message'], true);
                $orderId = $message['orderId'];
                $amount = $message['amount'];
                $order = ThirdOrders::where('orderId',$orderId)->order('create_time desc')->findOrEmpty();
                    if(!$order->isEmpty() && $order['verifyStatus'] != 2){
                        $un_pay = RechargeOrder::where(['work_id'=>$order['work_id'],'pay_status'=>0])->findOrEmpty();
                        if(!$un_pay->isEmpty()){
                            $un_pay->pay_way = 4;//美团支付
                            $un_pay->pay_status = PayEnum::ISPAID;
                            $un_pay->pay_time = time();
                            $un_pay->order_amount = $amount;
                            $un_pay->paid_amount = $amount;
                            $un_pay->save();
                        }else{
                            $orders = \app\common\model\orders\RechargeOrder::where(['work_id'=>$order->work_id])->select()->toArray();
                            if(count($orders)==1){
                                //判断是否是一口价预支付订单，支付成功后生成尾款订单，针对工程师未报价的订单
                                $good_order = $orders[0];
                                $order_goods = OrderGoods::where('sn',$good_order['sn'])->findOrEmpty();
                                if(!$order_goods->isEmpty()){
                                    //新增待支付尾款
                                    $order_data = [
                                        'order_type'=>$good_order['order_type'],
                                        'sn'=>generate_sn(\app\common\model\orders\RechargeOrder::class, 'sn'),
                                        'work_id'=>$good_order['work_id'],
                                        'user_id'=>$good_order['user_id'],
                                        'payment_type'=>2,
                                        'order_total'=>$amount,
                                        'order_amount'=>$amount,
                                        'order_terminal'=>$good_order['order_terminal'],
                                        'pay_status'=>PayEnum::ISPAID,
                                        'pay_time'=>time(),
                                        'paid_amount'=>$amount,
                                        'pay_way'=>4//美团支付
                                    ];
                                    \app\common\model\recharge\RechargeOrder::create($order_data);
                                }
                            }

                        }

                        //结算工单
                        $work = ServiceWork::where('id',$order['work_id'])->findOrEmpty();
                        if(!$work->isEmpty()){
                            $order->verifyStatus = 2;
                            $order->save();
                            $work->work_pay_status = WorkEnum::IS_PAY_STATUS;
                            $orders = \app\common\model\orders\RechargeOrder::where(['work_id'=>$order['work_id']])->select()->toArray();
                            $order_total = 0;
                            $order_amount = 0;
                            foreach ($orders as $k=>$v){
                                $order_total += $v['order_total'];
                                $order_amount += $v['order_amount'];
                            }
                            $work->work_total = $order_total;
                            $work->work_amount = $order_amount;
                            $work->work_status = 7;
                            $work->user_confirm_status = 5;
                            $work->service_status = 3;
                            $work->work_pay_status = 1;
                            $work->finished_time = time();
                            $work->save();
                            ThirdOrderLogic::updateorderfulfillinfo($work,ThirdTypeEnum::MEITUAN_COMPLETION);
                        }
                    }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                return $this->fail('尾款支付失败');
            }
        }
        return $this->success('尾款支付成功');
    }

    public function notify5810031()
    {
        return '';
        http_request('https://developer.kyjlkj.com/platf/Kaidianbao/completedByUser',http_build_query($this->request->param()));
        //尾款结算1        //尾款结算3
        //获取工单信息
        $request = $this->request->param();
//        $request = json_decode('{"opBizCode":"AE7MKOJAV67338LIC3UD0K5TGIO","msgType":"5810031","developerId":"114657","businessId":"58","sign":"70e9ab334024101d8601276e5e3a24f459005a1e","msgId":"8401776939815074952","message":"{\"orderId\":\"63702731\",\"verifyStatus\":\"2\",\"verifyChannel\":\"1\",\"type\":\"2\",\"serialNumber\":\"4078677902\"}","timestamp":"1743944824"}',true);
        Log::write('预订核销同步:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
        if(!empty($request['message'])){
            Db::startTrans();
            try {
                $message = json_decode($request['message'], true);
                $orderId = $message['orderId'];
                $order = ThirdOrders::where('orderId',$orderId)->order('create_time desc')->findOrEmpty();
                if(!$order->isEmpty() && $order['verifyStatus'] != 2  && $message['verifyStatus'] == 2){
                    //判断工单是否存在未结算的尾款订单，如果存在，等待结算后再核销
                    $un_pay = RechargeOrder::where(['work_id'=>$order['work_id'],'pay_status'=>0])->findOrEmpty();
                    $workOrder = RechargeOrder::where('work_id',$order['work_id'])->order('id desc')->findOrEmpty();
                    if($un_pay->isEmpty() && ($workOrder['payment_type'] == 0 || $workOrder['payment_type'] == 2)){
                        $work = ServiceWork::where('id',$order['work_id'])->findOrEmpty();
                        $order->verifyStatus = 2;
                        $order->save();

                        if(!$work->isEmpty()){
                            $work->work_pay_status = WorkEnum::IS_PAY_STATUS;
                            $orders = \app\common\model\orders\RechargeOrder::where(['work_id'=>$order->work_id])->select()->toArray();
                            $order_total = 0;
                            $order_amount = 0;
                            foreach ($orders as $k=>$v){
                                $order_total += $v['order_total'];
                                $order_amount += $v['order_amount'];
                            }
                            $work->work_total = $order_total;
                            $work->work_amount = $order_amount;
                            $work->work_status = 7;
                            $work->user_confirm_status = 5;
                            $work->service_status = 3;
                            $work->work_pay_status = 1;
                            $work->finished_time = time();
                            $work->save();

                            ThirdOrderLogic::updateorderfulfillinfo($work,ThirdTypeEnum::MEITUAN_COMPLETION);
                        }
                    }
                }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                return $this->fail('订单核销失败');
            }
            return $this->success('订单核销成功');
        }

    }

    /**
     * 手动完结订单
     * @return \think\response\Json
     */
    public function finishedWork()
    {
        $work = ServiceWork::where('id',324)->findOrEmpty();
        if(!$work->isEmpty()){
            $work->work_pay_status = WorkEnum::IS_PAY_STATUS;
            $orders = \app\common\model\orders\RechargeOrder::where(['work_id'=>324])->select()->toArray();
            $order_total = 0;
            $order_amount = 0;
            foreach ($orders as $k=>$v){
                $order_total += $v['order_total'];
                $order_amount += $v['order_amount'];
            }
            $work->work_total = $order_total;
            $work->work_amount = $order_amount;
            $work->work_status = 7;
            $work->user_confirm_status = 5;
            $work->service_status = 3;
            $work->work_pay_status = 1;
            $work->finished_time = time();
            $work->save();
        }
        return $this->success('订单核销成功');
    }

    public function notify5810099()
    {
        return '';
        //尾款结算4
//        {"opBizCode":"AE7MKOJAV67338LIC3UD0K5TGIO","msgType":"5810099","developerId":"114657","businessId":"58","sign":"a726ef82351172679a8faf83e1c687e23930f3e9","msgId":"-8772277532478005199","message":"{\"phone\":\"13545228441\",\"dealGroupId\":\"1287039501\",\"dealName\":\"【燃气灶维修】不打火维修电话安装上门维修优惠卷\",\"amount\":\"31.00\",\"firstOrderId\":\"4981005619907623352\",\"firstOrderCode\":\"5831711557\",\"firstOrderActualPrice\":\"30.00\",\"finalOrderId\":\"4981005652342579640\",\"finalOrderCode\":\"8283252725\",\"finalOrderActualPrice\":\"1.00\",\"firstOrderDiscountAmount\":\"0.00\",\"finalOrderDiscountAmount\":\"0.00\",\"dealUnitAmount\":\"30.00\",\"firstOrderPrice\":\"30.00\",\"finalOrderPrice\":\"1.00\"}","timestamp":"1741600287"}
        Log::write('加价尾单核销通知:'.json_encode($this->request->param(),JSON_UNESCAPED_UNICODE));
    }

    //商家操作接口

    public function bookresultcallback()
    {
        return '';
        $a = ThirdOrderLogic::bookresultcallback('AE7MKOJAV67338LIC3UD0K5TGIO','63950625',2);
        dd($a);
    }



    /**
     * 商家确认改约接口
     * @return void
     */
    public function changeresultcallback()
    {
        return '';
        //changeresultcallback-$shop_token2
        $a = ThirdOrderLogic::changeresultcallback('64201808');
        dd($a);
    }
}