package com.bohuikeji.delivery.backstage.service.third;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bohuikeji.delivery.backstage.constants.KeyConst;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.open.vo.CourierVo;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.entity.vo.CourierAddressVo;
import com.bohuikeji.delivery.backstage.listener.order.OrderAliCenterListener;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.base.ThirdBase;
import com.bohuikeji.delivery.backstage.thread.OrderReviewThread;
import com.bohuikeji.delivery.backstage.thread.ThirdThread;
import com.bohuikeji.delivery.backstage.util.maiyatian.maltUtils;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.thread.CachedThreadPool;
import com.bohuikeji.frame.module.admin.utils.SpringUtil;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.bohuikeji.frame.module.admin.utils.YiXunGmsUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.bohuikeji.delivery.backstage.service.third.base.ThirdBase.getCacheKey;
import static com.bohuikeji.delivery.backstage.service.third.base.ThirdBase.getCacheKeyPix;

/**
 * 第三方服务工具类
 * 统一下单，取消订单、查询订单等操作
 * 自动识别第三方
 * @author 孙劲辉
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ThirdUtils {

    final ITOrderService orderService;
    final ITPayService payService;
    final ITCustomerWalletService walletService;
    final ITNewsService newsService;
    final ITRefundService refundService;
    final IGmsService gmsService;
    final ITDiscountOrderService discountService;
    final RedisUtil redisUtil;
    final IThirdInfoService thirdInfoService;
    final MqTool mqTool;

    /**
     * 获取第三方服务类
     * @param serverName 第三方注册名称
     * @return
     */
    public static ThirdBase getServer(String serverName){
        return SpringUtil.getBean(ThirdBase.getRegisters().get(serverName));
    }

    /**
     * 获取Redis缓存
     * @param orderNum
     * @param thirdName
     * @return
     */
    public OrderDetailDO getRedisDetail(String orderNum,String thirdName){
        OrderDetailDO detail= redisUtil.get(ThirdBase.getCacheKey(orderNum,thirdName),OrderDetailDO.class);
        log.error("快递100回调通知详情4：{}",detail);
        TOrder order;
        if (detail==null){
            order=orderService.getByNum(orderNum);
            if (order.getThird()){
                APIEntity<OrderDetailDO> res=getServer(order.getThirdName()).orderDetail(order.getOrderNum(),order.getThirdNum());
                if (res.checkSuccess()){
                    detail=res.getBody();
                }
            }
        }
        return detail;
    }

    /**
     * 更新Redis缓存
     * @param detail
     */
    public void updateRedisDetail(OrderDetailDO detail){
        redisUtil.set(ThirdBase.getCacheKey(detail.getOrderNumber(),detail.getThirdName()),detail, Duration.ofDays(180).getSeconds());
    }



    /**
     * 第三方统一下单
     * 该方法将对所有已注册的第三方运力服务进行询价并下单
     * @param order 系统订单实体
     */
    public static void orderPlace(TOrder order){
        ThirdBase.getRegisters().forEach((k, v)->{
            try {
                CachedThreadPool.execute(new ThirdThread(SpringUtil.getBean(v),order));
            } catch (Exception e) {
                log.error("【第三方下单业务异常】下单线程异常，订单号：{}，业务类：{}",order.getOrderNum(),v);
                log.error("【第三方下单业务异常】定位：",e);
                e.printStackTrace();
            }
        });
    }

    /**
     * 取消订单
     */
    public static void orderCancel(TOrder order){
        if (order.getThird()){
            getServer(order.getThirdName()).orderCancel(order.getOrderNum(),order.getThirdNum());
        }else {
            orderCancelAll(order.getOrderNum());
        }

    }

    /**
     * 向所有第三方取消订单取消订单
     * @param orderNum
     */
    public static void orderCancelAll(String orderNum){
        RedisUtil rdsTmp= SpringUtil.getBean(RedisUtil.class);
        List<OrderDetailDO> doList=rdsTmp.getListByPattern(getCacheKeyPix(orderNum)+"*",OrderDetailDO.class);
        doList.forEach(d->{
            getServer(d.getThirdName()).orderCancel(d.getOrderNumber(),d.getThirdNum());
        });
    }

    /**
     * 查询第三方订单变更记录
     * @param thirdName 第三方名称
     * @param orderNum 订单号
     * @param thirdNum 第三方单号
     * @return
     */
    public static List<TOrderCircu> orderRecords(String thirdName,String orderNum,String thirdNum){
        return getServer(thirdName).orderRecord(orderNum,thirdNum);
    }

    /**
     * 向其他第三方取消订单
     * 【解释】当其中一个第三方接单后，需要将订单通知其他第三方取消。避免出现多个配送机构同时接到同一个订单的情况
     * @param order
     */
    public void orderCancelOther(TOrder order) {
        String thirdName = order.getThirdName();
        ThirdBase.getRegisters().forEach((k, v) -> {
            if (!thirdName.equals(k)) {
                OrderDetailDO detail = getRedisDetail(order.getOrderNum(), k);
                if (detail != null) {
                    SpringUtil.getBean(v).orderCancel(detail.getOrderNumber(), detail.getThirdNum());
                }
            }
        });
    }

    /**
     * 查询订单详情
     * @param order
     * @return
     */
    public  OrderDetailDO orderDetail(TOrder order){
        OrderDetailDO detail=getRedisDetail(order.getOrderNum(),order.getThirdName());
        if (detail==null){
            if (order.getThird()){
                APIEntity<OrderDetailDO> res=getServer(order.getThirdName()).orderDetail(order.getOrderNum(),order.getThirdNum());
                if (res.checkSuccess()){
                    detail=res.getBody();
                }
            }
        }
        log.error("订单22222：{}",detail);
        return detail;
    }

    /**
     * 查询订单骑手详情
     * @param order
     * @return
     */
    public CourierVo courierInfo(TOrder order){
        CourierVo couriervo=getServer(order.getThirdName()).courierInfo(order.getOrderNum(),order.getThirdNum()).getBody();
        return couriervo;
    }

    /**
     * 查询订单骑手详情
     * @param order
     * @return
     */
    public void addOrderTip(TOrder order,BigDecimal tipAmount){
        ThirdBase.getRegisters().forEach((k, v) -> {
            OrderDetailDO detail= redisUtil.get(ThirdBase.getCacheKey(order.getOrderNum(),k),OrderDetailDO.class);
            if (detail != null) {
                log.info("加小费时获取订单推送返回结果：{}",detail);
                SpringUtil.getBean(v).orderTip(detail.getOrderNumber(),detail.getThirdNum(),tipAmount);
            }
        });
    }

    /**
     * 获取订单推送结果
     * @param orderNum 订单号
     * @return
     */
    public APIEntity<OrderDetailDO> orderResult(String orderNum,String thirdName){
        String key=getCacheKey(orderNum,thirdName).replaceFirst("third","result");
        return redisUtil.get(key,APIEntity.class);
    }

    /**
     * 第三方订单统一回调
     * @param detail 订单详情
     */
    public void callBack(OrderDetailDO detail, JSONObject req) {
        log.error("【第三方回调进入】第三方名称：{}，订单：{}，缓存信息：{}",detail.getThirdName(),detail.getThirdNum(), detail);
        this.updateRedisDetail(detail);
        //获取第三方状态集合
        Map<String, String> statusMap = ThirdBase.getNoticeStatus(detail.getThirdName());
        TOrder order = orderService.getByNum(detail.getOrderNumber());
        //当第三方名称不为空，切第三方订单名称不等于回调名称，则取消其他第三方订单
        if (StringUtils.isNotBlank(order.getThirdName()) && (!order.getThirdName().equals(detail.getThirdName()))) {
            orderCancelOther(order);
            return;
        }
        String status = statusMap.get(detail.getStatus());
        //骑手ID不为空，且不等于11392这个骑手，说明订单被系统接了，需要取消订单，后续改成按状态判断
        if ((order.getCourierId() != null) && (!Integer.valueOf(11392).equals(order.getCourierId()))) {
            if ("cancel".equals(status)) {
                return;
            }
            log.error("【非第三方订单进入，取消第三方订单】订单：{}", order.getOrderNum());
            ThirdUtils.orderCancelAll(order.getOrderNum());
            return;
        }
        //无意义状态直接推出
        if (StringUtils.isBlank(status)) {
            return;
        }
        switch (status) {
            case "wait":
                log.error("【回调进去派单中】{}", detail);
                if(req.getInteger("subStatus")==2){
                    order.setOrderStatus("改派中");
                    order.setThirdStatus("转单改派中");
                    /*order.setCourierId(null);
                    order.setCourierPhone(null);*/
                }
                break;
            //取货中
            case "accept":
                if ("已取消".equals(order.getOrderStatus()) || "已退款".equals(order.getOrderStatus())) {
                    log.error("【回调订单状态异常】订单：{}，已经取消了。", order.getOrderNum());
                    orderCancelAll(detail.getOrderNumber());
                    break;
                }
                order.setCourierId(11392);
                order.setCourierPhone(detail.getCourierPhone());
                order.setAcceptanceTime(LocalDateTime.now());
                order.setThirdStatus("取件中");
                order.setThird(true);
                order.setThirdName(detail.getThirdName());
                order.setThirdNum(detail.getThirdNum());
                order.setThirdPrice(detail.getOrderPrice());
                //SQL更新
                orderService.update(new UpdateWrapper<TOrder>().set("order_status", "取件中").set("is_third", 1).set("third_name", detail.getThirdName()).set("third_num", detail.getThirdNum()).set("third_price", detail.getOrderPrice())
                        .set("third_status", "取件中").eq("order_id", order.getOrderId()));
                if (order.getOrderFactPrice().compareTo(new BigDecimal("0")) < 1) {
                    order.setOrderStatus("待支付");
                    if ("寄付".equals(order.getPaymentType())) {
                        TCustomerWallet tCustomerWallet = walletService.getOne(new QueryWrapper<TCustomerWallet>().eq("customer_id", order.getPlayerId()));
                        //钱包扣费
                        if (tCustomerWallet != null && tCustomerWallet.getWalletPrice().compareTo(order.getOrderExpectPrice()) > -1) {
                            TPay pay = payService.createBeforePay(order, "业务支付", "客户支付", "钱包");
                            payService.walletPay(pay, tCustomerWallet, order);
                            //向客户推送订阅消息
                            orderService.post(order.getOrderId(), "该订单已从钱包自动扣费。");
                        }
                        //提示支付
                        else {
                            //插入订单流转记录
                            TOrderCircu.insertCircu(order);
                            //向客户推送订阅消息
                            orderService.post(order.getOrderId(), "配送员已接单，请您尽快完成支付...");
                            //发送短信提示客户支付
                            Map<String, Object> params = new HashMap<>(2);
                            params.put("order", order.getOrderNum());
                            params.put("courier", detail.courierInfo());
                            //发送短信
                            gmsService.thirdMessage(order.getMailingPhone(),order.getOrderNum(), "SMS_ORDER_THIRD_30_pay", params);
                        }
                    }
                } else {
                    Map<String, Object> params = new HashMap<>(2);
                    params.put("order", order.getOrderNum());
                    params.put("courier", detail.courierInfo());
                    //发送短信
                    gmsService.thirdMessage(order.getMailingPhone(), order.getOrderNum(),"SMS_ORDER_THIRD_30", params);
                    order.setOrderStatus("取件中");
                    order.setAcceptanceTime(LocalDateTime.now());
                }
                //接单成功取消其他订单
                this.orderCancelOther(order);
                thirdInfoService.add(detail);
                break;
            //闪送中
            case "run":
                order.setThirdStatus("派送中");
                order.setConfirmPickTime(LocalDateTime.now());
                String estimateTime = detail.getEstimateTime();
                if (StringUtils.isBlank(estimateTime)) {
                    estimateTime = "";
                }
                if (order.getOrderFactPrice().compareTo(new BigDecimal("0")) < 1) {
                    Map<String, Object> params = new HashMap<>(2);
                    params.put("order", order.getOrderNum());
                    params.put("desc", params.put("desc", estimateTime));
                    orderService.post(order.getOrderId(), "您的订单开始配送，请您尽快完成支付...");
                    //发送短信提示客户支付
                    gmsService.thirdMessage(order.getMailingPhone(), order.getOrderNum(),"SMS_ORDER_THIRD_40_pay", params);
                } else {
                    Map<String, Object> params = new HashMap<>(2);
                    params.put("order", order.getOrderNum());
                    params.put("desc", estimateTime);
                    gmsService.thirdMessage(order.getMailingPhone(), order.getOrderNum(),"SMS_ORDER_THIRD_40", params);
                    order.setOrderStatus("派送中");
                    order.setConfirmPickTime(LocalDateTime.now());
                    gmsService.sendOrderSend(order.getReceiptPhone(),order.getOrderNum());
                }
                log.error("订单准备复核：{}，第三方服务商：{}",order.getOrderNum(),order.getThirdName());
                //取件后复核订单
                try {
                    CachedThreadPool.execute(new OrderReviewThread(getServer(order.getThirdName()),order.getOrderNum(), order.getThirdNum()));
                } catch (Exception e) {
                    log.error("",e);
                    e.printStackTrace();
                }
                break;
            //已完成
            case "end":
                order.setThirdStatus("已完成");
                if (order.getOrderFactPrice().compareTo(new BigDecimal("0")) < 1) {
                    orderService.post(order.getOrderId(), "您的订单已送达，不要忘记付款哦...");
                    Map<String, Object> params = new HashMap<>(2);
                    params.put("order", order.getOrderNum());
                    params.put("courier", detail.courierInfo());
                    //发送短信
                    gmsService.thirdMessage(order.getMailingPhone(), order.getOrderNum(),"SMS_ORDER_THIRD_50_pay", params);
                } else {
                    order.setOrderStatus("已完成");
                    order.setOrderEndTime(LocalDateTime.now());
                    Map<String, Object> params = new HashMap<>(2);
                    params.put("order", order.getOrderNum());
                    params.put("courier", detail.courierInfo());
                    //发送短信
                    gmsService.thirdMessage(order.getMailingPhone(),order.getOrderNum(), "SMS_ORDER_THIRD_50", params);
                    gmsService.sendOrderEnd(order.getReceiptPhone(), order.getOrderNum());
                    //推送小程序通知
                    newsService.pushCustomerMsg1(order.getPlayerId(), "订单完成通知", "尊敬的客户您好,您的订单{0}，已经配送完成，感谢您的信赖！", order.getOrderNum());
                }
                APIEntity<OrderDetailDO> res=getServer(detail.getThirdName()).orderDetail(detail.getOrderNumber(),detail.getThirdNum());
                if (res.checkSuccess())
                {   //订单完成更新一次订单金额
                    detail=res.getBody();
                    log.error("第三方订单跟踪：{}",detail);
                    orderService.update(new UpdateWrapper<TOrder>()
                            .eq("order_num",detail.getOrderNumber())
                            .set("third_price",detail.getOrderPrice()));
                }
                order.setThirdPrice(detail.getOrderPrice());
                //删除缓存
                redisUtil.del(ThirdBase.getCacheKey(detail.getOrderNumber(), detail.getThirdName()));
                break;
            //取消订单
            case "cancel":
                //不是自己的订单，不能取消
                if (!detail.getThirdName().equals(order.getThirdName())) {
                    return;
                }
                if ("已取消".equals(order.getOrderStatus())) {
                    log.error("订单已{}经主动取消了", order.getOrderNum());
                    order.setOrderRemarks("客户主动取消");
                    order.setThirdStatus("已取消");
                    break;
                }
                //如果是闪送取消则需要识别闪送类型
                if (ShansongServer.NAME.equals(detail.getThirdName())) {
                    Integer type = req.getInteger("abortType");
                    if (type.equals(1)) {
                        order.setCancelType(1);
                    }
                    if (type.equals(3)) {
                        order.setCancelType(5);
                    }
                    if (type.equals(10)) {
                        order.setCancelType(6);
                    }
                }
                //删除缓存
                redisUtil.del(ThirdBase.getCacheKey(detail.getOrderNumber(), detail.getThirdName()));
                order.setOrderStatus("已取消");
                order.setOrderEndTime(LocalDateTime.now());
                /*order.setOrderRemarks("第三方订单取消");*/
                order.setThirdStatus("已取消");
                if (order.getOrderFactPrice().compareTo(new BigDecimal("0")) > 0) {
                    List<TPay> tPays = payService.list(new QueryWrapper<TPay>().eq("order_id", order.getOrderId()).eq("pay_status", "已支付"));
                    if (tPays.size() > 0) {
                        //退款
                        refundService.cancel(order, tPays);
                    } else {
                        log.error("【第三取消回调异常】客户已支付，但是未找到支付记录，订单号：{}", order.getOrderNum());
                        //发送无服务短信通知
                        gmsService.sendNoServerMsg(order.getMailingPhone(), order.getMailingAddress().getCity());
                        //发送消息中心消息
                        AddressVo ads = order.getMailingAddress();
                        newsService.pushCustomerMsg1(order.getPlayerId(), "订单取消通知",
                                "尊敬的客户您好，由于{0}的该区域运力不足，暂时无法为您提供配送服务，系统已为您取消订单{1}，给您带来的不便敬请谅解！", ads.getProvince() + ads.getCity(), order.getOrderNum());
                        //待接单：超过规定时间无人接单，向客户推送订阅消息
                        orderService.cancelOrder("当前运力紧张，系统已为您取消订单", order);
                        if (!order.getDisId().equals(0)) {
                            //优惠卷恢复位置用状态
                            discountService.cancelOrderDisByVoucher(order);
                        }
                    }
                }
                break;
            default:
                break;
        }
        TOrderCircu.insertCircu(order);
        orderService.updateById(order);
        if("麦芽田".equals(order.getOrderChannel())){
            CourierVo courierVo= courierInfo(order);
            log.info("第三方骑手的信息：{}",courierVo);
            orderService.satusFlow(courierVo,order);
        }
        mqTool.sendMsg(order.getOrderNum(), OrderAliCenterListener.class);
        order.updateById();
    }

    /**
     * 快递100订单信息回调处理
     * @param detail 订单详情
     */
    public void kdCallBack(OrderDetailDO detail, JSONObject req) {
        log.error("【第三方回调进入】订单：{}，缓存信息：{}，回调信息：{}", detail.getThirdNum(), detail,req.toJSONString());
        this.updateRedisDetail(detail);
        TOrder order = orderService.getByNum(detail.getOrderNumber());
        //当第三方名称不为空，切第三方订单名称不等于回调名称，则取消其他第三方订单
        /*if (StringUtils.isNotBlank(order.getThirdName()) && (!order.getThirdName().equals(detail.getThirdName()))) {
            orderCancelOther(order);
            return;
        }*/
        String status = detail.getStatus();
        //骑手ID不为空，且不等于11392这个骑手，说明订单被系统接了，需要取消订单，后续改成按状态判断
       /* if ((order.getCourierId() != null) && (!Integer.valueOf(11392).equals(order.getCourierId()))) {
            if ("cancel".equals(status)) {
                return;
            }
            log.error("【非第三方订单进入，取消第三方订单】订单：{}", order.getOrderNum());
            this.orderCancelOther(order);
            ThirdUtils.orderCancelAll(order.getOrderNum());
            return;
        }*/
        //无意义状态直接推出
       /* if (StringUtils.isBlank(status)) {
            return;
        }*/
        switch (status) {
            //司机已接单
            case "1":
                order.setThirdStatus("已接单");
                order.setCourierId(11392);
                order.setCourierPhone(detail.getCourierPhone());
                order.setThirdNum(detail.getThirdNum());
                order.setThird(true);
                order.setOrderStatus("待取件");
                order.setAcceptanceTime(LocalDateTime.now());
                Map<String, Object> params = new HashMap<>(2);
                params.put("order", order.getOrderNum());
                params.put("courier", detail.courierInfo());
                //接单成功取消其他订单
                //this.orderCancelOther(order);
                gmsService.thirdMessage(order.getMailingPhone(), order.getOrderNum(),"SMS_ORDER_THIRD_30", params);
                break;
            case "2":
                order.setThirdStatus("收件中");
                order.setOrderStatus("取件中");
                break;
            case "10":
                order.setThirdStatus("已取件");
                order.setOrderStatus("待派送");
                order.setThirdPrice(detail.getOrderPrice());
                order.setConfirmPickTime(LocalDateTime.now());
                break;
            case "101":
                order.setThirdStatus("运输中");
                order.setOrderStatus("派送中");
                gmsService.sendOrderSend(order.getReceiptPhone(),order.getOrderNum());
                break;
            case "13":
                order.setThirdStatus("已签收");
                order.setOrderStatus("已完成");
                order.setOrderEndTime(LocalDateTime.now());
                Map<String, Object> paramsa = new HashMap<>(2);
                paramsa.put("order", order.getOrderNum());
                paramsa.put("courier", detail.courierInfo());
                //发送短信
                gmsService.thirdMessage(order.getMailingPhone(), order.getOrderNum(),"SMS_ORDER_THIRD_50", paramsa);
                //推送小程序通知
                newsService.pushCustomerMsg1(order.getPlayerId(), "订单完成通知", "尊敬的客户您好,您的订单{0}，已经配送完成，感谢您的信赖！", order.getOrderNum());
                break;
            //用户已取消订单
            case "9":
                order.setOrderStatus("已取消");
                order.setThirdStatus("用户主动取消");
                order.setOrderEndTime(LocalDateTime.now());
                break;
            case "99":
                //不是自己的订单，不能取消
                if (!detail.getThirdName().equals(order.getThirdName())) {
                    return;
                }
                if ("已取消".equals(order.getOrderStatus())) {
                    log.error("订单已{}经主动取消了", order.getOrderNum());
                    order.setOrderRemarks("客户主动取消");
                    order.setThirdStatus("已取消");
                    break;
                }
                //如果是闪送取消则需要识别闪送类型
                order.setCancelType(6);
                //删除缓存
                redisUtil.del(ThirdBase.getCacheKey(detail.getOrderNumber(), detail.getThirdName()));
                order.setOrderStatus("已取消");
                order.setOrderEndTime(LocalDateTime.now());
                /*order.setOrderRemarks("第三方订单取消");*/
                order.setThirdStatus("已取消");
                if (order.getOrderFactPrice().compareTo(new BigDecimal("0")) > 0) {
                    List<TPay> tPays = payService.list(new QueryWrapper<TPay>().eq("order_id", order.getOrderId()).eq("pay_status", "已支付"));
                    if (tPays.size() > 0) {
                        //退款
                        refundService.cancel(order, tPays);
                    } else {
                        log.error("【第三取消回调异常】客户已支付，但是未找到支付记录，订单号：{}", order.getOrderNum());
                        //发送无服务短信通知
                        gmsService.sendNoServerMsg(order.getMailingPhone(), order.getMailingAddress().getCity());
                        //发送消息中心消息
                        AddressVo ads = order.getMailingAddress();
                        newsService.pushCustomerMsg1(order.getPlayerId(), "订单取消通知",
                                "尊敬的客户您好，由于{0}的该区域运力不足，暂时无法为您提供配送服务，系统已为您取消订单{1}，给您带来的不便敬请谅解！", ads.getProvince() + ads.getCity(), order.getOrderNum());
                        //待接单：超过规定时间无人接单，向客户推送订阅消息
                        orderService.cancelOrder("当前运力紧张，系统已为您取消订单", order);
                        if (!order.getDisId().equals(0)) {
                            //优惠卷恢复位置用状态
                            discountService.cancelOrderDisByVoucher(order);
                        }
                    }
                }
                break;
            default:
                break;
        }
        if("已完成".equals(order.getOrderStatus())){
            Map<String, Object> paramsa = new HashMap<>(2);
            paramsa.put("order", order.getOrderNum());
            paramsa.put("courier", detail.courierInfo());
            //发送短信
            gmsService.thirdMessage(order.getMailingPhone(), order.getOrderNum(),"SMS_ORDER_THIRD_50", paramsa);
            //推送小程序通知
            newsService.pushCustomerMsg1(order.getPlayerId(), "订单完成通知", "尊敬的客户您好,您的订单{0}，已经配送完成，感谢您的信赖！", order.getOrderNum());
        }
        TOrderCircu.insertCircu(order);
        orderService.updateById(order);
        mqTool.sendMsg(order.getOrderNum(), OrderAliCenterListener.class);
        order.updateById();
    }


    /**
     * 快递100订单信息回调处理
     * @param detail 订单详情
     */
    public void kdInfoCallBack(OrderDetailDO detail, JSONObject req) {
        //log.error("【第三方回调进入】订单：{}，缓存信息：{}，回调信息：{}", detail.getThirdNum(), detail,req.toJSONString());
        this.updateRedisDetail(detail);
        //获取第三方状态集合
        Map<String, String> statusMap = ThirdBase.getNoticeStatus(detail.getThirdName());
        TOrder order = orderService.getByNum(detail.getOrderNumber());
        //当第三方名称不为空，切第三方订单名称不等于回调名称，则取消其他第三方订单
        if (StringUtils.isNotBlank(order.getThirdName()) && (!order.getThirdName().equals(detail.getThirdName()))) {
            orderCancelOther(order);
            return;
        }
        String status = detail.getStatus();
        //骑手ID不为空，且不等于11392这个骑手，说明订单被系统接了，需要取消订单，后续改成按状态判断
        if ((order.getCourierId() != null) && (!Integer.valueOf(11392).equals(order.getCourierId()))) {
            if ("cancel".equals(status)) {
                return;
            }
            log.error("【非第三方订单进入，取消第三方订单】订单：{}", order.getOrderNum());
            this.orderCancelOther(order);
            ThirdUtils.orderCancelAll(order.getOrderNum());
            return;
        }
        //无意义状态直接推出
        if (StringUtils.isBlank(status)) {
            return;
        }
        switch (status) {
            //用户已取消订单
            case "6":
                order.setOrderStatus("退回");
                order.setThirdStatus("已取消");
                break;
            //司机已接单
            case "102":
                order.setThirdStatus("待揽收");
                order.setCourierId(11392);
                order.setThirdNum(detail.getThirdNum());
                order.setThird(true);
                order.setOrderStatus("取件中");
                Map<String, Object> params = new HashMap<>(2);
                params.put("order", order.getOrderNum());
                params.put("courier", detail.courierInfo());
                //接单成功取消其他订单
                //this.orderCancelOther(order);
                gmsService.thirdMessage(order.getMailingPhone(), order.getOrderNum(),"SMS_ORDER_THIRD_30", params);
                break;
            case "103":
                order.setThirdStatus("已揽收");
                order.setOrderStatus("待派送");
                break;
            case "0":
                order.setThirdStatus("在途");
                order.setOrderStatus("派送中");
                break;
            //司机接单后拒绝，订单自动取消
            case "1001":
                order.setThirdStatus("到达派件城市");
                order.setOrderStatus("派送中");
                break;
            case "1002":
                order.setThirdStatus("干线");
                order.setOrderStatus("派送中");
                break;
            case "1003":
                order.setThirdStatus("转递");
                order.setOrderStatus("派送中");
                break;
            case "5":
                order.setThirdStatus("派件");
                order.setOrderStatus("派送中");
                break;
            case "501":
                order.setThirdStatus("投柜或驿站");
                order.setOrderStatus("派送中");
                break;
            case "3":
                order.setThirdStatus("签收");
                order.setOrderStatus("已完成");
                break;
            case "301":
                order.setThirdStatus("本人签收");
                order.setOrderStatus("已完成");
                break;
            case "302":
                order.setThirdStatus("派件异常后签收");
                order.setOrderStatus("已完成");
                break;
            case "303":
                order.setThirdStatus("代签");
                order.setOrderStatus("已完成");
                break;
            case "304":
                order.setThirdStatus("投柜或驿站签收");
                order.setOrderStatus("已完成");
                break;
            case "4":
                order.setThirdStatus("退签");
                order.setOrderStatus("已取消");
                break;
            case "401":
                order.setThirdStatus("已销单");
                order.setOrderStatus("已取消");
                break;
            case "14":
                order.setThirdStatus("拒签");
                order.setOrderStatus("已取消");
                break;
            default:
                break;
        }
        if("已完成".equals(order.getOrderStatus())){
            Map<String, Object> paramsa = new HashMap<>(2);
            paramsa.put("order", order.getOrderNum());
            paramsa.put("courier", detail.courierInfo());
            //发送短信
            gmsService.thirdMessage(order.getMailingPhone(), order.getOrderNum(),"SMS_ORDER_THIRD_50", paramsa);
            //推送小程序通知
            newsService.pushCustomerMsg1(order.getPlayerId(), "订单完成通知", "尊敬的客户您好,您的订单{0}，已经配送完成，感谢您的信赖！", order.getOrderNum());
        }
        TOrderCircu.insertCircu(order);
        orderService.updateById(order);
        mqTool.sendMsg(order.getOrderNum(), OrderAliCenterListener.class);
        order.updateById();
    }

    /**
     * 货拉拉回调
     * @param detail 订单详情
     */
    public void hllCallBack(OrderDetailDO detail, JSONObject req) {
        //log.error("【第三方回调进入】订单：{}，缓存信息：{}，回调信息：{}", detail.getThirdNum(), detail,req.toJSONString());
        this.updateRedisDetail(detail);
        //获取第三方状态集合
        Map<String, String> statusMap = ThirdBase.getNoticeStatus(detail.getThirdName());
        TOrder order = orderService.getByNum(detail.getOrderNumber());
        //当第三方名称不为空，切第三方订单名称不等于回调名称，则取消其他第三方订单
        if (StringUtils.isNotBlank(order.getThirdName()) && (!order.getThirdName().equals(detail.getThirdName()))) {
            orderCancelOther(order);
            return;
        }
        String status = detail.getStatus();
        //骑手ID不为空，且不等于11392这个骑手，说明订单被系统接了，需要取消订单，后续改成按状态判断
        if ((order.getCourierId() != null) && (!Integer.valueOf(11392).equals(order.getCourierId()))) {
            if ("cancel".equals(status)) {
                return;
            }
            log.error("【非第三方订单进入，取消第三方订单】订单：{}", order.getOrderNum());
            this.orderCancelOther(order);
            ThirdUtils.orderCancelAll(order.getOrderNum());
            return;
        }
        //无意义状态直接推出
        if (StringUtils.isBlank(status)) {
            return;
        }
        switch (status) {
            //用户已取消订单
            case "3002":
                if("HLL".equals(order.getThirdName())){
                    order.setOrderStatus("已取消");
                    order.setThirdStatus("已取消");
                }
                break;
            //司机已接单
            case "3003":
                if("分配中".equals(order.getThirdStatus())){
                    order.setThirdStatus("已接单");
                }
                if("分配中(2)".equals(order.getThirdStatus())){
                    order.setThirdStatus("已接单(2)");
                }
                order.setCourierId(11392);
                order.setThirdNum(detail.getThirdNum());
                order.setThird(true);
                order.setOrderStatus("待取件");
                Map<String, Object> params = new HashMap<>(2);
                params.put("order", order.getOrderNum());
                params.put("courier", detail.courierInfo());
                //接单成功取消其他订单
                this.orderCancelOther(order);
                gmsService.thirdMessage(order.getMailingPhone(), order.getOrderNum(),"SMS_ORDER_THIRD_30", params);
                break;
            //司机接单后拒绝，订单自动取消
            case "3005":
                if("已接单".equals(order.getThirdStatus())){
                    order.setOrderStatus("待接单");
                    order.setThirdStatus("分配中(2)");
                }
                if("已接单(2)".equals(order.getThirdStatus())){
                    //删除缓存
                    redisUtil.del(ThirdBase.getCacheKey(detail.getOrderNumber(), detail.getThirdName()));
                    order.setOrderStatus("已取消");
                    order.setThirdStatus("拒单取消");
                    order.setOrderEndTime(LocalDateTime.now());
                    if (order.getOrderFactPrice().compareTo(new BigDecimal("0")) > 0) {
                        List<TPay> tPays = payService.list(new QueryWrapper<TPay>().eq("order_id", order.getOrderId()).eq("pay_status", "已支付"));
                        if (tPays.size() > 0) {
                            //退款
                            refundService.cancel(order, tPays);
                        } else {
                            log.error("【第三取消回调异常】客户已支付，但是未找到支付记录，订单号：{}", order.getOrderNum());
                            //发送无服务短信通知
                            gmsService.sendNoServerMsg(order.getMailingPhone(), order.getMailingAddress().getCity());
                            //发送消息中心消息
                            AddressVo ads = order.getMailingAddress();
                            newsService.pushCustomerMsg1(order.getPlayerId(), "订单取消通知",
                                    "尊敬的客户您好，由于{0}的该区域运力不足，暂时无法为您提供配送服务，系统已为您取消订单{1}，给您带来的不便敬请谅解！", ads.getProvince() + ads.getCity(), order.getOrderNum());
                            //待接单：超过规定时间无人接单，向客户推送订阅消息
                            orderService.cancelOrder("当前运力紧张，系统已为您取消订单", order);
                            if (!order.getDisId().equals(0)) {
                                //优惠卷恢复位置用状态
                                discountService.cancelOrderDisByVoucher(order);
                            }
                        }
                    }
                }
                break;
            //司机完成卸货，订单运送完成
            case "3006":
                order.setOrderStatus("已完成");
                order.setThirdStatus("运送完成");
                break;
            case "3008":
                order.setThirdStatus("现金结清");
                break;
            //司机装货完成
            case "3011":
                order.setThirdStatus("后置支付完成");
                break;
            //司机装货完成
            case "3012":
                order.setOrderStatus("派送中");
                order.setThirdStatus("运送中");
                break;
            //装货中
            case "3018":
                order.setOrderStatus("取件中");
                order.setThirdStatus("装货中");
                order.setConfirmPickTime(LocalDateTime.now());
                break;
            //卸货中
            case "3019":
                order.setThirdStatus("卸货中");
                break;
            //发送账单
            case "3021":
                order.setThirdStatus("发送账单");
                try {
                    order.setOrderRemarks("订单补充支付");
                    CachedThreadPool.execute(new OrderReviewThread(getServer(order.getThirdName()),order.getOrderNum(), order.getThirdNum()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            //司机运送完成后，48小时无操作订单自动完成
            case "3024":
                order.setOrderStatus("已完成");
                order.setThirdStatus("已完成");
                order.setOrderRemarks("司机运送完成后，48小时无操作订单自动完成");
                Map<String, Object> paramsa = new HashMap<>(2);
                paramsa.put("order", order.getOrderNum());
                paramsa.put("courier", detail.courierInfo());
                //发送短信
                gmsService.thirdMessage(order.getMailingPhone(), order.getOrderNum(),"SMS_ORDER_THIRD_50", paramsa);
                //推送小程序通知
                newsService.pushCustomerMsg1(order.getPlayerId(), "订单完成通知", "尊敬的客户您好,您的订单{0}，已经配送完成，感谢您的信赖！", order.getOrderNum());
                break;
            //订单超出配对时间，已自动取消
            case "3025":
                order.setOrderStatus("已取消");
                order.setThirdStatus("已取消");
                order.setOrderRemarks("货拉拉订单超出配对时间，已自动取消");
                AddressVo ads = order.getMailingAddress();
                newsService.pushCustomerMsg1(order.getPlayerId(), "订单取消通知",
                        "尊敬的客户您好，由于{0}的该区域运力不足，暂时无法为您提供配送服务，系统已为您取消订单{1}，给您带来的不便敬请谅解！", ads.getProvince() + ads.getCity(), order.getOrderNum());
                //待接单：超过规定时间无人接单，向客户推送订阅消息
                orderService.cancelOrder("当前运力紧张，系统已为您取消订单", order);
                break;
            //企业前置支付完成
            case "3028":
                //order.setOrderRemarks("企业前置支付完成");
                order.setThirdStatus("分配中");
                break;
            default:
                break;
        }
        TOrderCircu.insertCircu(order);
        orderService.updateById(order);
        mqTool.sendMsg(order.getOrderNum(), OrderAliCenterListener.class);
        order.updateById();
    }
}
