<?php
namespace app\common\logic;


use app\api\logic\LoginLogic;
use app\common\{enum\GoodsEnum,
    enum\PayEnum,
    enum\WorkEnum,
    model\goods\Goods,
    model\orders\RechargeOrder,
    model\recharge\OrderGoods,
    model\setting\PostageRegion,
    model\third\ThirdGoods,
    model\third\ThirdOrders,
    model\user\User,
    model\works\ServiceWork,
    model\works\ServiceWorkAppointmentLog,
    model\works\ServiceWorkLog};
use think\facade\Db;
use app\common\model\service_area\ServiceArea;
use think\facade\Log;

/**
 * 第三方平台下单逻辑层
 * Class UserLogic
 * @package app\shopapi\logic
 */
class ThirdOrderLogic extends BaseLogic
{

    protected  const user_token = [
        "accessToken"=>"V2-29d801e316e9ec4eb88b3b9abd8dbda490367af539d97d754420056dc5c1329a2c1aff7d4d54729ff622d96ff7c9910aa930f7b7ad27910d199c15029ffc71aa4a84142d75b60f4a34b71a8390a89d8c01a4dd385232e4e9c9204fb5934eda89",
        "expireIn"=> 2592000,
        "opBizCode"=> "AG5MALO18KG6I5DL8LVONRSRF5G",
        "opBizName"=> "武汉开源节流科技有限公司",
        "refreshToken"=> "ab8d15b4028b7bd6aca383d230b87450436d301a2996b6bb3151d668dd2d015d68d8393e66fb2a59aa10146c70dd30728b473358ec0d156dc0bc5cc5e574a109a5680ab49c393fa9d2693ef5519ff41a16115b81259b58c71a54d79e23f26381",
        "scope"=> "dingdan,generalreserve,merchantreceipt,shangpin"
    ];
    protected const shop_token1 = [
        "accessToken"=> "V2-9667b1ce4ffaabe453d4ce847888c788c9c61762df9230ab342caf33e2b4a735ade021c559312195b7f01f30f3bdd44cf6f8528b1fd1ad1541ceabeb7da61156c852e314aae26eef9d52fb41fda585c566c18e05dc3cbb61733b2f71c05a78f6",
        "expireIn"=> 2592000,
        "opBizCode"=> "AH14KGRJ76O8PFH4GCO67F0CUKC",
        "opBizName"=> "众盾闪修 家电清洗 武汉",
        "refreshToken"=> "fd3da11174eed4c3d6b4d117f87ab7b62a72603627d2d597bed82dddb103694375ed9cab1944bc7437a204b171303cb3c0976fbddc88708e75f2169c532a28614ff36c68486a75cb9dbf0391e39d6dfa8bec0bf18b54b5d2119d895788a2281c",
        "scope"=> "merchantdata,poiqrcode,tuangou,ugc,yuding"
    ];
    protected const shop_token2 = [
        "accessToken"=> "V2-26f91ef8b515c59b97b9b4404e77dc2b2fc14b9715e3be7edb9f3f86178e193e21513ea76f021c503890172cad1863ea544d6b4c7b8b3790374ba912c15ad9e71e32ba0b195d38131da3584a59603ea55e81d1b3203a57ae280c36cbb67f5ffc",
        "expireIn"=> 2592000,
        "opBizCode"=> "AE7MKOJAV67338LIC3UD0K5TGIO",
        "opBizName"=> "众盾闪修 家电维修 武汉",
        "refreshToken"=> "bd57846c8817125f8ad7f4eb4ccad4af80c808f30c8b22e38476fc78c008b568376db34916f190e086272f6da315ac2ce4daefac6e61e4ce8889500f293e95537f6939f810f0466c8181086b052907c68b01a6d59ac5fe78abbae0ecd54578f5",
        "scope"=> "merchantdata,poiqrcode,tuangou,ugc,yuding"
    ];
    protected const developerId = 114657;

    protected const assessKey = '8471lgvnv0qcjpx6';


    /**
     * 处理订单
     * @param array $order
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function orderhandle(array $order)
    {
        $message = json_decode($order['message'], true);
        //查询用户是否存在
        $userName = $message['userName'];
        $mobile = $message['mobile'];
        $userAddress = json_decode($message['userAddress']);
        $user = User::where(['mobile' =>$mobile])->findOrEmpty();
        $product_message = json_decode($message['products'],true);
        if($user->isEmpty()){
            $user = LoginLogic::register([
                'password'=>'123456',
                'nickname'=>$userName,
                'account'=>$mobile,
                'mobile'=>$mobile,
                'channel'=>1,
                'user_type'=>0
            ]);
        }

        //查询美团商品和平台商品的对应关系
        $productId = $message['productId'];
        $product = ThirdGoods::where(['third_type'=>1,'product_id'=>$productId])->findOrEmpty();

        //生成第三方订单信息
        $orderData = [
            'orderId'=>$message['orderId'],
            'uni_order_id'=>$product_message[0]['uni_order_id'],
            'productId'=>$message['productId'],
            'productName'=>$message['productName'],
            'request_msg'=>json_encode($order,JSON_UNESCAPED_UNICODE),
            'bookStatus'=>1,
            'third_type'=>1,//美团
        ];

        //判断美团的预约订单是否生成
        if(!$product->isEmpty()){
            //查询美团预约订单是否生成
            $thirdOrder = ThirdOrders::where(['uni_order_id'=>$product_message[0]['uni_order_id']])->findOrEmpty();
            if(!$thirdOrder->isEmpty() and $thirdOrder['work_id'] != 0){
                //生成第三方订单信息
                $orderData['sync_status'] = 1;
                $orderData['work_id'] = $thirdOrder['work_id'];
            }
        }
        $thirdOrders = ThirdOrders::where('orderId',$message['orderId'])->findOrEmpty();
        //生成未同步预约订单信息
        if($thirdOrders->isEmpty()){
            $thirdOrders = ThirdOrders::create($orderData);

        }
        if(!$thirdOrders->isEmpty()){
            $orderData['work_id'] = $thirdOrders->work_id;
        }
        if(empty($orderData['work_id']) and !$product->isEmpty() and !empty($product['goods_id'])){
            $goods = Goods::findOrEmpty($product['goods_id']);
            $pattern = '/(?:省|市)([\w\s]+市)/u';
            Db::startTrans();
            try {
                if (preg_match($pattern, $userAddress->receiver_address, $matches)) {
                    $city = $matches[1];
                }
                $area_city = PostageRegion::where(['level'=>2,'name'=>$city])->value('id');

                //生成服务工单
                $work_data = [
                    'work_sn' => generate_sn(ServiceWork::class, 'work_sn'),
                    'real_name' => $userName,
                    'mobile' => $mobile,
                    'address' => $userAddress->receiver_address,
                    'province' => 0,
                    'city' => $area_city??0,
                    'area_name' => $userAddress->receiver_address,
                    'title' => $goods->goods_name,
                    'category_type' => $goods['category_type'],
                    'goods_category_ids' => $goods['goods_category_ids'],
                    'goods_category_id' => $goods['goods_category_id'],
                    'base_service_fee' => $goods['base_service_fee'],
                    'service_fee' => $product['product_price'],
                    'work_pay_status'=>WorkEnum::IS_PAY_STATUS,
                    'appointment_time' => strtotime($message['begintime']),
                    'user_id'=>$user['id'],
                    'lon'=>!empty($userAddress->longitude)?$userAddress->longitude:0,
                    'lat'=>!empty($userAddress->latitude)?$userAddress->latitude:0,
                    'property_activity_id'=>0,
                    'user_equity_id'=>0,
                    'third_type'=>1,
                    'work_total'=>$product['product_price'],
                    'work_amount'=>$product['product_price']
                ];
                $service_area_id = ServiceArea::serviceAreaId(['lon' => $work_data['lon'], 'lat' => $work_data['lat']]);
                $work_data['service_area_id'] = $service_area_id;
                $service_work = ServiceWork::create($work_data);

                //生成服务订单
                $data = [
                    'work_id'=> $service_work['id'],
                    'sn' => generate_sn(RechargeOrder::class, 'sn'),
                    'order_type'=>0,//服务订单
                    'order_terminal' => 1,
                    'payment_type'=>$goods['goods_payment_type']==GoodsEnum::ISGOODS_PAYMENT_TYPE?0:1,
                    'user_id' => $user['id'],
                    'pay_status' => PayEnum::ISPAID,
                    'coupon_id'=>0,
                    'coupon_price'=>0,
                    'pay_way' => 4,
                    'order_total' => $product['product_price'],
                    'order_amount' => $product['product_price'],
                    'paid_amount'=> $product['product_price'],
                ];
                $order = RechargeOrder::create($data);
                //生成订单服务详情
                OrderGoods::create([
                    'sn' => $order['sn'],
                    'goods_id' => $goods['id'],
                    'category_type' => $goods['category_type'],
                    'goods_category_ids' => $goods['goods_category_ids'],
                    'goods_category_id' => $goods['goods_category_id'],
                    'goods_name' => $goods['goods_name'],
                    'goods_image' => $goods['goods_image'],
                    'goods_video' => $goods['goods_video'],
                    'goods_number' => $goods['goods_number'],
                    'good_unit' => $goods['good_unit'],
                    'goods_size' => $goods['goods_size'],
                    'goods_type' => $goods['goods_type'],
                    'goods_brand' => $goods['goods_brand'],
                    'install_guide' => $goods['install_guide'],
                    'goods_payment_type'=>$goods['goods_payment_type'],
                    'base_service_fee' => $goods['base_service_fee'],
                    'service_total' => $goods['service_total'],
                    'service_fee' => $product['product_price'],
                    'service_image' => $goods['service_image'],
                    'warranty_period'=>$goods['warranty_period'],
                    'fee_schedule' => $goods['fee_schedule'],
                    'goods_status' => $goods['goods_status'],
                ]);

                //判断是否是一口价预支付订单，支付成功后生成尾款订单
                if(!$goods->isEmpty() and $goods->goods_payment_type == 3 and bcsub($goods->base_service_fee,$goods->service_fee,2)>=0){
                    //新增待支付尾款
                    $order_weikuan_data = [
                        'order_type'=>$order['order_type'],
                        'sn'=>generate_sn(\app\common\model\orders\RechargeOrder::class, 'sn'),
                        'work_id'=>$order['work_id'],
                        'user_id'=>$order['user_id'],
                        'payment_type'=>2,
                        'order_total'=>bcsub($goods->base_service_fee,$product['product_price'],2),
                        'order_amount'=>bcsub($goods->base_service_fee,$product['product_price'],2),
                        'order_terminal'=>$order['order_terminal']
                    ];
                    \app\common\model\recharge\RechargeOrder::create($order_weikuan_data);
                }

                $thirdOrders->work_id = $service_work->id;
                $thirdOrders->save();

                self::bookresultcallback($order['opBizCode'],$message['orderId'],2);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                self::setError($e->getMessage());
                return false;
            }
        }

        if(!empty($orderData['work_id']) and !$product->isEmpty() and !empty($product['goods_id'])) {
            //更改预约时间
            $serviceWorkInfo = ServiceWork::find($orderData['work_id']);
            if(!empty($serviceWorkInfo)){
                $appointment_time = $message['begintime'];
                ServiceWorkAppointmentLog::create([
                    'work_id'=>$serviceWorkInfo->id,
                    'last_appointment_time'=>strtotime($serviceWorkInfo->appointment_time),
                    'this_appointment_time'=>strtotime($appointment_time),
                ]);
                //修改预计完成时间
                if ($serviceWorkInfo->estimated_finish_time) {
                    $serviceWorkInfo->estimated_finish_time = strtotime($appointment_time) + (strtotime($serviceWorkInfo->estimated_finish_time) - strtotime($serviceWorkInfo->appointment_time));
                }
                $serviceWorkInfo->appointment_time = strtotime($appointment_time);
                $serviceWorkInfo->save();
            }
        }
        return true;
    }


    //手动添加订单
    public static function submitOrders(array $message)
    {
        //查询用户是否存在
        $userName = $message['userName'];
        $mobile = $message['mobile'];
        $user = User::where(['mobile' =>$mobile])->findOrEmpty();
        if($user->isEmpty()){
            $user = LoginLogic::register([
                'password'=>'123456',
                'nickname'=>$userName,
                'account'=>$mobile,
                'mobile'=>$mobile,
                'channel'=>1,
                'user_type'=>0,
            ]);
        }
        $goods = Goods::findOrEmpty($message['goods_id']);
        $pattern = '/(?:省|市)([\w\s]+市)/u';
        Db::startTrans();
        try {
            if (preg_match($pattern, $message['userAddress'], $matches)) {
                $city = $matches[1];
            }
            $area_city = PostageRegion::where(['level'=>2,'name'=>$city])->value('id');

            //生成服务工单
            $work_data = [
                'work_sn' => generate_sn(ServiceWork::class, 'work_sn'),
                'real_name' => $userName,
                'mobile' => $mobile,
                'address' => $message['userAddress'],
                'province' => 0,
                'city' => $area_city??0,
                'area_name' => $area_city??'',
                'title' => $goods->goods_name,
                'category_type' => $goods['category_type'],
                'goods_category_ids' => $goods['goods_category_ids'],
                'goods_category_id' => $goods['goods_category_id'],
                'base_service_fee' => $goods['base_service_fee'],
                'service_fee' => $message['amount'],
                'work_pay_status'=>WorkEnum::IS_PAY_STATUS,
                'appointment_time' => strtotime($message['appointment_time']),
                'user_id'=>$user['id'],
                'lon'=>$message['lon'],
                'lat'=>$message['lat'],
                'property_activity_id'=>0,
                'user_equity_id'=>0,
                'work_total'=>$message['amount'],
                'work_amount'=>$message['amount']
            ];
            $service_area_id = ServiceArea::serviceAreaId(['lon' => $work_data['lon'], 'lat' => $work_data['lat']]);
            $work_data['service_area_id'] = $service_area_id;
            $service_work = ServiceWork::create($work_data);

            //生成服务订单
            $data = [
                'work_id'=> $service_work['id'],
                'sn' => generate_sn(RechargeOrder::class, 'sn'),
                'order_type'=>0,//服务订单
                'order_terminal' => 1,
                'payment_type'=>$goods['goods_payment_type']==GoodsEnum::ISGOODS_PAYMENT_TYPE?0:1,
                'user_id' => $user['id'],
                'pay_status' => PayEnum::ISPAID,
                'coupon_id'=>0,
                'coupon_price'=>0,
                'pay_way' => 3,
                'order_total' => $message['amount'],
                'order_amount' => $message['amount'],
                'paid_amount'=>$message['amount']
            ];
            $order = RechargeOrder::create($data);
            //生成订单服务详情
            OrderGoods::create([
                'sn' => $order['sn'],
                'goods_id' => $goods['id'],
                'category_type' => $goods['category_type'],
                'goods_category_ids' => $goods['goods_category_ids'],
                'goods_category_id' => $goods['goods_category_id'],
                'goods_name' => $goods['goods_name'],
                'goods_image' => $goods['goods_image'],
                'goods_video' => $goods['goods_video'],
                'goods_number' => $goods['goods_number'],
                'good_unit' => $goods['good_unit'],
                'goods_size' => $goods['goods_size'],
                'goods_type' => $goods['goods_type'],
                'goods_brand' => $goods['goods_brand'],
                'install_guide' => $goods['install_guide'],
                'goods_payment_type'=>$goods['goods_payment_type'],
                'base_service_fee' => $goods['base_service_fee'],
                'service_total' => $goods['service_total'],
                'service_fee' => $message['amount'],
                'service_image' => $goods['service_image'],
                'warranty_period'=>$goods['warranty_period'],
                'fee_schedule' => $goods['fee_schedule'],
                'goods_status' => $goods['goods_status'],
            ]);

            //判断是否是一口价预支付订单，支付成功后生成尾款订单
            if(!$goods->isEmpty() and $goods->goods_payment_type == 3 and bcsub($goods->base_service_fee,$goods->service_fee,2)>=0){
                //新增待支付尾款
                $order_weikuan_data = [
                    'order_type'=>$order['order_type'],
                    'sn'=>generate_sn(\app\common\model\orders\RechargeOrder::class, 'sn'),
                    'work_id'=>$order['work_id'],
                    'user_id'=>$order['user_id'],
                    'payment_type'=>2,
                    'order_total'=>bcsub($goods->base_service_fee,$message['amount'],2),
                    'order_amount'=>bcsub($goods->base_service_fee,$message['amount'],2),
                    'order_terminal'=>$order['order_terminal']
                ];
                \app\common\model\recharge\RechargeOrder::create($order_weikuan_data);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
        return true;
    }

    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;
    }


    /**
     * 商家接单接口
     * @param $orderId
     * @param $bookStatus
     * @return string
     */
    public static function bookresultcallback($opBizCode,$orderId,$bookStatus=2)
    {
        return '';
        http_request('https://developer.kyjlkj.com/platf/kaidianbao/reservationSuccessful',http_build_query([$opBizCode,$orderId,$bookStatus]));
        //预订结果，2-预订成功，3-预订失败
        $url = 'https://api-open-cater.meituan.com/ddzh/yuding/bookresultcallback';
        $accessToken = $opBizCode == 'AE7MKOJAV67338LIC3UD0K5TGIO' ? self::shop_token2['accessToken'] : self::shop_token1['accessToken'];
        $data = [
            'timestamp'=>time(),
            'appAuthToken'=>$accessToken,
            'charset'=>'utf-8',
            'version'=>'2',
            'developerId'=>self::developerId,
            'businessId'=>58,
            'biz'=>json_encode([
                'orderId'=>$orderId,
                'bookStatus'=>$bookStatus,
                "code"=>200,
                "type"=>2
            ],JSON_UNESCAPED_UNICODE)
        ];
        $sign_data = self::get_sign(self::assessKey, $data);
        $data['sign'] = $sign_data;
        return http_request($url,http_build_query($data));
    }

    /**
     * 取消预订
     * @param array
     * $order
     * @return bool
     */
    public static function cancelOrderHandle(array $order)
    {
        $message = json_decode($order['message'], true);
        Db::startTrans();
        try {
            $thirdOrders = ThirdOrders::where('orderId',$message['orderId'])->findOrEmpty();
            if(!$thirdOrders->isEmpty()){
                $thirdOrders->bookStatus = 3;
                $thirdOrders->save();
                $serviceWorkInfo = ServiceWork::find($thirdOrders->work_id);
                if(!empty($serviceWorkInfo)){
                    $appointment_time = '2099-12-31 23:59:59';
                    ServiceWorkAppointmentLog::create([
                        'work_id'=>$serviceWorkInfo->id,
                        'last_appointment_time'=>strtotime($serviceWorkInfo->appointment_time),
                        'this_appointment_time'=>strtotime($appointment_time),
                    ]);
                    //修改预计完成时间
                    if ($serviceWorkInfo->estimated_finish_time) {
                        $serviceWorkInfo->estimated_finish_time = strtotime($appointment_time) + (strtotime($serviceWorkInfo->estimated_finish_time) - strtotime($serviceWorkInfo->appointment_time));
                    }
                    $serviceWorkInfo->appointment_time = strtotime($appointment_time);
                    $serviceWorkInfo->save();
                }
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 美团改约通知
     * @param array $order
     * @return bool
     */
    public static function updateOrderHandle(array $order)
    {
        $message = json_decode($order['message'], true);
        Db::startTrans();
        try {
            $thirdOrders = ThirdOrders::where('orderId',$message['orderId'])->findOrEmpty();
            if(!$thirdOrders->isEmpty()){
                $thirdOrders->bookStatus = 2;
                $thirdOrders->save();
                $serviceWorkInfo = ServiceWork::find($thirdOrders->work_id);
                if(!empty($serviceWorkInfo)){
                    $appointment_time = $message['reserveEndtime'];
                    ServiceWorkAppointmentLog::create([
                        'work_id'=>$serviceWorkInfo->id,
                        'last_appointment_time'=>strtotime($serviceWorkInfo->appointment_time),
                        'this_appointment_time'=>strtotime($appointment_time),
                    ]);
                    //修改预计完成时间
                    if ($serviceWorkInfo->estimated_finish_time) {
                        $serviceWorkInfo->estimated_finish_time = strtotime($appointment_time) + (strtotime($serviceWorkInfo->estimated_finish_time) - strtotime($serviceWorkInfo->appointment_time));
                    }
                    $serviceWorkInfo->appointment_time = strtotime($appointment_time);
                    $serviceWorkInfo->save();
                }
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 获取美团商品信息
     * @param $offset
     * @return string
     */
    public static function queryshopdeal($offset=1)
    {
        $url = 'https://api-open-cater.meituan.com/ddzh/tuangou/deal/queryshopdeal';
        $data = [
            'timestamp'=>time(),
            'appAuthToken'=>self::shop_token2['accessToken'],
            'charset'=>'utf-8',
            'version'=>'2',
            'developerId'=>self::developerId,
            'businessId'=>58,
            'biz'=>json_encode([
                'offset'=>$offset,
                'limit'=>100,
                "source"=>2,
            ],JSON_UNESCAPED_UNICODE)
        ];
        $sign_data = self::get_sign(self::assessKey, $data);
        $data['sign'] = $sign_data;
        return http_request($url,http_build_query($data));
    }

    /**
     * 获取美团商品信息
     * @param $offset
     * @return string
     */
    public static function queryshopdeal1($offset=1)
    {
        $url = 'https://api-open-cater.meituan.com/ddzh/tuangou/deal/queryshopdeal';
        $data = [
            'timestamp'=>time(),
            'appAuthToken'=>self::shop_token1['accessToken'],
            'charset'=>'utf-8',
            'version'=>'2',
            'developerId'=>self::developerId,
            'businessId'=>58,
            'biz'=>json_encode([
                'offset'=>$offset,
                'limit'=>100,
                "source"=>2,
            ],JSON_UNESCAPED_UNICODE)
        ];
        $sign_data = self::get_sign(self::assessKey, $data);
        $data['sign'] = $sign_data;
        return http_request($url,http_build_query($data));
    }

    /**
     * 商家改约
     * @param $offset
     * @return string
     */
    public static function merchantmodify($data)
    {
        $url = 'https://api-open-cater.meituan.com/ddzh/yuding/lifereserve/merchantmodify';
        $opBizCode = !empty($data['request_msg'])?json_decode($data['request_msg'],true)['opBizCode']:'';
        $accessToken = $opBizCode == 'AE7MKOJAV67338LIC3UD0K5TGIO' ? self::shop_token2['accessToken'] : self::shop_token1['accessToken'];
        $data = [
            'timestamp'=>time(),
            'appAuthToken'=>$accessToken,
            'charset'=>'utf-8',
            'version'=>'2',
            'developerId'=>self::developerId,
            'businessId'=>58,
            'biz'=>json_encode([
                'reserveOrderId'=>$data['reserveOrderId'],
                'reserveUserName'=>$data['reserveUserName'],
                "reservePhone"=>$data['reservePhone'],
                "reserveAddress"=>$data['reserveAddress'],
                "bookStartTime"=>$data['bookStartTime'],
                "bookEndTime"=>$data['bookEndTime'],
            ],JSON_UNESCAPED_UNICODE)
        ];
        $sign_data = self::get_sign(self::assessKey, $data);
        $data['sign'] = $sign_data;
        return http_request($url,http_build_query($data));
    }

    /**
     * 商家取消预定
     * @param $params
     * @return string|true
     */
    public static function merchantcancelorder($work_id)
    {
        return '';
        $third_order = ThirdOrders::where('work_id',$work_id)->findOrEmpty();
        if(!$third_order->isEmpty() && !empty($third_order['request_msg']) && $third_order['third_type']==1){
            Log::write('取消美团订单'.$work_id);
            $third_order->bookStatus = 3;
            $third_order->save();
            $url = 'https://api-open-cater.meituan.com/ddzh/yuding/merchantcancelorder';
            $opBizCode = !empty($third_order['request_msg'])?json_decode($third_order['request_msg'],true)['opBizCode']:'';
            $accessToken = $opBizCode == 'AE7MKOJAV67338LIC3UD0K5TGIO' ? self::shop_token2['accessToken'] : self::shop_token1['accessToken'];
            $data = [
                'timestamp'=>time(),
                'appAuthToken'=>$accessToken,
                'charset'=>'utf-8',
                'version'=>'2',
                'developerId'=>self::developerId,
                'businessId'=>58,
                'biz'=>json_encode([
                    'orderId'=>$third_order['orderId'],
                    'cancelReason'=>'取消预定',
                    "type"=>2,
                ],JSON_UNESCAPED_UNICODE)
            ];
            $sign_data = self::get_sign(self::assessKey, $data);
            $data['sign'] = $sign_data;
            return http_request($url,http_build_query($data));
        }
        return true;


    }

    /**
     * 更新履约状态
     * @param $work
     * @return string|void
     */
    public static function updateorderfulfillinfo($work,$orderFulfillStatus)
    {
        return '';
        //http_request('https://developer.kyjlkj.com/platf/Kaidianbao/performanceSecurity',http_build_query(['orderFulfillStatus'=>$orderFulfillStatus]));
        $third_order = ThirdOrders::where('work_id',$work['id'])->findOrEmpty();
        if(!$third_order->isEmpty() && !empty($third_order['request_msg'])) {
//        家政/维修更新顺序：已分配（40001）→ 已到达（40002）→ 履约完成（41001）
            $app_sku_id = ThirdGoods::where('product_id',$third_order['productId'])->value('app_sku_id');
            //判断当前履约状态
            $pic_url = 'https://cdnweixiu.kyjlkj.com/uploads/images/20240914/2024091414471041c336653.png';
            switch ($orderFulfillStatus){
                case '40001':
                    $describe = '已分配';
                    break;
                case '40002':
                    $describe = '已到达';
                    break;
                case '41001':
                    $describe = '履约完成';
                    $pic_url = !empty($work['finished_images'][0])?$work['finished_images'][0]:$pic_url;
                    break;
                default:
                    $describe = '未知';
                    break;
            }
            $url = 'https://api-open-cater.meituan.com/ddzh/yuding/updateorderfulfillinfo';
            $opBizCode = !empty($third_order['request_msg']) ? json_decode($third_order['request_msg'], true)['opBizCode'] : '';
            $accessToken = $opBizCode == 'AE7MKOJAV67338LIC3UD0K5TGIO' ? self::shop_token2['accessToken'] : self::shop_token1['accessToken'];
            $data = [
                'timestamp' => time(),
                'appAuthToken' => $accessToken,
                'charset' => 'utf-8',
                'version' => '2',
                'developerId' => self::developerId,
                'businessId' => 58,
                'biz' => json_encode([
                    'orderId' => $third_order['orderId'],
                    'attrKeyValue' => [
                        'service_voucher' => [
                            'detail_list' => [
                                [
                                    'app_sku_id' => $app_sku_id,
                                    'describe' => $describe,
                                    'pic_url' => $pic_url
                                ]
                            ]
                        ],
                        'delivery_info' => '无',
                        'delivery_type' => 3
                    ],
                    "type" => 2,
                    "orderFulfillStatus" => $orderFulfillStatus
                ], JSON_UNESCAPED_UNICODE)
            ];
            $sign_data = self::get_sign(self::assessKey, $data);
            $data['sign'] = $sign_data;
            return http_request($url, http_build_query($data));
        }
    }

    /**
     * 商家改约
     * @param $offset
     * @return string
     */
    public static function changeresultcallback($reserveOrderId)
    {
        $url = 'https://api-open-cater.meituan.com/ddzh/yuding/changeresultcallback';
        $opBizCode = !empty($data['request_msg'])?json_decode($data['request_msg'],true)['opBizCode']:'';
        $accessToken = $opBizCode == 'AE7MKOJAV67338LIC3UD0K5TGIO' ? self::shop_token2['accessToken'] : self::shop_token1['accessToken'];
        $data = [
            'timestamp'=>time(),
            'appAuthToken'=>$accessToken,
            'charset'=>'utf-8',
            'version'=>'2',
            'developerId'=>self::developerId,
            'businessId'=>58,
            'biz'=>json_encode([
                'reserveOrderId'=>$reserveOrderId,
                'changeOrderResult'=>2,
                "code"=>200,
            ],JSON_UNESCAPED_UNICODE)
        ];
        $sign_data = self::get_sign(self::assessKey, $data);
        $data['sign'] = $sign_data;
        return http_request($url,http_build_query($data));
    }

}