package cn.freemud.service.delivery;

import cn.freemud.adapter.MessageNoticeAdapter;
import cn.freemud.amp.service.ProduceMQService;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.entities.dto.delivery.*;
import cn.freemud.entities.dto.ecology.*;
import cn.freemud.entities.dto.pos.PosBaseRequestDto;
import cn.freemud.entities.vo.delivery.DeliveryAmountVo;
import cn.freemud.enums.*;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.management.entities.dto.request.order.OrderManagerRequest;
import cn.freemud.management.entities.dto.response.order.OrderManagerResponse;
import cn.freemud.management.enums.OperateType;
import cn.freemud.management.service.adapter.OrderManagerAdapter;
import cn.freemud.service.ThirdDeliveryService;
import cn.freemud.service.thirdparty.DeliveryFeiginClient;
import cn.freemud.service.thirdparty.EcologyAdminApplicationClient;
import cn.freemud.service.thirdparty.PosClient;
import cn.freemud.utils.AppLogUtil;
import cn.freemud.utils.DateTimeUtil;
import cn.freemud.utils.ResponseUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freemud.application.sdk.api.constant.ResponseConstant;
import com.freemud.application.sdk.api.deliverycenter.dto.CancelDeliveryOrderRequestDto;
import com.freemud.application.sdk.api.deliverycenter.response.DeliveryInfoDto;
import com.freemud.application.sdk.api.deliverycenter.response.DeliveryResponseDto;
import com.freemud.application.sdk.api.deliverycenter.service.DeliveryService;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.enums.NewOrderStatus;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.enums.OrderType;
import com.freemud.application.sdk.api.ordercenter.request.OrderCollectReq;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import com.freemud.application.sdk.api.storecenter.request.StoreInfoRequest;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import com.freemud.application.sdk.api.structure.request.PushMessageNoticeDto;
import com.freemud.application.sdk.api.structure.service.MessageCenterClient;
import com.freemud.sdk.api.assortment.order.request.order.AssortmentUpdateDeliveryAbnormalRequest;
import com.freemud.sdk.api.assortment.order.request.order.BaseQueryOrderRequest;
import com.freemud.sdk.api.assortment.order.request.order.UpdateDeliveryInfoByIdRequest;
import com.freemud.sdk.api.assortment.order.response.order.OrderBaseResponse;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrderByIdResponse;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.6.0
 * @Title: ThirdDeliveryServiceImpl
 * @Description: 配送服务
 * @author: qin.zhou
 * @date: 2019/6/1119:55
 * @Copyright: ${DATE.YARE} www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
public class ThirdDeliveryServiceImpl implements ThirdDeliveryService {

    private final static Integer SUCCESS_RESPONSE_CODE = 100;
    @Autowired
    private DeliveryService deliveryService;
    @Autowired
    private OrderCenterSdkService orderCenterSdkService;
    @Autowired
    private PosClient posClient;
    @Autowired
    private ProduceMQService produceMQService;
    @Autowired
    private DeliveryFeiginClient deliveryFeiginClient;
    @Autowired
    private OrderManagerAdapter orderManagerAdapter;
    @Autowired
    private OrderSdkService orderSdkService;
    @Autowired
    private MessageNoticeAdapter messageNoticeAdapter;
    @Autowired
    private MessageCenterClient messageNoticeClient;
    @Value("${delivery.micro.message.partner}")
    private String deliveryMicroMessagePartner;
    @Value("${mccafe.partner.id}")
    private String mcCafePartnerId;
    @Autowired
    private EcologyAdminApplicationClient ecologyAdminApplicationClient;
    @Autowired
    private StoreCenterService storeCenterService;

    private final String deliveryEarlyWarningMsg = "运单预警";


    @Override
    public BaseResponse callbackUrl(CallbackUrlRequestDto request) {
        // 获取回调状态
        int deliveryStatus = request.getDeliveryStatus();
        // 获取配送单信息
        DeliveryResponseDto<DeliveryInfoDto> delivery = deliveryService.deliveryOrderOne(request.getDeliveryId(), LogThreadLocal.getTrackingNo());
        if (SUCCESS_RESPONSE_CODE != delivery.getCode() || delivery.getData() == null) {
            return ResponseUtil.error(ResponseResult.DELIVERY_QUERY_ERROR);
        }
        String partnerId = delivery.getData().getPartnerId();
        String storeCode = delivery.getData().getStoreCode();
        // 调用订单服务修改运单号，第三方运单号，骑手信息，运单状态
        UpdateDeliveryInfoByIdRequest requestDto = new UpdateDeliveryInfoByIdRequest();
        requestDto.setOrderId(request.getOrderId());
        requestDto.setDeliveryId(request.getDeliveryId());
        requestDto.setCourierName(request.getRiderName());
        requestDto.setCourierPhone(request.getRiderPhone());
        requestDto.setExpress(request.getChannelCode());
        requestDto.setExpressChannelName(request.getChannelName());
        requestDto.setExpressNo(request.getChannelDeliveryId());
        requestDto.setOrderSubState(deliveryStatus);
        requestDto.setRemark(request.getRemark());
        requestDto.setExceptionDesc(request.getExceptionDesc());
        requestDto.setExceptionId(request.getExceptionId());
        //【ID1031049】 订单接受配送分配骑手状态回调
        requestDto.setEstimateArriveTime(request.getEstimateArriveTime());
        // 【ID1032317】外卖配送完成回调订单基础服务接口添加商户承担运费字段
        requestDto.setBusinessDeliveryAmount(request.getBusinessDeliveryAmount());
        if (StringUtils.isNotBlank(request.getRemark())) {
            requestDto.setRemark("配送:" + request.getRemark());
        }
        OrderBaseResponse orderBaseResponseDto = orderCenterSdkService.updateDeliveryInfoById(requestDto);
        //订单服务修改配送单信息失败
        if (!SUCCESS_RESPONSE_CODE.equals(orderBaseResponseDto.getErrcode())) {
            AppLogUtil.printLog("updateDeliveryInfoById_error", JSONObject.toJSONString(requestDto), JSONObject.toJSONString(orderBaseResponseDto));
            return ResponseUtil.success();
        }
        PosBaseRequestDto posBaseRequestDto = new PosBaseRequestDto();
        posBaseRequestDto.setOrder_id(request.getOrderId());
        posBaseRequestDto.setPartner_id(partnerId);
        if (deliveryStatus == DeliveryStatus.ALLOTRIDER.getCode()) {
            //骑手接单推送POS服务
            posBaseRequestDto.setStore_id(storeCode);
            posBaseRequestDto.setRider_name(request.getRiderName());
            posBaseRequestDto.setRider_phone(request.getRiderPhone());
            posBaseRequestDto.setDelivery_status(DeliveryStatus.ALLOTRIDER.getCode());
            posBaseRequestDto.setPartner_id(partnerId);
            sendPosService(deliveryStatus, posBaseRequestDto);
        } else if (deliveryStatus == DeliveryStatus.RIDERGETMEAL.getCode() || deliveryStatus == DeliveryStatus.RIDERSTARTDELIVERY.getCode()) {
            // 订单配送
            posBaseRequestDto.setHorseman(true);
            sendPosService(deliveryStatus, posBaseRequestDto);
        } else if (deliveryStatus == DeliveryStatus.DELIVERYARRIVED.getCode()) {
            // 订单已完成
            posBaseRequestDto.setHorseman(true);
            sendPosService(deliveryStatus, posBaseRequestDto);
        } else if (deliveryStatus == DeliveryStatus.DELIVERYERROR.getCode() || deliveryStatus == DeliveryStatus.DELIVERYCANCEL.getCode()) {
            Integer sendPosDeliveryStatus;
            if (deliveryStatus == DeliveryStatus.DELIVERYERROR.getCode()) {
                sendPosDeliveryStatus = 71;
            } else {
                sendPosDeliveryStatus = 81;
            }
            sendPosMessage(partnerId, storeCode, request.getOrderId(), sendPosDeliveryStatus, request.getRemark());
            //推送异常到生态
            sendException(request.getOrderId(), request.getExceptionDesc(), request.getUpdateTime(), DeliveryStatus.getDeliveryStatusByCode(deliveryStatus).getDesc());
            // 取消外卖中台配送单 订单异常
            // 如果 "配送单异常并且顾客更改配送地址" 不取消配送单
//            if (!isDeliveryAbnormalAndCustomerChangedAddress(request)) {
//                partnerCancelOrder(request.getDeliveryId());
//            }
            // 运单异常，取消订单
            posBaseRequestDto.setReason("没有骑手接单");
            posBaseRequestDto.setDeliveryId(request.getDeliveryId());
            sendPosService(deliveryStatus, posBaseRequestDto);
        }

        // 订单配送状态变化时发送到MQ
        if (DeliveryStatus.checkDeliveryStatueForPlatform(deliveryStatus)) {
            produceMQService.sendOfDeliveryInfo(request);
            produceMQService.sendRocketMqOfDeliveryInfo(request);
        }
        //配送订阅消息
        sendMicroMessage(partnerId, request.getOrderId(), deliveryStatus);

//        else {
//            return ResponseUtil.error(ResponseResult.SYSTEM_ERROR.getCode(), "订单回调状态有误");
//        }
        return ResponseUtil.success();
    }

    /**
     * 配送回调
     *
     * @param request
     */
    @Override
    public BaseResponse macCafeCallbackUrl(MacCafeCallbackUrlRequestDto request) {
        OrderManagerRequest orderManagerRequest = new OrderManagerRequest();
        orderManagerRequest.setPartnerId(request.getPartnerId());
        orderManagerRequest.setOrderId(request.getOrderId());
        if ("1".equals(request.getCancelApplicant())) {
            orderManagerRequest.setReason(StringUtils.isNotBlank(request.getCancelReason()) ? request.getCancelReason() : "餐道主动取消");
        } else {
            orderManagerRequest.setReason(null);
        }
        orderManagerRequest.setOperator("配送回调");


        Integer reviewStatus = request.getReviewStatus();
        int deliveryStatus = request.getDeliveryStatus();
        if (reviewStatus != null && reviewStatus.equals(DeliveryReviewStatus.AGREE.getCode())) {
            orderManagerRequest.setOperateType(OperateType.ORDER_AGREE_REFUND.getOpType());
            orderManagerRequest.setReason("配送回调-同意退款");
            return orderManagerAdapter.orderPayRefund(orderManagerRequest);
        }
        if (reviewStatus != null && reviewStatus.equals(DeliveryReviewStatus.REJECT.getCode())) {
            orderManagerRequest.setOperateType(OperateType.ORDER_REJECT_REFUND.getOpType());
            orderManagerRequest.setReason("配送回调-拒绝退款");
            return orderManagerAdapter.mcCafeOrderRejectRefund(orderManagerRequest);
        }
        if (deliveryStatus == DeliveryStatus.RIDERGETMEAL.getCode() || deliveryStatus == DeliveryStatus.RIDERSTARTDELIVERY.getCode()) {
            orderManagerRequest.setOperateType(OperateType.ORDER_SEND.getOpType());
            BaseResponse<OrderManagerResponse> baseResponse = orderManagerAdapter.orderDelivery(orderManagerRequest);
            if (ResponseConstant.SUCCESS_RESPONSE_CODE_STR.equals(baseResponse.getCode())) {
                updateDeliveryStatus(request);
            }
            sendMcCafeMicroMessage(request.getPartnerId(), request.getOrderId(), request.getDeliveryStatus());
            return baseResponse;
        } else if (deliveryStatus == DeliveryStatus.DELIVERYARRIVED.getCode()) {
            orderManagerRequest.setOperateType(OperateType.ORDER_AFFIRM.getOpType());
            BaseResponse<OrderManagerResponse> baseResponse = orderManagerAdapter.orderAffirm(orderManagerRequest, null);
            if (ResponseConstant.SUCCESS_RESPONSE_CODE_STR.equals(baseResponse.getCode())) {
                updateDeliveryStatus(request);
            }
            sendMcCafeMicroMessage(request.getPartnerId(), request.getOrderId(), request.getDeliveryStatus());
            return baseResponse;
        } else if (deliveryStatus == DeliveryStatus.WATINGORDER.getCode() || deliveryStatus == DeliveryStatus.SYSTEMGETORDER.getCode()
                || deliveryStatus == DeliveryStatus.ALLOTRIDER.getCode() || deliveryStatus == DeliveryStatus.RIDERARRIVESTORE.getCode()) {
            updateDeliveryStatus(request);
            return ResponseUtil.success();
        } else if (deliveryStatus == DeliveryStatus.COLLECTING.getCode()) {
            //推送订单到拉单队列
            OrderCollectReq orderCollectReq = new OrderCollectReq();
            orderCollectReq.setOrderCode(request.getOrderId());
            orderCollectReq.setPartnerId(request.getPartnerId());
            OrderBaseResp baseResponse = orderSdkService.collectOrder(orderCollectReq, LogThreadLocal.getTrackingNo());
            if (ResponseConstant.SUCCESS_RESPONSE_CODE_STR.equals(baseResponse.getCode())) {
                ResponseUtil.error(ResponseResult.ORDER_COLLECT_FAILED);
            }
            //回调成功，记录汇集状态
            updateDeliveryStatus(request);
            return ResponseUtil.success();
        } else if (deliveryStatus == DeliveryStatus.DELIVERYERROR.getCode()) {
            AssortmentUpdateDeliveryAbnormalRequest assortmentUpdateDeliveryAbnormalRequest = AssortmentUpdateDeliveryAbnormalRequest.builder()
                    .abnormalDesc(request.getRemark())
                    .deliveryId(request.getDeliveryId())
                    .orderCode(request.getOrderId())
                    .partnerId(request.getPartnerId())
                    .operator("餐道")
                    .build();
            orderCenterSdkService.updateDeliveryAbnormal(assortmentUpdateDeliveryAbnormalRequest);
            return ResponseUtil.success();
        }
        return ResponseUtil.error(ResponseResult.ORDER_DELIVERY_CALL_BACK_FAILED);
    }

    private OrderBaseResponse updateDeliveryStatus(MacCafeCallbackUrlRequestDto request) {
        UpdateDeliveryInfoByIdRequest updateDeliveryInfoByIdRequest = new UpdateDeliveryInfoByIdRequest();
        updateDeliveryInfoByIdRequest.setOrderId(request.getOrderId());
        updateDeliveryInfoByIdRequest.setOrderSubState(request.getDeliveryStatus());
        updateDeliveryInfoByIdRequest.setOperator("sys");
        if (StringUtils.isNotBlank(request.getRiderPhone())) {
            updateDeliveryInfoByIdRequest.setCourierPhone(request.getRiderPhone());
        }
        if (StringUtils.isNotBlank(request.getRiderName())) {
            updateDeliveryInfoByIdRequest.setCourierName(request.getRiderName());
        }
        return orderCenterSdkService.updateDeliveryInfoById(updateDeliveryInfoByIdRequest);
    }

    /**
     * 配送单异常并且顾客更改配送地址
     *
     * @return
     */
    public boolean isDeliveryAbnormalAndCustomerChangedAddress(CallbackUrlRequestDto request) {
        if (DeliveryStatus.DELIVERYERROR.getCode() != request.getDeliveryStatus()) return false;
        if (StringUtils.isBlank(request.getRemark())) return false;

        List<String> abnormalDesc = Lists.newArrayList("顾客更改配送地址", "顾客更改收货地址", "顾客更改送货地址");
        for (String str : abnormalDesc) {
            if (request.getRemark().contains(str)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public BaseResponse mallCallbackUrl(CallbackUrlRequestDto request) {
        return ResponseUtil.success();
    }

    @Override
    public BaseResponse<DeliveryAmountVo> queryDeliveryAmount(WeixinDeliveryAddressDto request) {

        QueryDeliveryAmountRequestDto requestDto = new QueryDeliveryAmountRequestDto();
        requestDto.setPartnerId(request.getPartnerId());
        requestDto.setProvince(request.getProvinceName());
        QueryDeliveryAmountResponseDto responseDto = deliveryFeiginClient.queryDeliveryAmount(requestDto);
        if (responseDto == null || SUCCESS_RESPONSE_CODE != responseDto.getCode() || CollectionUtils.isEmpty(responseDto.getData())) {
            return ResponseUtil.error(ResponseResult.DELIVERY_INFO_NOT_DELIVERY);
        }

        DeliveryAmountVo deliveryAmountVo = new DeliveryAmountVo();
        QueryDeliveryAmountResponseDto.QueryDeliveryAmountResult amountResult = responseDto.getData().get(0);
        deliveryAmountVo.setId(amountResult.getId());
        deliveryAmountVo.setPartnerId(amountResult.getPartnerId());
        deliveryAmountVo.setProvinceName(amountResult.getSendProvince());
        deliveryAmountVo.setDeliveryAmount(amountResult.getDeliveryAmount().intValue());
        return ResponseUtil.success(deliveryAmountVo);
    }

    @Override
    public BaseResponse errorCallbackUrl(CallbackUrlRequestDto request) {
        // pos获取回调状态
        sendPosMessage(request.getPartnerId(), request.getStoreId(), request.getOrderId(), 71, request.getErrorDesc());
        //生态回调
        sendException(request.getOrderId(),  request.getErrorDesc(),  request.getErrorCreateTime(),  deliveryEarlyWarningMsg);
        return ResponseUtil.success();
    }

    /**
     * 配送单异常取消配送单
     */
    public BaseResponse partnerCancelOrder(String deliveryId) {
        CancelDeliveryOrderRequestDto deliveryOrderRequestDto = new CancelDeliveryOrderRequestDto();
        deliveryOrderRequestDto.setDeliveryId(deliveryId);
        deliveryOrderRequestDto.setOrderCancelCode(4);
        deliveryOrderRequestDto.setOrderCancelDescription("运单异常，商户取消订单");
        String trackingNo = "";
        DeliveryResponseDto responseDto = deliveryService.deliveryOrderCancel(deliveryOrderRequestDto, trackingNo);
        if (SUCCESS_RESPONSE_CODE != responseDto.getCode()) {
            throw new ServiceException(ResponseResult.DELIVERY_CANCEL_ORDER_ERROR);
        }
        return ResponseUtil.success();
    }

    /**
     * 配送订单回调同步POS服务
     */
    public BaseResponse sendPosService(Integer deliveryStatus, PosBaseRequestDto posBaseRequestDto) {
        BaseResponse response = null;
        if (deliveryStatus == DeliveryStatus.ALLOTRIDER.getCode()) {
            response = posClient.deliveryRiderStatus(posBaseRequestDto);
        } else if (deliveryStatus == DeliveryStatus.RIDERGETMEAL.getCode() || deliveryStatus == DeliveryStatus.RIDERSTARTDELIVERY.getCode()) {
            // 告知订单配送
            response = posClient.posSend(posBaseRequestDto);
        } else if (deliveryStatus == DeliveryStatus.DELIVERYARRIVED.getCode()) {
            // 告知订单已完成
            response = posClient.posAffirm(posBaseRequestDto);
        } else if (deliveryStatus == DeliveryStatus.DELIVERYERROR.getCode() || deliveryStatus == DeliveryStatus.DELIVERYCANCEL.getCode()) {
            // 更新订单状态为异常单
            updateDeliveryAbnormal(posBaseRequestDto.getPartner_id(), posBaseRequestDto.getOrder_id(), posBaseRequestDto.getDeliveryId());
        }
        return response;
    }

    /**
     * 更新订单为异常单
     *
     * @param partnerCode
     * @param orderCode
     * @param deliveryId
     */
    private void updateDeliveryAbnormal(String partnerCode, String orderCode, String deliveryId) {
        AssortmentUpdateDeliveryAbnormalRequest request = AssortmentUpdateDeliveryAbnormalRequest.builder()
                .abnormalDesc("配送异常")
                .deliveryId(deliveryId)
                .orderCode(orderCode)
                .partnerId(partnerCode).build();
        orderCenterSdkService.updateDeliveryAbnormal(request);
    }

    /**
     * 发送pos端消息
     */
    public void sendPosMessage(String partnerId, String storeId, String orderId, Integer deliveryStatus, String errorMsg) {

        PushMessageNoticeDto pushMessageNoticeDto = new PushMessageNoticeDto();
        pushMessageNoticeDto.setPartnerId(partnerId);
        pushMessageNoticeDto.setStoreId(storeId);
        pushMessageNoticeDto.setTargetId(null);
        pushMessageNoticeDto.setTargetType(2);
        pushMessageNoticeDto.setCmd(11);
        cn.freemud.entities.dto.PushMessageNoticeDto.Message message = new cn.freemud.entities.dto.PushMessageNoticeDto.Message();
        message.setType(1);
        cn.freemud.entities.dto.PushMessageNoticeDto.Message.Content content = new cn.freemud.entities.dto.PushMessageNoticeDto.Message.Content();
        content.setOid(orderId);
        content.setDeliveryStatus(deliveryStatus);
        content.setErrorMsg(errorMsg);
        message.setContent(content);

        pushMessageNoticeDto.setData(new Gson().toJson(message));
        messageNoticeClient.createMessage(pushMessageNoticeDto, LogThreadLocal.getTrackingNo());
    }

    /**
     * 麦咖啡配送消息推送
     */
    public void sendMcCafeMicroMessage(String partnerId, String orderId, int deliveryStatus) {
        if ((deliveryStatus != DeliveryStatus.RIDERSTARTDELIVERY.getCode() && deliveryStatus != DeliveryStatus.DELIVERYARRIVED.getCode())
                || !mcCafePartnerId.equals(partnerId)) {
            AppLogUtil.infoLog("不发消息 orderId:{}", orderId,null);
            return;
        }
        try {
            SubscribeMessageRequest request = new SubscribeMessageRequest();
            request.setOrderCode(orderId);

            BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
            baseQueryOrderRequest.setOrderId(orderId);
            baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
            QueryOrderByIdResponse response = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);
            if (!ResponseConstant.SUCCESS_RESPONSE_CODE.equals(response.getErrcode())) {
                AppLogUtil.infoLog("麦咖啡订阅消息推送失败，查询订单信息失败:{} {}" ,null, JSON.toJSONString(response));
            }
            OrderBeanV1 orderBean = response.getData();
            if (OrderClientType.SAAS.getIndex().toString().equals(orderBean.getOrderClient())) {
                request.setChannel(1);
            } else {
                return;
            }

            OrderExtInfoDto extInfoDto = JSONObject.parseObject(orderBean.getExtInfo(), new TypeReference<OrderExtInfoDto>() {
            });
            request.setMiniAppId(extInfoDto.getAppid());
            List<String> userList = new ArrayList<>();
            userList.add(extInfoDto.getOpenid());
            request.setOpenIdList(userList);

            if (deliveryStatus == DeliveryStatus.RIDERSTARTDELIVERY.getCode()) {
                request.setMessageEventType(MessageEventTypeEnum.MCCAFE_DELIVERY_ORDER.getType());
                request.setScene(MessageSceneEnum.MCCAFE_DELIVERY_ORDER.getDesc());
                request.setMccafeDeliveryOrder(MccafeDeliveryOrder
                        .builder()
                        .orderId(orderBean.getOid())
                        .displayOrderId(orderBean.getDownstreamThirdOrderCode())
                        .address(orderBean.getAddress().length() > 20 ? orderBean.getAddress().substring(0, 17) + "..." : orderBean.getAddress())
                        .build());
            } else if (deliveryStatus == DeliveryStatus.DELIVERYARRIVED.getCode()) {
                request.setMessageEventType(MessageEventTypeEnum.MCCAFE_COMPLETE_ORDER.getType());
                request.setScene(MessageSceneEnum.MCCAFE_COMPLETE_ORDER.getDesc());
                request.setMccafeCompleteOrder(MccafeCompleteOrder
                        .builder()
                        .orderId(orderBean.getOid())
                        .displayOrderId(orderBean.getDownstreamThirdOrderCode())
                        .orderAmount(new BigDecimal(orderBean.getActualPayAmount()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).toString())
                        .utcTime(cn.freemud.base.util.DateUtil.convert2String(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .build());
            } else {
                return;
            }
            ecologyAdminApplicationClient.subscribeMessage(request);
        } catch (Exception e) {
            AppLogUtil.errorLog("麦咖啡订阅消息推送失败 orderId:{}" , orderId ,null, e);
        }
    }

    /**
     * 配送消息推送
     */
    public void sendMicroMessage(String partnerId, String orderId, int deliveryStatus) {
        //如果商户配置了配送订阅消息推送
        if (deliveryMicroMessagePartner.contains(partnerId)) {
            try {
                BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
                baseQueryOrderRequest.setOrderId(orderId);
                baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
                QueryOrderByIdResponse response = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);
                OrderBeanV1 orderBean = response.getData();
                SubscribeMessageRequest request = new SubscribeMessageRequest();
                OrderExtInfoDto extInfoDto = JSONObject.parseObject(orderBean.getExtInfo(), new TypeReference<OrderExtInfoDto>() {
                });
                request.setMiniAppId(extInfoDto.getAppid());
                List<String> userList = new ArrayList<>();
                userList.add(extInfoDto.getOpenid());
                request.setOpenIdList(userList);
                request.setScene("scene_delivery");
                //默认微信
                request.setChannel(1);
                //支付宝
                if ("3".equals(orderBean.getOrderClient())) {
                    request.setChannel(2);
                }
                //配送订阅模板消息
                if (deliveryStatus == DeliveryStatus.ALLOTRIDER.getCode()) {
                    request.setMessageEventType("ORDER_DELIVERY");
                    OrderDeliveryScene orderDeliveryScene = new OrderDeliveryScene();
                    orderDeliveryScene.setAddress(orderBean.getAddress());
                    Long createTime = orderBean.getGmtCreate();
                    // 获取门店信息
                    StoreInfoRequest storeInfoRequest = new StoreInfoRequest(partnerId, orderBean.getShopId(), null);
                    StoreResponse storeResponse = storeCenterService.getStoreInfo(storeInfoRequest, LogThreadLocal.getTrackingNo());
                    //立即单外卖
                    if (OrderType.GENERAL_EXPRESS.getIndex() == orderBean.getNewOrderType()) {
                        if (storeResponse != null && storeResponse.getBizVO() != null && storeResponse.getBizVO().getServiceTime() != null) {
                            createTime = createTime + storeResponse.getBizVO().getServiceTime() * 1000 * 60;
                            orderDeliveryScene.setEstimateArrivalTime(DateTimeUtil.timeStampToTime(createTime));
                        }
                    }//预约单外卖
                    if (OrderType.RESERVED_EXPRESS.getIndex() == orderBean.getNewOrderType() && orderBean.getGmtExpect() != null) {
                        orderDeliveryScene.setEstimateArrivalTime(DateTimeUtil.timeStampToTime(orderBean.getGmtExpect()));
                    }
                    orderDeliveryScene.setMerchantPhone(storeResponse.getBizVO().getPhone());
                    orderDeliveryScene.setOrderNo(orderId);
                    request.setOrderDeliveryScene(orderDeliveryScene);
                    ecologyAdminApplicationClient.subscribeMessage(request);
                }
                //配送异常模板消息
                if (deliveryStatus == DeliveryStatus.DELIVERYCANCEL.getCode() || deliveryStatus == DeliveryStatus.DELIVERYERROR.getCode()) {
                    request.setMessageEventType("DELIVERY_ERROR_REMINDER");
                    DeliveryErrorReminder deliveryErrorReminder = new DeliveryErrorReminder();
                    deliveryErrorReminder.setCreateTime(DateTimeUtil.timeStampToTime(orderBean.getGmtCreate()));
                    deliveryErrorReminder.setOrderId(orderId);
                    deliveryErrorReminder.setMerchantPhone(orderBean.getShopPhone());
                    deliveryErrorReminder.setAddress(orderBean.getAddress());
                    deliveryErrorReminder.setRemark("订单配送异常，请电话联系门店确认哦");
                    request.setDeliveryErrorReminder(deliveryErrorReminder);
                    ecologyAdminApplicationClient.subscribeMessage(request);
                }

            } catch (Exception e) {
                AppLogUtil.errorLog("配送订阅消息推送失败:{},失败原因:{}", orderId, "", e);
            }
        }
    }

    /**
     * 通知生态发送调用消息
     */
    public void sendException(String orderId, String unusualReason, String unusualTime, String desc) {
        BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
        baseQueryOrderRequest.setOrderId(orderId);
        baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        QueryOrderByIdResponse response = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);
        OrderBeanV1 orderBean = response.getData();
        SubscribeMessageRequest request = new SubscribeMessageRequest();
        OrderExtInfoDto extInfoDto = JSONObject.parseObject(orderBean.getExtInfo(), new TypeReference<OrderExtInfoDto>() {
        });
        String messageType = "UNUSUAL_ORDER";
        if (deliveryEarlyWarningMsg.equals(desc)) {
            messageType = "DELIVERY_REMIND";
            if (orderBean.getStatusV2() != null && NewOrderStatus.getByCode(orderBean.getStatusV2()) != null) {
                desc = NewOrderStatus.getByCode(orderBean.getStatusV2()).getName();
            }
        }
        request.setMiniAppId(extInfoDto.getAppid());
        SendMessageRequest sendMessageRequest = new SendMessageRequest();
        sendMessageRequest.setMessageType(messageType);
        sendMessageRequest.setMiniAppId(extInfoDto.getAppid());
        sendMessageRequest.setOrderId(orderId);
        sendMessageRequest.setPartnerId(orderBean.getCompanyId());
        sendMessageRequest.setRemark(unusualReason);
        sendMessageRequest.setStoreId(orderBean.getShopId());
        sendMessageRequest.setOrderStatus(desc);
        sendMessageRequest.setUtcTime(unusualTime);
        SendMessageResponse sendMessageResponse = ecologyAdminApplicationClient.sendTemplateMessage(sendMessageRequest);
    }




}
