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.base.log.LogTreadLocal;
import cn.freemud.base.util.DateUtil;
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.Orderservice;
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.DateTimeUtil;
import cn.freemud.utils.LogUtil;
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.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.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.response.order.QueryOrdersResponse;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
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.util.ArrayList;
import java.util.Arrays;
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.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Slf4j
@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;

    @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());
        if (StringUtils.isNotBlank(request.getRemark()))
        {
            requestDto.setRemark("配送:"+request.getRemark());
        }
        OrderBaseResponse orderBaseResponseDto = orderCenterSdkService.updateDeliveryInfoById(requestDto);
        //订单服务修改配送单信息失败
        if (!SUCCESS_RESPONSE_CODE.equals(orderBaseResponseDto.getErrcode())) {
            LogUtil.error("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()) {
            // 订单配送
            sendPosService(deliveryStatus,posBaseRequestDto);
        } else if (deliveryStatus == DeliveryStatus.DELIVERYARRIVED.getCode()) {
            // 订单已完成
            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());
            // 取消外卖中台配送单 订单异常
            // 如果 "配送单异常并且顾客更改配送地址" 不取消配送单
            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);
            }
            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);
            }
            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());
            com.freemud.application.sdk.api.ordercenter.response.BaseResponse baseResponse = orderSdkService.collectOrder(orderCollectReq, LogTreadLocal.getTrackingNo());
            if(ResponseConstant.SUCCESS_RESPONSE_CODE_STR.equals(baseResponse.getCode())) {
                ResponseUtil.error(ResponseResult.ORDER_COLLECT_FAILED);
            }
            //回调成功，记录汇集状态
            updateDeliveryStatus(request);
            return ResponseUtil.success();
        }
        sendMcCafeMicroMessage(request.getPartnerId(), request.getOrderId(), request.getDeliveryStatus());
        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)) {
                log.info("isDeliveryAbnormalAndCustomerChangedAddress.true of {}", JSONObject.toJSONString(request));
                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);
    }

    /**
     * 配送单异常取消配送单
     */
    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(!mcCafePartnerId.equals(partnerId)) {
            return;
        }
        try {
            SubscribeMessageRequest request = new SubscribeMessageRequest();
            request.setOrderCode(orderId);

            BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
            baseQueryOrderRequest.setOrderId(orderId);
            baseQueryOrderRequest.setTrackingNo(LogTreadLocal.getTrackingNo());
            QueryOrderByIdResponse response = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);
            if(!ResponseConstant.SUCCESS_RESPONSE_CODE.equals(response.getErrcode())) {
                log.error("麦咖啡订阅消息推送失败，查询订单信息失败:"+JSON.toJSONString(response));
            }
            QueryOrdersResponse.DataBean.OrderBean orderBean = response.getData();
            if(OrderClientType.WE_CHAT.getIndex().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())
                        .address(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())
                        .orderAmount(orderBean.getActualPayAmount().toString())
                        .utcTime(cn.freemud.base.util.DateUtil.convert2String(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .build());
            }
            ecologyAdminApplicationClient.subscribeMessage(request);


        }catch (Exception e){
            log.error("麦咖啡订阅消息推送失败:"+orderId, e);
        }
    }

    /**
     * 配送消息推送
     */
    public void  sendMicroMessage(String partnerId,String orderId,int deliveryStatus){
        //如果商户配置了配送订阅消息推送
        if(deliveryMicroMessagePartner.contains(partnerId)){
            try {
                BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
                baseQueryOrderRequest.setOrderId(orderId);
                baseQueryOrderRequest.setTrackingNo(LogTreadLocal.getTrackingNo());
                QueryOrderByIdResponse response = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);
                QueryOrdersResponse.DataBean.OrderBean 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){
                log.error("配送订阅消息推送失败:{},失败原因:{}",orderId,e.getMessage());
            }
        }
    }
}
