package com.freemud.sdk.api.assortment.order.service.order;

import cn.freemud.amqp.Header;
import cn.freemud.amqp.MQAction;
import cn.freemud.amqp.MQMessage;
import cn.freemud.amqp.MQService;
import cn.freemud.base.util.DateUtil;
import cn.freemud.base.util.JsonUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.manager.customer.AssortmentCustomerInfoManager;
import com.freemud.api.assortment.datamanager.meal.MealCacheManager;
import com.freemud.api.assortment.datamanager.order.config.ManagerOrderBeanConfig;
import com.freemud.api.assortment.datamanager.order.manager.AssortmentOrderManager;
import com.freemud.api.assortment.datamanager.order.vo.DMOrderItemVo;
import com.freemud.application.sdk.api.base.BaseResponse;
import com.freemud.application.sdk.api.couponcenter.offline.request.CouponLockRequest;
import com.freemud.application.sdk.api.couponcenter.offline.request.CouponRequest;
import com.freemud.application.sdk.api.couponcenter.offline.response.CouponLockResponse;
import com.freemud.application.sdk.api.couponcenter.offline.response.CouponRedeemResponse;
import com.freemud.application.sdk.api.couponcenter.offline.service.OfflineCouponSdkService;
import com.freemud.application.sdk.api.log.ApiLog;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.log.ThirdPartyLog;
import com.freemud.application.sdk.api.membercenter.request.GetMemberExtendInfoRequest;
import com.freemud.application.sdk.api.membercenter.request.SendPointRequest;
import com.freemud.application.sdk.api.membercenter.request.UserScoreRequest;
import com.freemud.application.sdk.api.membercenter.response.GetMemberExtendInfoResponse;
import com.freemud.application.sdk.api.membercenter.service.MemberCenterService;
import com.freemud.application.sdk.api.membercenter.service.MemberPropertyService;
import com.freemud.application.sdk.api.membercenter.service.MemberScoreService;
import com.freemud.application.sdk.api.ordercenter.enums.*;
import com.freemud.application.sdk.api.ordercenter.request.*;
import com.freemud.application.sdk.api.ordercenter.request.create.*;
import com.freemud.application.sdk.api.ordercenter.response.*;
import com.freemud.application.sdk.api.ordercenter.response.AfterSalesListResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.QueryByCodeResponse;
import com.freemud.application.sdk.api.ordercenter.service.OrderDownLoadSdkService;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import com.freemud.application.sdk.api.promotioncenter.dto.promotion.DiscountDTO;
import com.freemud.application.sdk.api.promotioncenter.request.promotion.ActivityUpdateStockRequest;
import com.freemud.application.sdk.api.promotioncenter.request.promotion.CalculationDiscountRequest;
import com.freemud.application.sdk.api.promotioncenter.response.CalculationDiscountResponseDTO;
import com.freemud.application.sdk.api.promotioncenter.service.PromotionSdkService;
import com.freemud.application.sdk.api.stockapi.request.UpdateStocksRequest;
import com.freemud.application.sdk.api.stockapi.service.StockSdkService;
import com.freemud.application.sdk.api.storecenter.enums.ActiveFlagEnum;
import com.freemud.application.sdk.api.storecenter.enums.OpenTableEnum;
import com.freemud.application.sdk.api.storecenter.request.ChangeTableOrderStateRequest;
import com.freemud.application.sdk.api.storecenter.request.GetStoreTableRequest;
import com.freemud.application.sdk.api.storecenter.request.StoreInfoRequest;
import com.freemud.application.sdk.api.storecenter.request.vo.GetOrgTreeListRequest;
import com.freemud.application.sdk.api.storecenter.response.GetStoreTableResponse;
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.MessageCenterType;
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.adapter.*;
import com.freemud.sdk.api.assortment.order.domain.ResponseCodeConstant;
import com.freemud.sdk.api.assortment.order.entities.OrderEditInfo;
import com.freemud.sdk.api.assortment.order.enums.*;
import com.freemud.sdk.api.assortment.order.request.order.CreateOrderRequest;
import com.freemud.sdk.api.assortment.order.request.order.OrderDownloadRequest;
import com.freemud.sdk.api.assortment.order.request.order.*;
import com.freemud.sdk.api.assortment.order.response.order.*;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse.DataBean.OrderBean;
import com.freemud.sdk.api.assortment.order.response.payment.OrderPayResponse;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import com.freemud.sdk.api.assortment.order.vo.AssortmentOrderProductVo;
import com.google.gson.Gson;
import com.mysql.jdbc.log.LogUtils;
import lombok.extern.log4j.Log4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.freemud.application.sdk.api.membercenter.constant.InterfaceAddressConstant.MEMBER_EXTEND_INFO;
import static com.freemud.sdk.api.assortment.order.domain.ResponseCodeConstant.RESPONSE_SUCCESS;
import static com.freemud.sdk.api.assortment.order.domain.ResponseCodeConstant.RESPONSE_SUCCESS_STR;

@Import(ManagerOrderBeanConfig.class)
@Service
public class OrderCenterSdkServiceImpl implements OrderCenterSdkService {

    @Autowired
    private StockSdkService stockSdkService;
    @Autowired
    private PromotionSdkService promotionSdkService;
    @Autowired
    private OrderSdkAdapter orderSdkAdapter;
    @Autowired
    private MemberSdkAdapter memberSdkAdapter;
    @Autowired
    private ActivitySdkAdapter activitySdkAdapter;
    @Autowired
    private MQService mqService;
    @Autowired
    private MemberScoreService memberScoreService;
    @Autowired
    private MemberPropertyService memberPropertyService;
    @Autowired
    private OrderSdkService orderSdkService;
    @Autowired
    private StoreCenterService storeCenterService;
    @Autowired
    private OrderDownLoadSdkService orderDownLoadSdkService;
    @Autowired
    private MealCacheManager mealCacheManager;
    @Autowired
    private AssortmentOrderManager assortmentOrderManager;
    @Autowired(required = false)
    private MessageCenterClient messageCenterClient;
    @Autowired
    private AssortmentCustomerInfoManager assortmentCustomerInfoManager;
    @Autowired
    private MemberCenterService memberCenterService;
    @Autowired
    private OfflineCouponSdkService offlineCouponSdkService;

    @Override
    public CreateOrderResponse createOrderFlow(CreateOrderRequest config) {
        com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest request = orderSdkAdapter.convent2NEWCreateOrderRequest(config.getBaseCreateOrderRequest());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<OrderInfoReqs> order = orderSdkService.createOrder(request, config.getTrackingNo());
        CreateOrderResponse createOrderResponse = orderSdkAdapter.convent2NEWOrderInfoReqs(order);
        if (!RESPONSE_SUCCESS.equals(createOrderResponse.getErrcode())
                || createOrderResponse.getData() == null) {
            return getCreateOrderResponse(createOrderResponse.getErrcode().toString(), createOrderResponse.getErrmsg(), null);
        }
        BaseOrderResponse baseOrderResponse = updateStockAndScore(createOrderResponse.getData(), config.getBaseCreateOrderRequest().getProducts(), config.getBaseCreateOrderRequest().getActivityUpdateStockRequest(),
                config.getBaseCreateOrderRequest().getAccounts(), config.getMqMessageRequest(),config.getBaseCreateOrderRequest().getMenuType());
        if (!RESPONSE_SUCCESS.equals(baseOrderResponse.getErrcode())) {
            return getCreateOrderResponse(baseOrderResponse.getErrcode().toString(), baseOrderResponse.getErrmsg(), null);
        }
        return createOrderResponse;
    }

    @Override
    public CreateFatherSonOrderResponse createFatherSonOrder(CreateFatherSonOrderRequest createFatherSonOrderRequest) {
        CreateFatherSonOrderReq request = orderSdkAdapter.convent2NEWCreateFatherSonOrderRequest(createFatherSonOrderRequest);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<List<OrderInfoReqs>> baseResponse = orderSdkService.createFatherSonOrder(request, createFatherSonOrderRequest.getTrackingNo());
        if (!RESPONSE_SUCCESS_STR.equals(baseResponse.getCode()) || baseResponse.getResult() == null) {
            return CreateFatherSonOrderResponse.error(baseResponse.getCode(), baseResponse.getMessage());
        }
        CreateFatherSonOrderResponse createFatherSonOrderResponse = orderSdkAdapter.convent2NEWFatherOrderInfoReqs(baseResponse);
        List<QueryOrdersResponse.DataBean.OrderBean> productOrderInfo = createFatherSonOrderResponse.getOrderBeanList().stream().filter(orderBeanTemp -> 1 == orderBeanTemp.getBizType()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(productOrderInfo)) {
            return CreateFatherSonOrderResponse.error("500", "");
        }
        CreateFatherSonOrderRequest.OrderInfo productOrderRequest = createFatherSonOrderRequest.getOrderInfoList().stream().filter(orderBeanTemp -> 1 == orderBeanTemp.getBizType()).collect(Collectors.toList()).get(0);
        BaseOrderResponse baseOrderResponse =updateStockAndScore(productOrderInfo.get(0), productOrderRequest.getProducts(), productOrderRequest.getActivityUpdateStockRequest(), productOrderRequest.getAccounts(),
                createFatherSonOrderRequest.getMqMessageRequest(),createFatherSonOrderRequest.getMenuType());
        if (!RESPONSE_SUCCESS.equals(baseOrderResponse.getErrcode())) {
            return CreateFatherSonOrderResponse.error(baseOrderResponse.getErrcode().toString(), baseOrderResponse.getErrmsg());
        }
        return createFatherSonOrderResponse;
    }

    /**
     * 开放平台专用
     * @param baseCreateOrderRequest
     * @return
     */
    @Override
    public CreateOrderResponse createOrder(BaseCreateOrderRequest baseCreateOrderRequest) {
        com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest request = orderSdkAdapter.convent2NEWCreateOrderRequest(baseCreateOrderRequest);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<OrderInfoReqs> order = orderSdkService.createOrderByPlatform(request, baseCreateOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2NEWOrderInfoReqs(order);
    }

    private BaseOrderResponse updateStockAndScore(OrderBean orderBean, List<CreateOrderProductRequest> products, ActivityUpdateStockRequest updateStockRequest,
                                                  List<CreateOrderAccountRequest> accounts, MqMessageRequest mqMessageRequest,String menuType) {
        //TODO 转换获取库存信息,扣减库存
        UpdateStocksRequest updateStocksRequest = orderSdkAdapter.getUpdateProductStock(orderBean, products, StockChangeType.REDUCE,menuType);
        if (updateStocksRequest != null && CollectionUtils.isNotEmpty(updateStocksRequest.getProductStocks())) {
            BaseResponse baseResponse = stockSdkService.reducesStocks(updateStocksRequest, "");
            ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(),
                    "updateStock", JSONObject.toJSONString(updateStocksRequest), JSONObject.toJSONString(baseResponse));
            if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, baseResponse.getCode())) {
                //TODO 失败取消订单
                CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
                        AfterSalesType.SYSTEM_CANCEL, "商品库存不足", "", null);
                orderCancel(cancelOrderRequest);
                return BaseOrderResponse.getErrorBaseOrderResponse(baseResponse.getCode(), "商品库存不足");
            }
        }
        //TODO 扣减活动库存
        ActivityUpdateStockRequest activityUpdateStockRequest = orderSdkAdapter.convert2ActivityUpdateStockRequest(orderBean, updateStockRequest);
        if (activityUpdateStockRequest != null && CollectionUtils.isNotEmpty(activityUpdateStockRequest.getStock())) {
            BaseResponse activityResponse = promotionSdkService.subtractStock(activityUpdateStockRequest, "");
            ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(),
                    "subtractStock", JSONObject.toJSONString(activityUpdateStockRequest), JSONObject.toJSONString(activityResponse));
            if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, activityResponse.getCode())) {
                //TODO 失败取消订单,异步冲正库存
                CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
                        AfterSalesType.SYSTEM_CANCEL, "活动库存不足", "", null);
                orderCancel(cancelOrderRequest);
                //失败异步冲正库存，取消订单
                backOrdersNotifyActivity(orderBean, mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
                return BaseOrderResponse.getErrorBaseOrderResponse(activityResponse.getCode(), "活动库存不足");
            }
        }
        // 扣减积分，扣减失败冲正积分返回错误
        UserScoreRequest userScoreRequest = orderSdkAdapter.convent2UserScoreRequest(orderBean, accounts, true);
        if (userScoreRequest != null) {
            BaseResponse userScoreResponse = memberScoreService.useScore(userScoreRequest, "");
            if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, userScoreResponse.getCode())) {
                //TODO 失败取消订单,异步冲正库存
                CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
                        AfterSalesType.SYSTEM_CANCEL, "积分不足", "", null);
                orderCancel(cancelOrderRequest);
                //失败异步冲正库存，取消订单
                backOrdersNotifyActivity(orderBean, mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
                return BaseOrderResponse.getErrorBaseOrderResponse(userScoreResponse.getCode(), "积分不足");
            }
        }

        // 下单成锁定劵，冻结失败提示下单失败并冲正库存积分等,判断支付渠道，积分和svc卡直接核销，无需锁定10102 = svc卡支付 || 支付金额小于等于0
        if((!StringUtils.isEmpty(orderBean.getPayChannel()) && orderBean.getPayChannel().equalsIgnoreCase("10102")) || orderBean.getAmount() <=0){
            // 核销优惠券，核销失败提示下单失败并冲正库存积分等
            CouponRequest couponVerificationRequest = orderSdkAdapter.convert2CouponVerificationRequest(orderBean, accounts);
            if (couponVerificationRequest!=null){
                // 核销券新增参数：组织机构
                couponVerificationRequest.setChannel_codes(this.getOrgIds(orderBean.getCompanyId(), orderBean.getShopId()));
                BaseResponse<CouponRedeemResponse> couponRedeemResponseBaseResponse = offlineCouponSdkService.couponRedeem(couponVerificationRequest, "");
                if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, couponRedeemResponseBaseResponse.getCode())) {
                    //TODO 失败取消订单,异步冲正库存
                    CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
                            AfterSalesType.SYSTEM_CANCEL, "核销券码失败", "", null);
                    orderCancel(cancelOrderRequest);
                    //失败异步冲正库存，取消订单
                    backOrdersNotifyActivity(orderBean, mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
                    return BaseOrderResponse.getErrorBaseOrderResponse(couponRedeemResponseBaseResponse.getCode(), "核销券码失败");
                }
            }
        }else{
            CouponLockRequest couponLockRequest = orderSdkAdapter.convert2CouponLockRequest(orderBean, accounts);
            if (couponLockRequest != null) {
                BaseResponse<CouponLockResponse> couponLockResponseBaseResponse = offlineCouponSdkService.couponLock(couponLockRequest, "");
                if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, couponLockResponseBaseResponse.getCode())) {
                    CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(), AfterSalesType.SYSTEM_CANCEL, "锁定券码失败", "", null);
                    orderCancel(cancelOrderRequest);
                    //失败异步冲正库存，取消订单
                    backOrdersNotifyActivity(orderBean, mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
                    return BaseOrderResponse.getErrorBaseOrderResponse(couponLockResponseBaseResponse.getCode(), couponLockResponseBaseResponse.getMessage());
                }
            }

        }
        return BaseOrderResponse.getErrorBaseOrderResponse(RESPONSE_SUCCESS_STR, "");
    }

    /**
     * 围餐更新库存和积分 
     */
    private BaseOrderResponse updateWcStockAndScore(OrderBean orderBean, List<CreateOrderProductRequest> products, ActivityUpdateStockRequest updateStockRequest,
                                                  List<CreateOrderAccountRequest> accounts, MqMessageRequest mqMessageRequest,String menuType) {
        //扣减活动库存
        ActivityUpdateStockRequest activityUpdateStockRequest = orderSdkAdapter.convert2ActivityUpdateStockRequest(orderBean, updateStockRequest);
        if (activityUpdateStockRequest != null && CollectionUtils.isNotEmpty(activityUpdateStockRequest.getStock())) {
            BaseResponse activityResponse = promotionSdkService.subtractStock(activityUpdateStockRequest, "");
            ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(),
                    "subtractStock", JSONObject.toJSONString(activityUpdateStockRequest), JSONObject.toJSONString(activityResponse));
            if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, activityResponse.getCode())) {
                //失败异步冲正库存，取消订单
                backOrdersNotifyActivity(orderBean, mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
                return BaseOrderResponse.getErrorBaseOrderResponse(activityResponse.getCode(), "当前活动人数已满");
            }
        }

        // 核销优惠券，核销失败提示下单失败并冲正库存积分等
        CouponRequest couponVerificationRequest = orderSdkAdapter.convert2CouponVerificationRequest(orderBean, accounts);
        if (couponVerificationRequest!=null){
            BaseResponse<CouponRedeemResponse> couponRedeemResponseBaseResponse = offlineCouponSdkService.couponRedeem(couponVerificationRequest, "");
            if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, couponRedeemResponseBaseResponse.getCode())) {
                //失败异步冲正库存，取消订单
                backOrdersNotifyActivity(orderBean, mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
                return BaseOrderResponse.getErrorBaseOrderResponse(couponRedeemResponseBaseResponse.getCode(), "优惠券核销失败，请重试");
            }
        }

        // 扣减积分，扣减失败冲正积分返回错误
        UserScoreRequest userScoreRequest = orderSdkAdapter.convent2UserScoreRequest(orderBean, accounts, true);
        if (userScoreRequest != null) {
            BaseResponse userScoreResponse = memberScoreService.useScore(userScoreRequest, "");
            if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, userScoreResponse.getCode())) {
                //失败异步冲正库存，取消订单
                backOrdersNotifyActivity(orderBean, mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
                return BaseOrderResponse.getErrorBaseOrderResponse(userScoreResponse.getCode(), "积分不足");
            }
        }
        return BaseOrderResponse.getErrorBaseOrderResponse(RESPONSE_SUCCESS_STR, "");
    }


    @Override
    public PayAccessResponse payAccess(ConfirmOrderRequest confirmOrderRequest) {
        PaySuccessReq request = new PaySuccessReq();
        request.setPayRequestNo(confirmOrderRequest.getPayVoucher());
        request.setCompleteOrderCode(confirmOrderRequest.getCompleteOrderCode());
        request.setOrderCode(confirmOrderRequest.getOrderId());
        request.setMealCodeRule(confirmOrderRequest.getMealCodeRule());
        // 引入门店基础服务 查询自动制作完成配置时间，预约单单独超时任务设置
        request.setTimeout(getPaySuccessTimeout(confirmOrderRequest,request));

        if (!org.springframework.util.CollectionUtils.isEmpty(confirmOrderRequest.getOrderSettlements())) {
            List<OrderSettlementCreateReq> orderSettlementCreateReqs = new ArrayList<>();
            int size = confirmOrderRequest.getOrderSettlements().size();
            OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
            for (int i = 0; i < size; i++) {
                ConfirmOrderRequest.OrderSettlement orderSettlement = confirmOrderRequest.getOrderSettlements().get(i);
                orderSettlementCreateReq.setPlatformDiscountAmount(orderSettlement.getPlatformDiscountAmount());
                orderSettlementCreateReq.setShopDiscountAmount(orderSettlement.getShopDiscountAmount());
                orderSettlementCreateReq.setSettlementAmount(orderSettlement.getSettlementAmount());
                orderSettlementCreateReq.setNote(orderSettlement.getNote());
                orderSettlementCreateReq.setSettlementType(this.convertAssortmentSettlementTypeToNewOrderSettlementType(orderSettlement.getSettlementType()));
                orderSettlementCreateReqs.add(orderSettlementCreateReq);
            }
            request.setOrderSettlementDetailList(orderSettlementCreateReqs);
        }
        request.setActualPayAmount(confirmOrderRequest.getActualPayAmount());
//        request.setActualPayAmount(request.getActualPayAmount());
        request.setOperator(confirmOrderRequest.getOperator());
        if (StringUtils.isNotBlank(confirmOrderRequest.getPayChannel())) {
            request.setPayChannel(confirmOrderRequest.getPayChannel());
            request.setPayChannelName(confirmOrderRequest.getPayChannelName());
        }
        QueryOrderByIdResponse orderByIdResponse = new QueryOrderByIdResponse();
        BaseResponse<GetMemberExtendInfoResponse> extendInfo = new BaseResponse();
        try {
            QueryByCodeResponse codeResponse = orderSdkService.getOrderInfo(confirmOrderRequest.getProductOrderCode(), 0, confirmOrderRequest.getTrackingNo());
            orderByIdResponse = orderSdkAdapter.convent2QueryOrderByIdResponse(codeResponse);

            GetMemberExtendInfoRequest extendInfoRequest = new GetMemberExtendInfoRequest();
            extendInfoRequest.setMemberId(orderByIdResponse.getData().getUserId());
            extendInfoRequest.setPartnerId(orderByIdResponse.getData().getCompanyId());
            extendInfo = memberCenterService.getMemberExtendInfo(extendInfoRequest, confirmOrderRequest.getTrackingNo());
            OrderExtInfoDto extInfoDTO = JSONObject.parseObject(orderByIdResponse.getData().getExtInfo(),OrderExtInfoDto.class);
            extInfoDTO.setMemberLevel(extendInfo.getData().getMemberGrade()!=null?extendInfo.getData().getMemberGrade().getRuleName():"");
            extInfoDTO.setPaidMember(CollectionUtils.isNotEmpty(extendInfo.getData().getMemberPaids()));
            extInfoDTO.setPayTransId(confirmOrderRequest.getPayTransId());
            extInfoDTO.setPayDate(confirmOrderRequest.getPayDate());
            extInfoDTO.setEndTransId(confirmOrderRequest.getEndTransId());
            request.setExtInfo(JSON.toJSONString(extInfoDTO));
        }catch (Exception e){
            ErrorLog.printErrorLog("getMemberExtendInfoError",MEMBER_EXTEND_INFO,confirmOrderRequest,e);
        }
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<PaySuccessResp> response = orderSdkService.paySuccess(request, confirmOrderRequest.getTrackingNo());
        //获取会员信息直接返回，非空判断
        if(extendInfo.getData() == null){
            return orderSdkAdapter.convent2PayAccessResponse(response);
        }

        return orderSdkAdapter.convent2PayAccessResponse(response);
    }


    @Override
    public PayAccessResponse payAccessMCCafe(ConfirmOrderRequest confirmOrderRequest) {
        PaySuccessReq request = new PaySuccessReq();
        request.setPayRequestNo(confirmOrderRequest.getPayVoucher());
        request.setCompleteOrderCode(confirmOrderRequest.getCompleteOrderCode());
        request.setOrderCode(confirmOrderRequest.getOrderId());
        // 引入门店基础服务 查询自动制作完成配置时间，预约单单独超时任务设置
        request.setTimeout(getMCCafePaySuccessTimeout(confirmOrderRequest,request));

        if (!org.springframework.util.CollectionUtils.isEmpty(confirmOrderRequest.getOrderSettlements())) {
            List<OrderSettlementCreateReq> orderSettlementCreateReqs = new ArrayList<>();
            int size = confirmOrderRequest.getOrderSettlements().size();
            OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
            for (int i = 0; i < size; i++) {
                ConfirmOrderRequest.OrderSettlement orderSettlement = confirmOrderRequest.getOrderSettlements().get(i);
                orderSettlementCreateReq.setPlatformDiscountAmount(orderSettlement.getPlatformDiscountAmount());
                orderSettlementCreateReq.setShopDiscountAmount(orderSettlement.getShopDiscountAmount());
                orderSettlementCreateReq.setSettlementAmount(orderSettlement.getSettlementAmount());
                orderSettlementCreateReq.setNote(orderSettlement.getNote());
                orderSettlementCreateReq.setSettlementType(this.convertAssortmentSettlementTypeToNewOrderSettlementType(orderSettlement.getSettlementType()));
                orderSettlementCreateReqs.add(orderSettlementCreateReq);
            }
            request.setOrderSettlementDetailList(orderSettlementCreateReqs);
        }
        request.setActualPayAmount(confirmOrderRequest.getActualPayAmount());
//        request.setActualPayAmount(request.getActualPayAmount());
        request.setOperator(confirmOrderRequest.getOperator());
        if (StringUtils.isNotBlank(confirmOrderRequest.getPayChannel())) {
            request.setPayChannel(confirmOrderRequest.getPayChannel());
            request.setPayChannelName(confirmOrderRequest.getPayChannelName());
        }
        QueryOrderByIdResponse orderByIdResponse = new QueryOrderByIdResponse();
        BaseResponse<GetMemberExtendInfoResponse> extendInfo = new BaseResponse();
        try {
            QueryByCodeResponse codeResponse = orderSdkService.getOrderInfo(confirmOrderRequest.getProductOrderCode(), 0, confirmOrderRequest.getTrackingNo());
            orderByIdResponse = orderSdkAdapter.convent2QueryOrderByIdResponse(codeResponse);

            GetMemberExtendInfoRequest extendInfoRequest = new GetMemberExtendInfoRequest();
            extendInfoRequest.setMemberId(orderByIdResponse.getData().getUserId());
            extendInfoRequest.setPartnerId(orderByIdResponse.getData().getCompanyId());
            extendInfo = memberCenterService.getMemberExtendInfo(extendInfoRequest, confirmOrderRequest.getTrackingNo());
            OrderExtInfoDto extInfoDTO = JSONObject.parseObject(orderByIdResponse.getData().getExtInfo(),OrderExtInfoDto.class);
            extInfoDTO.setMemberLevel(extendInfo.getData().getMemberGrade()!=null?extendInfo.getData().getMemberGrade().getRuleName():"");
            extInfoDTO.setPaidMember(CollectionUtils.isNotEmpty(extendInfo.getData().getMemberPaids()));
            extInfoDTO.setPayTransId(confirmOrderRequest.getPayTransId());
            extInfoDTO.setPayDate(confirmOrderRequest.getPayDate());
            extInfoDTO.setEndTransId(confirmOrderRequest.getEndTransId());
            request.setExtInfo(JSON.toJSONString(extInfoDTO));
        }catch (Exception e){
            ErrorLog.printErrorLog("getMemberExtendInfoError",MEMBER_EXTEND_INFO,confirmOrderRequest,e);
        }
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<PaySuccessResp> response = orderSdkService.paySuccessMCCafe(request, confirmOrderRequest.getTrackingNo());
        //获取会员信息直接返回，非空判断
        if(extendInfo.getData() == null){
            return orderSdkAdapter.convent2PayAccessResponse(response);
        }
        CalculationDiscountRequest discountRequest=activitySdkAdapter.convert2CalculationDiscountRequestDto(orderByIdResponse.getData(),extendInfo.getData());
        BaseResponse<CalculationDiscountResponseDTO> baseResponse=promotionSdkService.calculationDiscount(discountRequest,confirmOrderRequest.getTrackingNo());
        List<Integer> activityTypes=baseResponse.getData().getDiscounts().stream().map(DiscountDTO::getType).collect(Collectors.toList());
        if(activityTypes.contains(221)){
            DiscountDTO discountDTO=baseResponse.getData().getDiscounts().stream().filter(d -> 221==d.getType()).findFirst().get();
            SendPointRequest pointRequest=memberSdkAdapter.convert2SendPointRequest(confirmOrderRequest,orderByIdResponse.getData(),discountDTO);
            if (pointRequest.getSendPoint() != 0) {
                memberPropertyService.sendMemberPoint(pointRequest,confirmOrderRequest.getTrackingNo());
            }
        }

        return orderSdkAdapter.convent2PayAccessResponse(response);
    }

    private Integer convertAssortmentSettlementTypeToNewOrderSettlementType(OldOrderAccountType settlementType) {
        if (settlementType == OldOrderAccountType.WEIXIN) {
            return OrderSettlementType.WEIXIN.getIndex();
        }
        return -1;
    }

    @Override
    public QueryOrderByIdResponse queryOrderById(BaseQueryOrderRequest request) {
        QueryByCodeResponse orderInfo = orderSdkService.getOrderInfo(request.getOrderClient(), request.getOrderId(),
                request.getThirdOrderCode(), request.getWithOperationHistory(), request.getTrackingNo());
        QueryOrderByIdResponse response = new QueryOrderByIdResponse();
        if (orderInfo == null || orderInfo.getResult() == null) {
            return response;
        }
        response.setErrcode(Integer.parseInt(orderInfo.getCode()));
        response.setErrmsg(orderInfo.getMessage());
        if (orderInfo.getResult().getOrderCode() == null || "".equals(orderInfo.getResult().getOrderCode())) {
            return response;
        }
        QueryOrderByIdResponse orderByIdResponse = orderSdkAdapter.convent2QueryOrderByIdResponse(orderInfo);
        return orderByIdResponse;
    }

    @Override
    public QueryOrdersResponse queryOrders(QueryOrdersRequest queryOrdersRequest) {
        OrderUserConditionsReq request = orderSdkAdapter.convent2QueryOrdersRequest(queryOrdersRequest);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<QueryOrderForUserResp> userorderResponse = orderSdkService.queryOrderForUser(request, queryOrdersRequest.getTrackingNo());
        return orderSdkAdapter.convent2QueryOrdersResponse(userorderResponse);
    }

    @Override
    public QueryOrderByIdResponse queryMCCafeOrderById(BaseQueryOrderRequest request) {
        QueryByCodeResponse orderInfo = orderSdkService.getOrderInfo(request.getOrderClient(), request.getOrderId(),
                request.getThirdOrderCode(), request.getWithOperationHistory(), request.getTrackingNo());
        QueryOrderByIdResponse response = new QueryOrderByIdResponse();
        if (orderInfo == null || orderInfo.getResult() == null) {
            return response;
        }
        response.setErrcode(Integer.parseInt(orderInfo.getCode()));
        response.setErrmsg(orderInfo.getMessage());
        if (orderInfo.getResult().getOrderCode() == null || "".equals(orderInfo.getResult().getOrderCode())) {
            return response;
        }
        QueryOrderByIdResponse orderByIdResponse = orderSdkAdapter.convent2QueryOrderByIdResponse(orderInfo);
        return orderByIdResponse;
    }

    @Override
    public QueryOrdersResponse queryMCCafeOrders(QueryOrdersRequest queryOrdersRequest) {
        OrderUserConditionsReq request = orderSdkAdapter.convent2QueryOrdersRequest(queryOrdersRequest);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<QueryOrderForUserResp> userorderResponse = orderSdkService.queryOrderForUser(request, queryOrdersRequest.getTrackingNo());
        return orderSdkAdapter.convent2QueryOrdersResponse(userorderResponse);
    }

    @Override
    public BaseOrderResponse deleteOrder(DeleteOrderRequest deleteOrderRequest) {
        OrderDeleteReq request = new OrderDeleteReq();
        request.setOrderCode(deleteOrderRequest.getOrderId());
        request.setOperator(deleteOrderRequest.getOperator());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.deleteOrder(request, deleteOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse orderRefund(OrderRefundRequest orderRefundRequest) {
        CreateAfterSalesOrder request = new CreateAfterSalesOrder();
        request.setPartnerId(orderRefundRequest.getPartnerId());
        if(null != orderRefundRequest.getOrderClient()) {
            request.setOrderClient(orderRefundRequest.getOrderClient());
        } else {
            request.setOrderClient(OrderClientType.SAAS.getIndex());
        }
        if(orderRefundRequest.getActualAmount() != null)
        request.setActualAmount(orderRefundRequest.getActualAmount());
        //申请金额，单位分，如果是全部退款，并且传递null,则自动填入 订单用户需支付金额
        request.setReqAmount(orderRefundRequest.getReqAmount());
        //是否有退货货物
        request.setHasCargo(false);
        //传入的售后单类型为：2：售中用户取消 8：售后申请
        if(null != orderRefundRequest.getAfterSalesType()) {
            request.setAfterSalesType(orderRefundRequest.getAfterSalesType().getIndex());
        } else if (OldOrderStatus.COMPLETE.getCode().equals(orderRefundRequest.getOrderStatus())) {
            request.setAfterSalesType(AfterSalesType.USER_SALE_RETURN.getIndex());
        } else {
            request.setAfterSalesType(AfterSalesType.USER_CANCEL.getIndex());
        }
        request.setOrderCode(orderRefundRequest.getOrderId());
        request.setReqRemark(orderRefundRequest.getRemark());
        request.setAfterSalesReason(orderRefundRequest.getReason());
        request.setOperator(orderRefundRequest.getOperator());
        if(null != orderRefundRequest.getCreateEvent()) {
            request.setCreateEvent(orderRefundRequest.getCreateEvent());
        }
        // 查询门店服务配置，退单模式为2为自动退款，判断自动退款时间,设置为0则不传入timeout,
        StoreResponse.Configuration configuration = getStoreAutoConfiguration(orderRefundRequest.getPartnerId(), orderRefundRequest.getStoreId(), orderRefundRequest.getTrackingNo());
        if (configuration != null && ObjectUtils.equals("2", configuration.getAutoChargebackOrderType())
                && !ObjectUtils.equals("0", configuration.getAutoChargebackOrderTime())) {
            request.setTimeOut(AutoOrderConfigTime.getTime(configuration.getAutoChargebackOrderTime()));
        }
        OrderTaskReq orderTask = setAfterSalesOrderTimeOutTask(configuration);
        request.setOrderTask(orderTask);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.createAfterSalesOrder(request, orderRefundRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    /**
     * 设置申请退款时间
     * 如果时间的类型是2表示采用原来的48小时逻辑
     * 如果时间的类型是1表示在指定的时间之后进行退款
     * 为了防止同一时刻的退款量太大，需要将退款的订单分散到指定的时间后半小时内
     */
    private OrderTaskReq setAfterSalesOrderTimeOutTask(StoreResponse.Configuration configuration) {

        if(configuration != null && (configuration.getTimeTypeOfRefund() != null && 2 == configuration.getTimeTypeOfRefund().intValue()) || configuration.getTimeTypeOfRefund() == null){// 48小时之后
            OrderTaskReq orderTask = new OrderTaskReq();
            orderTask.setTaskType(4);
            orderTask.setTimeout(1);
            //1000*60*60*24*2 毫秒（48小时）
            long timeout = 172800000;
            long timeMillis = System.currentTimeMillis();
            Date processingDate = new Date(timeMillis + timeout - 60000);
            Date taskTime = new Date(timeMillis + timeout);
            orderTask.setTaskTime(DateUtil.convert2String(taskTime, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
            //处理时间，当前时间加48小时减1分钟
            orderTask.setProcessingTime(DateUtil.convert2String(processingDate, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));

            return orderTask;
        }else if(configuration != null && configuration.getTimeTypeOfRefund() != null && 1 == configuration.getTimeTypeOfRefund().intValue()){// 指定时间
            OrderTaskReq orderTask = new OrderTaskReq();
            orderTask.setTaskType(4);
            orderTask.setTimeout(1);
            // 获取门店配置的当天指定的退款时间
            String timeOfRefund = configuration.getTimeOfRefund();
            // 获取半小时的随机数
            Random r = new Random();
            int minute = r.ints(1,31).findFirst().getAsInt() * 60000;
            String today = DateUtil.getCurrentDate(DateUtil.FORMAT_YMD);
            Date configTime = DateUtil.convert2Date(today+" "+timeOfRefund, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
            Date processingDate = new Date(configTime.getTime() + minute);
            String processingStr = DateUtil.convert2String(processingDate, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
            orderTask.setTaskTime(processingStr);
            orderTask.setProcessingTime(processingStr);

            return orderTask;
        }
        return null;
    }

    /**
     * 获取门店自动配置信息
     *
     * @param partnerId
     * @param storeCode
     * @param trackingNo
     * @return
     */
    private StoreResponse.Configuration getStoreAutoConfiguration(String partnerId, String storeCode, String trackingNo) {
        if (StringUtils.isEmpty(storeCode)) {
            return null;
        }
        StoreInfoRequest storeInfoRequest = new StoreInfoRequest();
        storeInfoRequest.setPartnerId(partnerId);
        storeInfoRequest.setStoreCode(storeCode);
        StoreResponse storeResponse = storeCenterService.getStoreInfo(storeInfoRequest, trackingNo);
        if (storeResponse == null || storeResponse.getBizVO() == null || storeResponse.getBizVO().getStoreConfig() == null) {
            return null;
        }

        return storeResponse.getBizVO().getStoreConfig();
    }

    /**
     * 获取支付成功 超时取消订单或者超时接单时间
     * @param confirmOrderRequest
     * @return
     */
    private Integer getPaySuccessTimeout(ConfirmOrderRequest confirmOrderRequest,PaySuccessReq request){
        Integer timeout = 0;
        StoreInfoRequest storeInfoRequest = new StoreInfoRequest();
        storeInfoRequest.setPartnerId(confirmOrderRequest.getPartnerId());
        storeInfoRequest.setStoreCode(confirmOrderRequest.getStoreId());
        StoreResponse storeResponse = storeCenterService.getStoreInfo(storeInfoRequest, confirmOrderRequest.getTrackingNo());
        if (storeResponse != null && storeResponse.getBizVO() != null ) {
            StoreResponse.Configuration configuration = storeResponse.getBizVO().getStoreConfig();
            //配置为空超时取消订单
            if (configuration == null || org.apache.commons.lang.StringUtils.isBlank(configuration.getOverTimeCloseOrder())){
                timeout = 30;
            }
            //超时关单开启
            if(configuration != null  && ObjectUtils.equals("1", configuration.getOverTimeCloseOrder())
                    && StringUtils.isNotBlank(configuration.getOverTimeCloseOrderTime())){
                timeout =  Integer.parseInt(configuration.getOverTimeCloseOrderTime());
            }
            //isAutoTakeOrder = 3为服务端超时接单
            if("3".equals(storeResponse.getBizVO().getIsAutoTakeOrder())){
                //外卖订单
                if(confirmOrderRequest.getOrderType() == OldOrderType.TAKE_OUT.getCode()){
                    timeout = PaySuccessTimeoutEnum.getMin(configuration.getTakeOutAutomaticOrderTime());
                }else {
                    timeout = PaySuccessTimeoutEnum.getMin(configuration.getPickUpAutomaticOrderTime());
                }
            }
        }
        return timeout;
    }

    /**
     * 获取麦咖啡支付成功 超时取消订单或者超时接单时间
     * @param confirmOrderRequest
     * @return
     */
    private Integer getMCCafePaySuccessTimeout(ConfirmOrderRequest confirmOrderRequest,PaySuccessReq request){
        Integer timeout = 0;
        StoreInfoRequest storeInfoRequest = new StoreInfoRequest();
        storeInfoRequest.setPartnerId(confirmOrderRequest.getPartnerId());
        storeInfoRequest.setStoreCode(confirmOrderRequest.getStoreId());
        StoreResponse storeResponse = storeCenterService.getStoreInfo(storeInfoRequest, confirmOrderRequest.getTrackingNo());
        if (storeResponse != null && storeResponse.getBizVO() != null ) {
            StoreResponse.Configuration configuration = storeResponse.getBizVO().getStoreConfig();
            //配置为空超时取消订单
            if (configuration == null || org.apache.commons.lang.StringUtils.isBlank(configuration.getOverTimeCloseOrder())){
                timeout = 30;
            }
            //超时关单开启
            if(configuration != null  && ObjectUtils.equals("1", configuration.getOverTimeCloseOrder())
                    && StringUtils.isNotBlank(configuration.getOverTimeCloseOrderTime())){
                timeout =  Integer.parseInt(configuration.getOverTimeCloseOrderTime());
            }
        }
        return timeout;
    }



    @Override
    public BaseOrderResponse orderEdit(OrderEditRequest orderEdit) {
        UpdateOrderReq request = new UpdateOrderReq();
        request.setOrderCode(orderEdit.getOrderId());
        request.setExtInfo(orderEdit.getExtInfo());
        request.setOrderClient(OrderClientType.SAAS.getIndex());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.editOrder(request, orderEdit.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse orderCancel(CancelOrderRequest cancelOrderRequest) {
        OrderCancelReq request = new OrderCancelReq();
        //商户号必传
        request.setPartnerId(cancelOrderRequest.getPartnerId());
        request.setOrderCode(cancelOrderRequest.getOrderId());
        request.setReqRemark(cancelOrderRequest.getReqRemark());
        //售后单类型 1:其他取消 2:用户取消 3:商户取消 4:未支付超时关单 5:商户接单超时取消 6:商家拒单
        // 7:配送用户拒收 8:用户售后退货/售后退款 9:系统取消 10:客服取消 11:用户统一取消，
        request.setAfterSalesType(cancelOrderRequest.getAfterSalesType().getIndex() == null ? 1 : cancelOrderRequest.getAfterSalesType().getIndex());
        request.setOrderClient(cancelOrderRequest.getOrderClient());
        request.setCancelReason(cancelOrderRequest.getReason());
        //若为4，默认做【创建】+【同意并退款完成】，售后单状态为【完成】
        request.setCreateEvent(cancelOrderRequest.getCreateEvent());
        request.setAfterSerialNo(cancelOrderRequest.getRefundSerialNo());
        request.setOperator(cancelOrderRequest.getOperator());
        //为空发起售后单
        if(cancelOrderRequest.getCreateEvent() == null){
            // 查询门店服务配置，退单模式为2为自动退款，判断自动退款时间,设置为0则不传入timeout,
            StoreResponse.Configuration configuration = getStoreAutoConfiguration(cancelOrderRequest.getPartnerId(), cancelOrderRequest.getStoreId(), cancelOrderRequest.getTrackingNo());
            if (configuration != null && ObjectUtils.equals("2", configuration.getAutoChargebackOrderType())
                    && !ObjectUtils.equals("0", configuration.getAutoChargebackOrderTime())) {
                request.setTimeOut(AutoOrderConfigTime.getTime(configuration.getAutoChargebackOrderTime()));
            }
            OrderTaskReq orderTask = setAfterSalesOrderTimeOutTask(configuration);
            request.setOrderTask(orderTask);
        }
        request.setRefundDeliveryAmount(cancelOrderRequest.isRefundDeliveryAmount());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.cancelOrder(request, cancelOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse queryOrderQueueIndex(BaseQueryOrderRequest baseQueryOrderRequest) {
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<Integer> response = orderSdkService.queryQueueIndex(baseQueryOrderRequest.getOrderId(), baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse queryStoreOrderQuantity(BaseQueryOrderRequest baseQueryOrderRequest) {
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<Integer> response = orderSdkService.queryQueueSize(baseQueryOrderRequest.getPartnerId(), baseQueryOrderRequest.getShopId(),
                baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public OrderStatusTrackingInfoResponse getOrderStatusTrackingInfoByOid(BaseQueryOrderRequest baseQueryOrderRequest) {
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<List<OrderTraceInfoResp>> response = orderSdkService.queryTrackInfo(baseQueryOrderRequest.getOrderId(), baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2OrderStatusTrackingInfoResponse(response);
    }

    @Override
    public QueryOrdersResponse repeatGetOrders(RepeatQueryOrdersRequest repeatQueryOrdersRequest) {
        PullOrdersReq pullOrdersReq = new PullOrdersReq();
        pullOrdersReq.setPartnerId(repeatQueryOrdersRequest.getCompanyId());
        pullOrdersReq.setStoreId(repeatQueryOrdersRequest.getShopId());
        pullOrdersReq.setOrderClient(repeatQueryOrdersRequest.getOrderClient());
        pullOrdersReq.setUpdateTimestamp(repeatQueryOrdersRequest.getTimestamp());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.pullOrders(pullOrdersReq, repeatQueryOrdersRequest.getTrackingNo());
        return orderSdkAdapter.convent2PullOrderResponse(response);
    }

    @Override
    public BaseOrderResponse orderConfirmTake(BaseQueryOrderRequest baseQueryOrderRequest) {
        POSOrderOperationBaseReq request = new POSOrderOperationBaseReq();
        request.setOrderCode(baseQueryOrderRequest.getOrderId());
        request.setOperator(baseQueryOrderRequest.getOperator());
        // 引入门店基础服务 查询自动制作完成配置时间
        setTimeout(baseQueryOrderRequest,request);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.acceptOrder(request, baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse orderConfirmTakeMCCafe(BaseQueryOrderRequest baseQueryOrderRequest) {
        POSOrderOperationBaseReq request = new POSOrderOperationBaseReq();
        request.setOrderCode(baseQueryOrderRequest.getOrderId());
        request.setOperator(baseQueryOrderRequest.getOperator());
        // 引入门店基础服务 查询自动制作完成配置时间
        setTimeout(baseQueryOrderRequest,request);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.acceptOrderMCCafe(request, baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse orderReject(CancelOrderRequest cancelOrderRequest) {
        OrderCancelReq request = new OrderCancelReq();
        //商户号必传
        request.setPartnerId(cancelOrderRequest.getPartnerId());
        request.setOrderCode(cancelOrderRequest.getOrderId());
        //售后单类型 1:其他取消 2:用户取消 3:商户取消 4:未支付超时关单 5:商户接单超时取消 6:商家拒单
        // 7:配送用户拒收 8:用户售后退货/售后退款 9:系统取消 10:客服取消 11:用户统一取消，
        request.setAfterSalesType(cancelOrderRequest.getAfterSalesType().getIndex() == null ? 1 : cancelOrderRequest.getAfterSalesType().getIndex());
        request.setOrderClient(OrderClientType.SAAS.getIndex());
        request.setCancelReason(cancelOrderRequest.getReason());
        //若为4，默认做【创建】+【同意并退款完成】，售后单状态为【完成】
        request.setCreateEvent(4);
        request.setOperator(cancelOrderRequest.getOperator());
        request.setAfterSerialNo(cancelOrderRequest.getRefundSerialNo());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.cancelOrder(request, cancelOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse mcCafeOrderReject(CancelOrderRequest cancelOrderRequest, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        if(CollectionUtils.isEmpty(orderBean.getRefundList())) {
            OrderCancelReq request = new OrderCancelReq();
            //商户号必传
            request.setPartnerId(cancelOrderRequest.getPartnerId());
            request.setOrderCode(cancelOrderRequest.getOrderId());
            //售后单类型 1:其他取消 2:用户取消 3:商户取消 4:未支付超时关单 5:商户接单超时取消 6:商家拒单
            // 7:配送用户拒收 8:用户售后退货/售后退款 9:系统取消 10:客服取消 11:用户统一取消，
            request.setAfterSalesType(cancelOrderRequest.getAfterSalesType().getIndex() == null ? 1 : cancelOrderRequest.getAfterSalesType().getIndex());
            request.setOrderClient(OrderClientType.SAAS.getIndex());
            request.setCancelReason(cancelOrderRequest.getReason());
            //若为4，默认做【创建】+【同意并退款完成】，售后单状态为【完成】
            request.setCreateEvent(4);
            request.setOperator(cancelOrderRequest.getOperator());
            request.setAfterSerialNo(cancelOrderRequest.getRefundSerialNo());
            com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.cancelOrder(request, cancelOrderRequest.getTrackingNo());
            return orderSdkAdapter.convent2BaseOrderResponse(response);
        } else {
            for(int i=0;i<orderBean.getRefundList().size();i++) {
                if (RefundStatus.APPLY_REFUND.getCode().equals(orderBean.getRefundList().get(i).getStatus())) {
                    AfterSalesOperateReq request = new AfterSalesOperateReq();
                    request.setOrderCode(cancelOrderRequest.getOrderId());
                    request.setPartnerId(cancelOrderRequest.getPartnerId());
                    request.setOrderClient(OrderClientType.SAAS.getIndex());
                    request.setAfterSalesCode(orderBean.getRefundList().get(i).getRid());
                    request.setAfterSerialNo(cancelOrderRequest.getRefundSerialNo());
                    request.setAdultRemark(cancelOrderRequest.getReason());
                    request.setOperator(cancelOrderRequest.getOperator());
                    com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.adultApproveWithRefundComplete(request, cancelOrderRequest.getTrackingNo());
                    return orderSdkAdapter.convent2BaseOrderResponse(response);
                }
                if (RefundStatus.COMPLETE_REFUND.getCode().equals(orderBean.getRefundList().get(i).getStatus())) {
                    BaseOrderResponse response = new BaseOrderResponse();
                    response.setErrcode(100);
                    response.setErrmsg("success");
                    return response;
                }
            }
            OrderRefundRequest orderRefundRequest = new OrderRefundRequest();
            orderRefundRequest.setPartnerId(cancelOrderRequest.getPartnerId());
            orderRefundRequest.setStoreId(cancelOrderRequest.getStoreId());
            orderRefundRequest.setOrderId(cancelOrderRequest.getOrderId());
            orderRefundRequest.setOrderClient(OrderClientType.SAAS.getIndex());

            orderRefundRequest.setAfterSalesType(cancelOrderRequest.getAfterSalesType().getIndex() == null ? AfterSalesType.PARTNER_REJECT
                    : cancelOrderRequest.getAfterSalesType());
            orderRefundRequest.setReason(cancelOrderRequest.getReason());
            orderRefundRequest.setRemark(cancelOrderRequest.getReqRemark());
            orderRefundRequest.setOperator(cancelOrderRequest.getOperator());
            orderRefundRequest.setOrderStatus(orderBean.getStatus());
            orderRefundRequest.setCreateEvent(4);

            BaseOrderResponse baseOrderResponse = orderRefund(orderRefundRequest);
            return baseOrderResponse;
        }
    }

    @Override
    public BaseOrderResponse orderSend(BaseQueryOrderRequest baseQueryOrderRequest) {
        POSOrderOperationBaseReq request = new POSOrderOperationBaseReq();
        request.setOrderCode(baseQueryOrderRequest.getOrderId());
        request.setOperator(baseQueryOrderRequest.getOperator());
        // 调用门店服务查询外卖单自动完成时间
        StoreResponse.Configuration configuration = getStoreAutoConfiguration(baseQueryOrderRequest.getPartnerId(), baseQueryOrderRequest.getShopId(), baseQueryOrderRequest.getTrackingNo());
        if (configuration != null ) {
            if(StringUtils.isNotEmpty(configuration.getAutoDeliveryTakeOrderWorkflowFinishTime())){
                request.setTimeout(AutoOrderConfigTime.getTime(configuration.getAutoDeliveryTakeOrderWorkflowFinishTime()));
            }
            if(StringUtils.isNotEmpty(baseQueryOrderRequest.getExpectTime()) && StringUtils.isNotEmpty(configuration.getAppointAutoDeliveryTakeOrderWorkflowFinishTime())){
                request.setTimeout(AutoOrderConfigTime.getTime(configuration.getAppointAutoDeliveryTakeOrderWorkflowFinishTime()));
            }

        } else {
            request.setTimeout(120);
        }
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.directDelivery(request, baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse orderAffirm(BaseQueryOrderRequest baseQueryOrderRequest) {
        OrderChangeStateReq request = new OrderChangeStateReq();
        request.setOrderCode(baseQueryOrderRequest.getOrderId());
        request.setOrderState(NewOrderStatus.COMPLETE.getIndex());
        request.setOperator(baseQueryOrderRequest.getOperator());
        request.setRemark("已完成");
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.updateOrderState(request, baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse refundComplete(BaseQueryOrderRequest baseQueryOrderRequest) {
        AfterSalesOperateReq request = new AfterSalesOperateReq();
        request.setOrderCode(baseQueryOrderRequest.getOrderId());
        request.setPartnerId(baseQueryOrderRequest.getPartnerId());
        request.setOrderClient(OrderClientType.SAAS.getIndex());
        request.setAfterSalesCode(baseQueryOrderRequest.getAfterSalesCode());
        request.setAfterSerialNo(baseQueryOrderRequest.getRefundSerialNo());
        request.setAdultRemark(baseQueryOrderRequest.getReason());
        request.setOperator(baseQueryOrderRequest.getOperator());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.adultApproveWithRefundComplete(request, baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse orderRefundComplete(BaseQueryOrderRequest baseQueryOrderRequest) {
        AfterSalesOperateReq request = new AfterSalesOperateReq();
        request.setOrderCode(baseQueryOrderRequest.getOrderId());
        request.setPartnerId(baseQueryOrderRequest.getPartnerId());
        request.setOrderClient(OrderClientType.SAAS.getIndex());
        request.setAfterSalesCode(baseQueryOrderRequest.getAfterSalesCode());
        request.setOperator(baseQueryOrderRequest.getOperator());
        request.setAfterSerialNo(baseQueryOrderRequest.getRefundSerialNo());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.adultWithRefundComplete(request, baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse refundReturn(BaseQueryOrderRequest baseQueryOrderRequest) {
        AfterSalesOperateReq request = new AfterSalesOperateReq();
        request.setOrderCode(baseQueryOrderRequest.getOrderId());
        request.setPartnerId(baseQueryOrderRequest.getPartnerId());
        request.setOrderClient(OrderClientType.SAAS.getIndex());
        request.setAfterSalesCode(baseQueryOrderRequest.getAfterSalesCode());
        request.setAfterSerialNo(baseQueryOrderRequest.getRefundSerialNo());
        request.setAdultRemark(baseQueryOrderRequest.getReason());
        request.setOperator(baseQueryOrderRequest.getOperator());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.adultApproveWithGoodsReturned(request, baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse orderRefundReject(CancelOrderRequest cancelOrderRequest) {
        AfterSalesOperateReq request = new AfterSalesOperateReq();
        request.setOrderClient(OrderClientType.SAAS.getIndex());
        request.setPartnerId(cancelOrderRequest.getPartnerId());
        request.setOrderCode(cancelOrderRequest.getOrderId());
        request.setAfterSalesCode(cancelOrderRequest.getAfterSalesCode());
        request.setAdultRemark(cancelOrderRequest.getReason());
        request.setOperator(cancelOrderRequest.getOperator());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.adultReject(request, cancelOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse orderDone(BaseQueryOrderRequest baseQueryOrderRequest) {
        POSOrderOperationBaseReq request = new POSOrderOperationBaseReq();
        request.setOrderCode(baseQueryOrderRequest.getOrderId());
        request.setOperator(baseQueryOrderRequest.getOperator());
        // 调用门店服务查询自动完成配置信息
        StoreResponse.Configuration configuration = getStoreAutoConfiguration(baseQueryOrderRequest.getPartnerId(), baseQueryOrderRequest.getShopId(), baseQueryOrderRequest.getTrackingNo());
        if (configuration != null) {
            if(StringUtils.isNotEmpty(configuration.getAutoSelfmentionMakerWorkflowFinishTime())){
                request.setTimeout(AutoOrderConfigTime.getTime(configuration.getAutoSelfmentionMakerWorkflowFinishTime()));
            }
            if(StringUtils.isNotEmpty(baseQueryOrderRequest.getExpectTime()) && StringUtils.isNotEmpty(configuration.getAppointAutoSelfmentionMakerWorkflowFinishTime())){
                request.setTimeout(AutoOrderConfigTime.getTime(configuration.getAppointAutoSelfmentionMakerWorkflowFinishTime()));
            }
        } else {
            request.setTimeout(120);
        }
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.prepareComplete(request, baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public QueryOrdersResponse getOrderListByConditions(QueryOrdersByConditionsRequest queryOrdersByConditionsRequest) {
        OrderConditionsReq request = orderSdkAdapter.convent2QueryOrdersByConditionsRequest(queryOrdersByConditionsRequest);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.queryOrderByConditions(request, queryOrdersByConditionsRequest.getTrackingNo());
        //活动号查询订单
        if (queryOrdersByConditionsRequest.getDiscountId() != null && !"".equals(queryOrdersByConditionsRequest.getDiscountId())) {
            OrderDiscountReq orderDiscountReq = orderSdkAdapter.convent2OrderDiscountReq(queryOrdersByConditionsRequest);
            response = orderSdkService.queryOrderByDiscount(orderDiscountReq, queryOrdersByConditionsRequest.getTrackingNo());
        }
        return orderSdkAdapter.convent2QueryOrdersResponse(response);
    }

    /**
     * 通过es综合查询订单
     *
     * @param queryOrdersByConditionsRequest
     * @return
     */
    @Override
    public QueryOrdersResponse getOrderListByES(QueryOrdersByConditionsRequest queryOrdersByConditionsRequest) {
        OrderConditionsReq request = orderSdkAdapter.convent2QueryOrdersByConditionsRequest(queryOrdersByConditionsRequest);
        BaseDownLoadResponse<List<OrderInfoReqs>> baseDownLoadResponse = orderDownLoadSdkService.queryOrderByConditions(request, "");

        if (ObjectUtils.notEqual("100", baseDownLoadResponse.getCode()) || CollectionUtils.isEmpty(baseDownLoadResponse.getResult())) {
            QueryOrdersResponse queryOrdersResponse = new QueryOrdersResponse();
            queryOrdersResponse.setErrcode(Integer.parseInt(baseDownLoadResponse.getCode()));
            QueryOrdersResponse.DataBean dataBean = new QueryOrdersResponse.DataBean();
            dataBean.setOrders(new ArrayList<>());
            dataBean.setUpdateTimestamp(0L);
            dataBean.setCount(0);
            queryOrdersResponse.setData(dataBean);
            return queryOrdersResponse;
        }

        if(request.getPageNum()>0){
            return orderSdkAdapter.convent2OrdersResponseByES(baseDownLoadResponse);
        }

        List<OrderInfoReqs> list = new ArrayList<>();
        list.addAll(baseDownLoadResponse.getResult());
        if (baseDownLoadResponse.getTotalNum() > queryOrdersByConditionsRequest.getPageSize()) {
            QueryOrderByScrollRequest queryOrderByScrollRequest = new QueryOrderByScrollRequest();
            queryOrderByScrollRequest.setVer(1);
            queryOrderByScrollRequest.setScrollId(baseDownLoadResponse.getScrollId());
            while (true) {
                BaseDownLoadResponse<List<OrderInfoReqs>> listBaseDownLoadResponse = orderDownLoadSdkService.queryOrderByScroll(queryOrderByScrollRequest, "");
                if (ObjectUtils.equals("100", listBaseDownLoadResponse.getCode()) && CollectionUtils.isNotEmpty(listBaseDownLoadResponse.getResult())) {
                    list.addAll(listBaseDownLoadResponse.getResult());
                    queryOrderByScrollRequest.setScrollId(listBaseDownLoadResponse.getScrollId());
                } else {
                    break;
                }
            }
        }
        baseDownLoadResponse.setResult(list);
        return orderSdkAdapter.convent2OrdersResponseByES(baseDownLoadResponse);
    }


    @Override
    public BatchQueryResponse batchQuery(BatchQueryRequest batchQueryRequest) {
        BatchQueryReq request = orderSdkAdapter.convent2BatchQueryReq(batchQueryRequest);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<BatchQueryResp> response = orderSdkService.batchQuery(request, batchQueryRequest.getTrackingNo());
        return orderSdkAdapter.convent2BatchQueryResponse(response);
    }

    @Override
    public GetStatisticStoreOrderReportResponse getStatisticStoreOrderReport(GetStatisticStoreOrderReportRequest request) {
        StoreOrderStatisticReq storeOrderStatisticReq = orderSdkAdapter.convent2GetStatisticStoreOrderReportRequest(request);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<StoreOrderStatisticResp> response = orderSdkService.queryStatisticStoreOrder(storeOrderStatisticReq, request.getTrackingNo());
        return orderSdkAdapter.convent2GetStatisticStoreOrderReportResponse(response);
    }

    @Override
    public OrderBaseResponse updateDeliveryInfoById(UpdateDeliveryInfoByIdRequest request) {
        OrderExpressReq expressReq = new OrderExpressReq();
        expressReq.setExpressChannelCode(request.getExpressChannelCode());
        expressReq.setExpressChannelName(request.getExpressChannelName());
        expressReq.setOperator(request.getOperator());
        expressReq.setOrderClient(request.getOrderClient() != null ? request.getOrderClient().byteValue() : null);
        expressReq.setThirdOrderCode(request.getThirdOrderCode());
        expressReq.setOrderCode(request.getOrderId());
        expressReq.setThirdDeliveryId(request.getDeliveryId());
        expressReq.setExpressNo(request.getExpressNo());
        expressReq.setExpressChannelName(request.getExpressChannelName());
        expressReq.setExpressChannelCode(request.getExpress());
        expressReq.setContactsName(request.getCourierName());
        expressReq.setMobile(request.getCourierPhone());
        expressReq.setRemark(request.getDeliveryId());
        expressReq.setOrderSubState(request.getOrderSubState());
        expressReq.setRemark(request.getRemark());
        expressReq.setOrderSubState(request.getOrderSubState());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response = orderSdkService.updateDeliveryInfo(expressReq, request.getTrackingNo());
        OrderBaseResponse baseResponse = new OrderBaseResponse();
        baseResponse.setErrcode(response.getCode() != null ? Integer.parseInt(response.getCode()) : null);
        baseResponse.setErrmsg(response.getMessage());
        return baseResponse;
    }

    @Override
    public OrderDownloadResponse orderDownload(OrderDownloadRequest request) {
        OrderConditionsReq orderConditionsReq = orderSdkAdapter.convent2OrderConditionsReq(request);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<QueryOrderForUserResp> response = orderSdkService.queryOrderByConditions(orderConditionsReq, request.getTrackingNo());
        return orderSdkAdapter.convent2OrderDownloadResponse(response);
    }

    @Override
    public OrderDetailResponse getByIdForParentProduct(BaseQueryOrderRequest request) {
        QueryByCodeResponse orderInfo = orderSdkService.getOrderInfo(request.getOrderClient(), request.getOrderId(), request.getThirdOrderCode(), 0, request.getTrackingNo());
        OrderDetailResponse response = orderSdkAdapter.convent2OrderDetailResponse(orderInfo);
        return response;
    }

    @Override
    public QueryRefundOrderResponse queryAfterSalesList(QueryRefundOrdersRequest request) {
        OrderRefundQueryReq orderRefundQueryReq = orderSdkAdapter.convent2OrderRefundReq(request);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<AfterSalesPageResp> baseResponse = orderSdkService.queryAfterSalesList(orderRefundQueryReq, request.getTrackingNo());
        QueryRefundOrderResponse queryRefundOrderResponse = new QueryRefundOrderResponse();
        if (baseResponse != null && baseResponse.getResult() != null) {
            queryRefundOrderResponse.setItemList(baseResponse.getResult().getItemList());
            queryRefundOrderResponse.setTotal(baseResponse.getResult().getTotal());
        }
        return queryRefundOrderResponse;
    }

    @Override
    public BatchQueryAfterSalesResponse batchQueryAfterSales(BatchQueryAfterSalesRequest request) {
        BatchQueryAfterSalesReq batchQueryAfterSalesReq = orderSdkAdapter.convent2BatchQueryAfterSalesReq(request);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<BatchQueryAfterSalesResp> baseResponse = orderSdkService.batchQueryAfterSales(batchQueryAfterSalesReq, request.getTrackingNo());

        BatchQueryAfterSalesResponse response = new BatchQueryAfterSalesResponse();
        if (baseResponse == null) {
            return response;
        }
        response.setVer(baseResponse.getVer());
        response.setCode(baseResponse.getCode());
        response.setMessage(baseResponse.getMessage());
        BatchQueryAfterSalesResp result = baseResponse.getResult();
        if (result == null) {
            return response;
        }
        response.setNextOrderCode(result.getNextOrderCode());
        response.setNextStartTimestamp(result.getNextStartTimestamp());
        response.setItemList(result.getItemList());
        response.setPageNum(result.getPageNum());
        response.setPageSize(result.getPageSize());
        response.setPages(result.getPages());
        response.setTotal(result.getTotal());
        return response;
    }

    @Override
    public BatchOrdersStateResponse batchQueryOrderStatus(BatchOrdersStateRequest request) {
        QueryOrdersStateReq queryOrdersStateReq = orderSdkAdapter.convent2BatchQueryOrderState(request);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse baseResponse = orderSdkService.queryOrdersState(queryOrdersStateReq, request.getTrackingNo());

        BatchOrdersStateResponse batchOrdersStateResponse = new BatchOrdersStateResponse();
        if (baseResponse == null || baseResponse.getResult() == null) {
            return null;
        }

        return orderSdkAdapter.convent2BatchQueryOrderStateResp(baseResponse, batchOrdersStateResponse);
    }

    @Override
    public QueryOrdersResponse batchQueryByCodes(BatchQueryByCodesRequest request) {
        BatchQueryByCodesReq batchQueryByCodesReq = new BatchQueryByCodesReq();
        batchQueryByCodesReq.setOrderCodes(request.getOrderCodes());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<List<OrderInfoReqs>> baseResponse = orderSdkService.batchQueryByCodes(batchQueryByCodesReq, request.getTrackingNo());

        QueryOrdersResponse response = new QueryOrdersResponse();
        QueryOrdersResponse.DataBean dataBean = new QueryOrdersResponse.DataBean();
        if (!org.springframework.util.CollectionUtils.isEmpty(baseResponse.getResult())) {
            List<QueryOrdersResponse.DataBean.OrderBean> orderBeanList = new ArrayList<>();
            for (OrderInfoReqs orderInfoReqs : baseResponse.getResult()) {
                QueryOrdersResponse.DataBean.OrderBean orderBean = orderSdkAdapter.convent2NEWOrderInfo(orderInfoReqs);
                orderBeanList.add(orderBean);
            }
            dataBean.setOrders(orderBeanList);
        }
        response.setData(dataBean);
        response.setErrcode(baseResponse.getCode() != null ? Integer.parseInt(baseResponse.getCode()) : 500);
        response.setErrmsg(baseResponse.getMessage());
        return response;
    }

    @Override
    public QueryRelatedOrderByCodeResp queryRelatedOrderByCode(QueryRelatedOrderByCodeRequest request) {
        QueryRelatedOrderByCodeReq queryRelatedOrderByCodeReq = orderSdkAdapter.convert2QueryRelatedOrderByCodeRequest(request);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<List<OrderInfoReqs>> baseResponse = orderSdkService.queryRelatedOrderByCode(queryRelatedOrderByCodeReq, request.getTrackingNo());
        return orderSdkAdapter.convent2QueryFatherOrderInfo(baseResponse);
    }

    @Override
    public BaseOrderResponse updateThirdOrderCode(AssortmentSdkUpdateThirdOrderCodeRequest assortmentSdkUpdateThirdOrderCodeRequest) {
        SdkNewOrderUpdateThirdOrderCodeReq sdkNewOrderUpdateThirdOrderCodeReq = orderSdkAdapter.convert2NewOrderUpdateThirdOrderCodeReq(assortmentSdkUpdateThirdOrderCodeRequest);
        return orderSdkAdapter.convent2NewOrderUpdateThirdOrderCode(orderSdkService.updateThirdOrderCode(sdkNewOrderUpdateThirdOrderCodeReq, assortmentSdkUpdateThirdOrderCodeRequest.getTrackingNo()));
    }

    /**
     * 更新三方配送单异常
     *
     * @param request
     * @return
     */
    @Override
    public OrderBaseResponse updateDeliveryAbnormal(AssortmentUpdateDeliveryAbnormalRequest request) {
        SdkUpdateAbnormalState updateAbnormalStateRequest = orderSdkAdapter.convert2SdkUpdateAbnormalState(request);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse baseResponse = orderSdkService.updateAbnormalState(updateAbnormalStateRequest);
        OrderBaseResponse orderBaseResponse = new OrderBaseResponse();
        if (!ObjectUtils.notEqual(RESPONSE_SUCCESS, baseResponse.getCode())) {
            orderBaseResponse.setErrcode(baseResponse.getCode() != null ? Integer.parseInt(baseResponse.getCode()) : null);
            orderBaseResponse.setErrmsg(baseResponse.getMessage());
            return orderBaseResponse;
        }
        UpdateDeliveryInfoByIdRequest updateDeliveryInfoByIdRequest = new UpdateDeliveryInfoByIdRequest();
        updateDeliveryInfoByIdRequest.setDeliveryId(StringUtils.isEmpty(request.getDeliveryId()) ? "0" : request.getDeliveryId());
        updateDeliveryInfoByIdRequest.setOrderId(request.getOrderCode());
        updateDeliveryInfoByIdRequest.setOrderSubState(DeliveryStatusEnum.DELIVERYERROR.getCode());
        return updateDeliveryInfoById(updateDeliveryInfoByIdRequest);
    }

    /**
     * 冲正商品库存，活动库存,商品库存，订单取消，退款
     *
     * @param orderBean 订单信息
     * @param transType TransTypeEnum 冲正类型
     */
    public void backOrdersNotifyActivity(OrderBean orderBean, List<Integer> transType, String backOrdersNotifyActivityQueue,
                                         String backOrdersNotifyActivityExchange) {
        if (orderBean == null) {
            return;
        }
        // 删除订单 通知活动添加商品库存
        ActivityCancelStockRequest activityCancelStockRequestDto = activitySdkAdapter.convert2ActivityCancelStockRequestDto(
                orderBean, transType);
        try {
            Header header = new Header(MQAction.INSERT.getAction(), "backOrdersNotifyActivity", orderBean.getOid(), backOrdersNotifyActivityQueue);
            MQMessage<ActivityCancelStockRequest> message = new MQMessage<>(header, activityCancelStockRequestDto);
            mqService.convertAndSend(backOrdersNotifyActivityExchange, backOrdersNotifyActivityQueue, message);
            ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(),
                    "backOrdersNotifyActivity_end", backOrdersNotifyActivityExchange, backOrdersNotifyActivityQueue + "_"
                            + JSONObject.toJSONString(message));
        } catch (Exception e) {
            //TODO 邮件告警
            ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(),
                    "backOrdersNotifyActivity_error", backOrdersNotifyActivityExchange, backOrdersNotifyActivityQueue);
        }
    }

    private void backOrdersNotifyActivity(OrderBean orderBean, String backOrdersChangeOrderStatusConsumerQueue, String backOrdersNotifyActivityExchange) {
        if (null == orderBean || backOrdersChangeOrderStatusConsumerQueue == null || backOrdersNotifyActivityExchange == null) {
            return;
        }
        String oid = orderBean.getOid();
        Integer status = orderBean.getStatus();
        if (StringUtils.isEmpty(oid)) {
            return;
        }
        ApiLog.info("backOrdersStatusChange", oid, String.valueOf(status));
        OrderStatusChangeRequestDto requestDto = new OrderStatusChangeRequestDto();
        requestDto.setOid(oid);
        requestDto.setOrderStatus(status);
        try {
            Header header = new Header(MQAction.INSERT.getAction(), "backOrdersStatusChange", oid, backOrdersChangeOrderStatusConsumerQueue);
            MQMessage<OrderStatusChangeRequestDto> message = new MQMessage<>(header, requestDto);
            mqService.convertAndSend(backOrdersNotifyActivityExchange, backOrdersChangeOrderStatusConsumerQueue, message);
        } catch (Exception e) {
            //TODO 邮件告警
            ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(),
                    "backOrdersStatusChangeNotify_error", backOrdersNotifyActivityExchange, backOrdersChangeOrderStatusConsumerQueue);
        }
    }


    /**
     * 编辑订单，保持预支付信息
     */
    public BaseOrderResponse updateOrderInfo(OrderPayResponse orderPayResponse, OrderEditInfo orderEditInfo) {
        //TODO 创建自定义信息
        OrderExtInfoDto orderExtInfo = orderSdkAdapter.getOrderExtInfo(orderPayResponse, orderEditInfo);
        OrderEditRequest orderEditRequest = new OrderEditRequest(orderPayResponse.getPayTransId(),
                JSONObject.toJSONString(orderExtInfo));
        orderEditRequest.setOrderId(orderPayResponse.getOrderId());
        orderEditRequest.setTrackingNo(orderEditInfo.getTrackingNo());
        return orderEdit(orderEditRequest);
    }

    public BaseOrderResponse getBaseOrderResponse(String code, String message, String data) {
        BaseOrderResponse baseOrderResponse = new BaseOrderResponse();
        baseOrderResponse.setErrcode(Integer.valueOf(code));
        baseOrderResponse.setErrmsg(message);
        baseOrderResponse.setData(data);
        return baseOrderResponse;
    }

    public CreateOrderResponse getCreateOrderResponse(String code, String message, QueryOrdersResponse.DataBean.OrderBean data) {
        CreateOrderResponse baseOrderResponse = new CreateOrderResponse();
        baseOrderResponse.setErrcode(Integer.valueOf(code));
        baseOrderResponse.setErrmsg(message);
        baseOrderResponse.setData(data);
        return baseOrderResponse;
    }

    @Override
    public CreateOrderResponse createGroupOrder(AssortmentGroupCreateOrderRequest createOrderRequest) {
        GroupCreateOrderRequest groupCreateOrderRequest = orderSdkAdapter.conventGroupCreateOrderRequest(createOrderRequest);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<OrderInfoReqs> baseResponse = orderSdkService.createGroupOrder(groupCreateOrderRequest, createOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2NEWOrderInfoReqs(baseResponse);
    }

    @Override
    public AssortmentAffirmGroupOrderResponse affirmGroupOrder(AssortmentGroupOrderAffirmRequest orderAffirmRequest) {
        GroupOrderAffirmReq groupOrderAffirmReq = orderSdkAdapter.conventGroupAffirmOrderRequest(orderAffirmRequest);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<PaySuccessResp> baseResponse = orderSdkService.affirmGroupOrder(groupOrderAffirmReq, orderAffirmRequest.getTrackingNo());
        return orderSdkAdapter.conventGroupPaySuccessReqs(baseResponse);
    }

    @Override
    public OrderDetailResponse updateGroupOrder(AssortmentGroupUpdateOrderRequest createOrderRequest) {
        GroupOrderUpdateReq groupOrderAffirmReq = orderSdkAdapter.conventGroupUpdateOrderRequest(createOrderRequest);
        if(ObjectUtils.notEqual(createOrderRequest.isUpdateAccounts(), true)) {
            groupOrderAffirmReq.setOrderSettlementDetailList(new ArrayList<>());
        }
        QueryByCodeResponse orderInfo = orderSdkService.updateGroupOrder(groupOrderAffirmReq, createOrderRequest.getTrackingNo());
        OrderDetailResponse response = orderSdkAdapter.convent2OrderDetailResponse(orderInfo);
        return response;
    }

    @Override
    public AssortmentAffirmGroupOrderResponse clearGroupOrder(AssortmentGroupOrderClearRequest groupOrderClearRequest) {
        GroupOrderClearReq groupOrderClearReq1 = new GroupOrderClearReq();
        groupOrderClearReq1.setOrderCode(groupOrderClearRequest.getOrderCode());
        groupOrderClearReq1.setOrderClient(groupOrderClearRequest.getOrderClient());
        groupOrderClearReq1.setPartnerId(groupOrderClearRequest.getCompanyId());
        groupOrderClearReq1.setThirdOrderCode(groupOrderClearRequest.getThirdOrderCode());
        groupOrderClearReq1.setOperator(groupOrderClearRequest.getOperator());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<PaySuccessResp> baseResponse = orderSdkService.clearGroupOrder(groupOrderClearReq1, groupOrderClearRequest.getTrackingNo());
        return orderSdkAdapter.conventGroupPaySuccessReqs(baseResponse);
    }

    @Override
    public OrderDetailResponse updateOrderItem(AssortmentSdkUpdateOrderProductInfoRequest updateOrderProductInfoRequest) {
        QueryOrderByIdResponse queryOrderByIdResponse = null;
        /**
         * 若先清除再更新先清除现有订单商品信息
         */
        if (AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.deleteAndUpdate == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()) {
            this.orderSdkService.clearGroupOrder(this.orderSdkAdapter.convertAssortmentSdkUpdateOrderProductInfoRequestTo(updateOrderProductInfoRequest), updateOrderProductInfoRequest.getTrackingNo());
        } else if (AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.update == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()
                || AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.updatePrePayPrice == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()
                || AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.updateByOrderProductDetailId == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()
                || AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.deleteOrderProduct == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()) {
            queryOrderByIdResponse = this.queryOrderById(this.orderSdkAdapter.convertAssortmentSdkUpdateOrderProductInfoRequestToBaseQueryOrderRequest(updateOrderProductInfoRequest));
        }

        /**
         * 加菜把加的菜添加到pos拉加菜缓存
         */
        if (AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.update == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()) {
            this.syncAddProductToCache(updateOrderProductInfoRequest);
        }

        // 历史订单商品
        List<OrderBean.ProductBean> productListByOrder = queryOrderByIdResponse != null && queryOrderByIdResponse.getData() != null && CollectionUtils.isNotEmpty(queryOrderByIdResponse.getData().getProductList())
                ? queryOrderByIdResponse.getData().getProductList() : new ArrayList<>();
        // 请求订单商品
        List<CreateOrderProductRequest> orderItemListByRequest = updateOrderProductInfoRequest.getOrderItemList() == null ? new ArrayList<>() : updateOrderProductInfoRequest.getOrderItemList();

        /**
         * 更新订单商品详情(更新要修改的商品重量信息)
         */
        if (AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.updateByOrderProductDetailId == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()
            || AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.deleteOrderProduct == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()) {

            boolean isDeleted = AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.deleteOrderProduct == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum() ? true : false;

            // 1.先把历史订单商品转化为请求订单商品
            orderItemListByRequest = productListByOrder.stream().map(p -> this.orderSdkAdapter.convertOrderBeanProductBean2CreateOrderProductRequest(p, updateOrderProductInfoRequest.getTrackingNo())).collect(Collectors.toList());
            Map<Long, CreateOrderProductRequest> createOrderProductRequestMap = new HashMap<>();
            for(CreateOrderProductRequest createOrderProductRequest : orderItemListByRequest) {
                createOrderProductRequestMap.put(createOrderProductRequest.getId(), createOrderProductRequest);
                if(CollectionUtils.isNotEmpty(createOrderProductRequest.getComboProduct())) {
                    createOrderProductRequestMap.putAll(createOrderProductRequest.getComboProduct().stream().collect(Collectors.toMap(CreateOrderProductRequest::getId, v -> v, (k, v) -> v)));
                }
            }
            List<CreateOrderProductRequest> deletedOrderProductList = new ArrayList<>();
            // 2.更新要修改的商品的重量
            if(CollectionUtils.isNotEmpty(updateOrderProductInfoRequest.getOrderItemList())) {
                updateOrderProductInfoRequest.getOrderItemList().forEach( t -> {
                    CreateOrderProductRequest createOrderProductRequest = createOrderProductRequestMap.get(t.getId());
                    if(createOrderProductRequest != null) {
                        createOrderProductRequest.setIsDeleted(isDeleted);
                        if(isDeleted) {
                            if(CollectionUtils.isNotEmpty(createOrderProductRequest.getComboProduct())) {
                                createOrderProductRequest.getComboProduct().forEach(ct -> {
                                    ct.setIsDeleted(true);
                                });
                            }
                            deletedOrderProductList.add(createOrderProductRequest);
                        } else {
                            if(t.getWeight() != null && t.getWeight() > 0D) {
                                createOrderProductRequest.setWeight(t.getWeight());
                            }
                            if(t.getNumber() != null && t.getNumber() > 0) {
                                createOrderProductRequest.setNumber(t.getNumber());
                            }
                        }
                    }
                });
            }
            /**
             * 订单商品删除时需要放入到缓存给到pos增加菜品拉单接口（有删除标志）
             */
            if(isDeleted && CollectionUtils.isNotEmpty(deletedOrderProductList)) {
                updateOrderProductInfoRequest.setOrderItemList(deletedOrderProductList);
                this.syncAddProductToCache(updateOrderProductInfoRequest);
            }
            updateOrderProductInfoRequest.setOrderItemList(orderItemListByRequest);
        } else if (AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.updatePrePayPrice == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()
                ||  AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.updatePrePayPriceTwo == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum() ) {
            orderItemListByRequest = productListByOrder.stream().map(p -> this.orderSdkAdapter.convertOrderBeanProductBean2CreateOrderProductRequest(p, updateOrderProductInfoRequest.getTrackingNo())).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(updateOrderProductInfoRequest.getOrderItemList())) {
                orderItemListByRequest.forEach(t -> {
                    CreateOrderProductRequest createOrderProductRequest = updateOrderProductInfoRequest.getOrderItemList().stream().filter(o -> Objects.equals(o.getId(), t.getId())).findFirst().orElse(null);
                    if(createOrderProductRequest != null) {
                        t.setTotalDiscountAmount(createOrderProductRequest.getTotalDiscountAmount());
                        t.setAccounts(createOrderProductRequest.getAccounts());
                        if (CollectionUtils.isNotEmpty(createOrderProductRequest.getComboProduct())) {
                            t.setComboProduct(createOrderProductRequest.getComboProduct());
                        }
                    }
                });
            }
            updateOrderProductInfoRequest.setOrderItemList(orderItemListByRequest);
        } else {
            /**
             * 新增，考虑相同商品合并
             */
            for(OrderBean.ProductBean eachProductBean : productListByOrder) {
                //称重商品不用合并
                if (ProductTypeEnum.WEIGHT_PRODUCT.getCode() == eachProductBean.getProductType()) {
                    orderItemListByRequest.add(this.orderSdkAdapter.convertOrderBeanProductBean2CreateOrderProductRequest(eachProductBean, updateOrderProductInfoRequest.getTrackingNo()));
                    continue;
                }
                boolean hasWeightSetmeal = false;
                if(Objects.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), eachProductBean.getProductType()) || Objects.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), eachProductBean.getProductType())) {
                    if(CollectionUtils.isNotEmpty(eachProductBean.getComboProduct())) {
                        long count = eachProductBean.getComboProduct().stream().filter(c -> {
                            return Objects.equals(ProductTypeEnum.WEIGHT_PRODUCT.getCode(), c.getProductType());
                        }).count();
                        hasWeightSetmeal = count > 0;
                    }
                }
                if(hasWeightSetmeal) {
                    orderItemListByRequest.add(this.orderSdkAdapter.convertOrderBeanProductBean2CreateOrderProductRequest(eachProductBean, updateOrderProductInfoRequest.getTrackingNo()));
                    continue;
                }
                StringBuilder compareProductInfoFromOrder = new StringBuilder();
                Map<String, OrderBean.ProductBean> combProductMap = new HashMap<>();
                compareProductInfoFromOrder.append(eachProductBean.getProductId()).append(JSONObject.toJSONString(eachProductBean.getAddInfo()));
                if ((ProductTypeEnum.SETMEAL_PRODUCT.getCode() == eachProductBean.getProductType() || ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode() == eachProductBean.getProductType()) && CollectionUtils.isNotEmpty(eachProductBean.getComboProduct())) {
                    List<OrderBean.ProductBean> comboProductList = eachProductBean.getComboProduct();
                    comboProductList.forEach(comboProduct -> {
                        combProductMap.put(comboProduct.getProductId() + comboProduct.getAddInfo(), comboProduct);
                        compareProductInfoFromOrder.append(comboProduct.getProductId()).append(JSONObject.toJSONString(comboProduct.getAddInfo()));
                    });
                }
                boolean isFind = false;
                for(CreateOrderProductRequest createOrderProductRequest : orderItemListByRequest) {
                    if (ProductTypeEnum.WEIGHT_PRODUCT.getCode() == createOrderProductRequest.getProductType()) {
                        continue;
                    }
                    StringBuilder compareProductInfoFromRequest = new StringBuilder();
                    compareProductInfoFromRequest.append(createOrderProductRequest.getProductId()).append(JSONObject.toJSONString(createOrderProductRequest.getAddInfo()));
                    if ((ProductTypeEnum.SETMEAL_PRODUCT.getCode() == eachProductBean.getProductType() || ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode() == eachProductBean.getProductType()) && CollectionUtils.isNotEmpty(createOrderProductRequest.getComboProduct())) {
                        List<CreateOrderProductRequest> comboProductList = createOrderProductRequest.getComboProduct();
                        comboProductList.forEach(comboProduct -> {
                            compareProductInfoFromRequest.append(comboProduct.getProductId()).append(JSONObject.toJSONString(createOrderProductRequest.getAddInfo()));
                        });
                    }

                    if (ObjectUtils.equals(compareProductInfoFromOrder.toString(), compareProductInfoFromRequest.toString())) {
                        createOrderProductRequest.setNumber(createOrderProductRequest.getNumber() + eachProductBean.getNumber());
                        createOrderProductRequest.setTotalDiscountAmount(createOrderProductRequest.getTotalDiscountAmount() + eachProductBean.getProductSharePrice().longValue() * eachProductBean.getNumber());
                        createOrderProductRequest.setId(eachProductBean.getId());
                        if (ProductTypeEnum.SETMEAL_PRODUCT.getCode() == eachProductBean.getProductType() || ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode() == eachProductBean.getProductType()) {
                            createOrderProductRequest.getComboProduct().forEach(comboProduct -> {
                                OrderBean.ProductBean combProductBean = combProductMap.get(comboProduct.getProductId() + comboProduct.getAddInfo());
                                comboProduct.setNumber(comboProduct.getNumber() + combProductBean.getNumber());
                                comboProduct.setId(combProductBean.getId());
                                comboProduct.setTotalDiscountAmount(comboProduct.getTotalDiscountAmount() + combProductBean.getProductSharePrice().longValue() * combProductBean.getNumber());
                            });
                        }
                        isFind = true;
                        break;
                    }
                }
                if (!isFind) {
                    orderItemListByRequest.add(this.orderSdkAdapter.convertOrderBeanProductBean2CreateOrderProductRequest(eachProductBean, updateOrderProductInfoRequest.getTrackingNo()));
                }
            }
        }

        //复用结算逻辑
        if (updateOrderProductInfoRequest.getOrderItemList() == null) {
            updateOrderProductInfoRequest.setOrderItemList(orderItemListByRequest);
        }

        if (AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.updatePrePayPrice == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()) {
            // 围餐订单的创建不一定是付款人，需要重新赋值
            if (OrderClientType.WAI_MEAL.getIndex() == Integer.valueOf(queryOrderByIdResponse.getData().getOrderClient())) {
                queryOrderByIdResponse.getData().setUserId(updateOrderProductInfoRequest.getUserId());
            }
            BaseOrderResponse baseOrderResponse = this.updateWcStockAndScore(queryOrderByIdResponse.getData(), orderItemListByRequest, updateOrderProductInfoRequest.getActivityUpdateStockRequest(), updateOrderProductInfoRequest.getAccounts(),
                    updateOrderProductInfoRequest.getMqMessageRequest(), updateOrderProductInfoRequest.getMenuType());
            if (!Objects.equals(baseOrderResponse.getErrcode(), RESPONSE_SUCCESS)) {
                OrderDetailResponse orderDetailResponse = new OrderDetailResponse();
                orderDetailResponse.setErrcode(baseOrderResponse.getErrcode());
                orderDetailResponse.setErrmsg(baseOrderResponse.getErrmsg());
                return orderDetailResponse;
            }
        }

        OrderDetailResponse baseResponse = this.updateGroupOrder(this.orderSdkAdapter.convertAssortmentSdkUpdateOrderProductInfoRequestToAssortmentGroupUpdateOrderRequest(updateOrderProductInfoRequest));

        if (AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.updatePrePayPrice == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()) {
            if (baseResponse == null || ObjectUtils.notEqual(baseResponse.getErrcode(),RESPONSE_SUCCESS)){
                MqMessageRequest mqMessageRequest = updateOrderProductInfoRequest.getMqMessageRequest();
                backOrdersNotifyActivity(queryOrderByIdResponse.getData(), mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
            }
        }
        /**
         * 加菜或者删菜的时候通知pos拉菜
         */
        if (AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.update == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()
            || AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.deleteOrderProduct == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()) {
            this.sendOrderAddProductMessage(updateOrderProductInfoRequest);
        }

        return baseResponse;
    }

    @Override
    public OrderBaseResponse clearTableNumber(ClearTableRequest clearTableRequest) {
        OrderBaseResponse orderBaseResponse = new OrderBaseResponse();
        orderBaseResponse.setErrcode(100);
        orderBaseResponse.setErrmsg("成功");
        mealCacheManager.deleteTableNumberStatus(clearTableRequest.getPartnerId(), clearTableRequest.getStoreId(), clearTableRequest.getTableNumber());
        mealCacheManager.deleteOrderUpdateVersion(clearTableRequest.getPartnerId(), clearTableRequest.getStoreId(), clearTableRequest.getTableNumber());
        mealCacheManager.deleteOrderCreatePreParmentLock(clearTableRequest.getPartnerId(), clearTableRequest.getStoreId(), clearTableRequest.getTableNumber());
        assortmentCustomerInfoManager.clearBindTable(clearTableRequest.getPartnerId(), clearTableRequest.getStoreId(), clearTableRequest.getTableNumber());
        //判断当前桌号是否存在绑定订单  存在则删除
        String orderId = mealCacheManager.getMealOrder(clearTableRequest.getPartnerId(), clearTableRequest.getStoreId(), clearTableRequest.getTableNumber());
        mealCacheManager.clearAll(clearTableRequest.getPartnerId(), clearTableRequest.getStoreId(), clearTableRequest.getTableNumber());
        if (ClearTableRequest.OpClearTableEnum.closeOrder == clearTableRequest.getOpClearTableEnum()) {
            if (StringUtils.isNotEmpty(orderId)) {
                BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
                baseQueryOrderRequest.setOrderId(orderId);
                baseQueryOrderRequest.setTrackingNo(clearTableRequest.getTrackingNo());
                QueryOrderByIdResponse queryOrderByIdResponse = this.queryOrderById(baseQueryOrderRequest);
                if (ObjectUtils.notEqual(queryOrderByIdResponse.getErrcode(), 100) || queryOrderByIdResponse.getData() == null) {
                    orderBaseResponse.setErrcode(queryOrderByIdResponse.getErrcode());
                    orderBaseResponse.setErrmsg(queryOrderByIdResponse.getErrmsg());
                    return orderBaseResponse;
                }
                if (ObjectUtils.equals(queryOrderByIdResponse.getData().getPayStatus(), PayStatus.NOT_PAY.getCode())) {
                    OrderBean orderBean = queryOrderByIdResponse.getData();
                    GroupDiningCloseReq groupDiningCloseReq = new GroupDiningCloseReq();
                    groupDiningCloseReq.setOrderCode(orderBean.getOid());
                    groupDiningCloseReq.setCancelReason("主动清台");
                    groupDiningCloseReq.setPartnerId(orderBean.getCompanyId());
                    //围餐
                    groupDiningCloseReq.setOrderClient(19);
                    groupDiningCloseReq.setOperator(clearTableRequest.getOperator());
                    com.freemud.application.sdk.api.ordercenter.response.BaseResponse<PaySuccessResp> baseResponse = orderSdkService.groupClose(groupDiningCloseReq, LogThreadLocal.getTrackingNo());

                    if (ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), baseResponse.getCode())) {
                        orderBaseResponse.setErrcode(Integer.valueOf(baseResponse.getCode()));
                        orderBaseResponse.setErrmsg(baseResponse.getMessage());
                        return orderBaseResponse;
                    }
                }
                if (StringUtils.isNotBlank(queryOrderByIdResponse.getData().getExtInfo())) {
                    OrderExtInfoDto extInfo = JSONObject.parseObject(queryOrderByIdResponse.getData().getExtInfo(), OrderExtInfoDto.class);
                    /**
                     * 清除预支付订单自增--transId
                     */
                    if (extInfo != null) {
                        mealCacheManager.deleteMealTransId(clearTableRequest.getPartnerId(), clearTableRequest.getStoreId(), clearTableRequest.getTableNumber(), extInfo.getPayTransId());
                    }
                }
            }
        }
        //查询当前桌号状态
        GetStoreTableRequest storeTableListRequest = new GetStoreTableRequest();
        storeTableListRequest.setPartnerId(clearTableRequest.getPartnerId());
        storeTableListRequest.setStoreCode(clearTableRequest.getStoreId());
        storeTableListRequest.setTableCode(clearTableRequest.getTableNumber());
        com.freemud.application.sdk.api.base.BaseResponse<GetStoreTableResponse> storeTable = storeCenterService.getStoreTable(storeTableListRequest, LogThreadLocal.getTrackingNo());
        if (ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), storeTable.getCode()) || storeTable.getData() == null) {
            orderBaseResponse.setErrcode(Integer.valueOf(storeTable.getCode()));
            orderBaseResponse.setErrmsg(storeTable.getMessage());
        }
        if (storeTable.getData().getActiveFlag() == ActiveFlagEnum.ACTIVE_FLAG_1.getCode() &&
                storeTable.getData().getOrderState() == OpenTableEnum.OPEN_TABLE_1.getCode()) { //只有桌号启用且已开台才调用清台
            //调用门店服务解锁桌号
            com.freemud.application.sdk.api.base.BaseResponse tableNumberStatus = this.changeTableNumberStatus(clearTableRequest);
            if (ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), tableNumberStatus.getCode())) {
                //发送邮件告警--异常清空桌号锁定状态失败
                orderBaseResponse.setErrcode(Integer.valueOf(tableNumberStatus.getCode()));
                orderBaseResponse.setErrmsg(tableNumberStatus.getMessage());
            }
        }
        return orderBaseResponse;
    }

    private com.freemud.application.sdk.api.base.BaseResponse changeTableNumberStatus(ClearTableRequest clearTableRequest) {
        //调用门店服务锁定桌号
        ChangeTableOrderStateRequest tableOrderStateRequest = new ChangeTableOrderStateRequest();
        tableOrderStateRequest.setTableCode(clearTableRequest.getTableNumber());
        tableOrderStateRequest.setStoreCode(clearTableRequest.getStoreId());
        tableOrderStateRequest.setOrderState(OpenTableEnum.OPEN_TABLE_2.getCode());  //1开台  2清台
        tableOrderStateRequest.setPartnerId(clearTableRequest.getPartnerId());
        tableOrderStateRequest.setUpdateUserId(clearTableRequest.getUserId());
        tableOrderStateRequest.setRemark("清台");
        return storeCenterService.changeTableOrderState(tableOrderStateRequest, LogThreadLocal.getTrackingNo());
    }

    /**
     * 只修改订单商品称重信息
     *
     * @param updateOrderProductInfoRequest
     * @return
     */
    public OrderDetailResponse updateByOrderProductDetailId(AssortmentSdkUpdateOrderProductInfoRequest updateOrderProductInfoRequest) {
        GroupOrderUpdateReq groupOrderUpdateReq = new GroupOrderUpdateReq();
        groupOrderUpdateReq.setPartnerId(updateOrderProductInfoRequest.getPartnerId());
        groupOrderUpdateReq.setOrderCode(updateOrderProductInfoRequest.getOrderCode());
        groupOrderUpdateReq.setOrderClient(updateOrderProductInfoRequest.getOrderClient());
        List<OrderItemCreateReq> orderItemList = new ArrayList<>();
        updateOrderProductInfoRequest.getOrderItemList().forEach(createOrderProductRequest -> {
            OrderItemCreateReq orderItemCreateReq = new OrderItemCreateReq();
            orderItemCreateReq.setId(createOrderProductRequest.getId());
            orderItemCreateReq.setWeight(createOrderProductRequest.getWeight());
            orderItemList.add(orderItemCreateReq);
        });
        groupOrderUpdateReq.setOrderItemList(orderItemList);
        QueryByCodeResponse orderInfo = orderSdkService.updateGroupOrder(groupOrderUpdateReq, updateOrderProductInfoRequest.getTrackingNo());
        OrderDetailResponse response = orderSdkAdapter.convent2OrderDetailResponse(orderInfo);
        return response;
    }

    /**
     * 新增菜品需要放入到缓存给到pos增加菜品拉单接口
     *
     * @param updateOrderProductInfoRequest
     */
    private void syncAddProductToCache(AssortmentSdkUpdateOrderProductInfoRequest updateOrderProductInfoRequest) {
        if (AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.updateByOrderProductDetailId == updateOrderProductInfoRequest.getOpUpdateOrderItemEnum()) {
            return;
        }
        this.assortmentOrderManager.saveOrderAddProduct(OrderAssortmentDtoConvertToDMVoAdapter.convertAssortmentSdkUpdateOrderProductInfoRequestToDMOrderVo(updateOrderProductInfoRequest));
    }

    private void sendOrderAddProductMessage(AssortmentSdkUpdateOrderProductInfoRequest updateOrderProductInfoRequest) {
        PushMessageNoticeDto pushMessageNoticeDto = new PushMessageNoticeDto();
        pushMessageNoticeDto.setPartnerId(updateOrderProductInfoRequest.getPartnerId());
        pushMessageNoticeDto.setStoreId(updateOrderProductInfoRequest.getStoreId());
        //pushMessageNoticeDto.setTargetId(userId);
        pushMessageNoticeDto.setTargetType(2);
        pushMessageNoticeDto.setTtl(0);
        pushMessageNoticeDto.setVer("1");
        PushMessageNoticeDto.Message message = new PushMessageNoticeDto.Message();
        message.setType(MessageCenterType.ORDER_GET_ADD_PRODUCT.getType());
        PushMessageNoticeDto.Message.Content content = new PushMessageNoticeDto.Message.Content();
        content.setOid(updateOrderProductInfoRequest.getOrderCode());
        message.setContent(content);
        pushMessageNoticeDto.setData(new Gson().toJson(message));
        this.messageCenterClient.createMessage(pushMessageNoticeDto, LogThreadLocal.getTrackingNo());
    }


    public AssortmentOrderGetOrderAddProductResponse getOrderAddProduct(OrderCommonRequest orderCommonRequest) {
        AssortmentOrderGetOrderAddProductResponse assortmentOrderGetOrderAddProductResponse = new AssortmentOrderGetOrderAddProductResponse();
        List<DMOrderItemVo> dmOrderItemVos = this.assortmentOrderManager.getOrderAddProducts(orderCommonRequest.getPartnerId(), orderCommonRequest.getOrderCode());
        if (CollectionUtils.isEmpty(dmOrderItemVos)) {
            assortmentOrderGetOrderAddProductResponse.setErrcode(Integer.valueOf(ResponseResult.ORDER_QUERYORDER_ERROR.getCode()));
            return assortmentOrderGetOrderAddProductResponse;
        }
        List<AssortmentOrderProductVo> assortmentOrderProductVos = new ArrayList<>();
        dmOrderItemVos.forEach(dmOrderItemVo -> {
            AssortmentOrderProductVo assortmentOrderProductVo = OrderDMVoConvertToAssortmentDtoAdapter.convertorderProductVoToOrderProductVo(dmOrderItemVo);
            if (CollectionUtils.isNotEmpty(dmOrderItemVo.getComboProduct())) {
                List<AssortmentOrderProductVo> comOrderInfo = new ArrayList<>();
                dmOrderItemVo.getComboProduct().forEach(each -> {
                    AssortmentOrderProductVo assortmentOrderProductVo1 = OrderDMVoConvertToAssortmentDtoAdapter.convertorderProductVoToOrderProductVo(each);
                    comOrderInfo.add(assortmentOrderProductVo1);
                });
                assortmentOrderProductVo.setComboProduct(comOrderInfo);
            }
            assortmentOrderProductVos.add(assortmentOrderProductVo);
        });
        assortmentOrderGetOrderAddProductResponse.setAssortmentOrderProductVos(assortmentOrderProductVos);
        this.assortmentOrderManager.deleteOrderAddProducts(orderCommonRequest.getPartnerId(), orderCommonRequest.getOrderCode());
        assortmentOrderGetOrderAddProductResponse.setErrcode(Integer.valueOf(ResponseResult.SUCCESS.getCode()));
        return assortmentOrderGetOrderAddProductResponse;
    }

    @Override
    public AfterSalesListResp queryAfterSalesListES(QueryAfterSalesOrderConditionsReq queryRequest, String trackNo) {
        return orderDownLoadSdkService.queryAfterSalesOrderConditions(queryRequest, "");
    }

    @Override
    public QueryOrderByIdResponse queryOrderByCodeES(String partnerId, String orderCode, String trackingNo) {
        QueryByCodeResponse orderInfo = orderDownLoadSdkService.queryOrderByCode(partnerId,orderCode,trackingNo);
        if (orderInfo == null || orderInfo.getResult() == null) {
            return new QueryOrderByIdResponse();
        }
        QueryOrderByIdResponse response = new QueryOrderByIdResponse();
        response.setErrcode(Integer.parseInt(orderInfo.getCode()));
        response.setErrmsg(orderInfo.getMessage());
        if (StringUtils.isEmpty(orderInfo.getResult().getOrderCode())) {
            return response;
        }
        QueryOrderByIdResponse orderByIdResponse = orderSdkAdapter.convent2QueryOrderByIdResponse(orderInfo);
        return orderByIdResponse;
    }

    @Override
    public QueryOrderByIdResponse queryOrderByDownstream(String downstreamPosCode, String downstreamThirdOrderCode, String trackingNo) {
        QueryByCodeResponse orderInfo = orderSdkService.getOrderInfoByDownstream(downstreamPosCode,downstreamThirdOrderCode,trackingNo);
        if (orderInfo == null || orderInfo.getResult() == null) {
            return new QueryOrderByIdResponse();
        }
        QueryOrderByIdResponse response = new QueryOrderByIdResponse();
        response.setErrcode(Integer.parseInt(orderInfo.getCode()));
        response.setErrmsg(orderInfo.getMessage());
        if (StringUtils.isEmpty(orderInfo.getResult().getOrderCode())) {
            return response;
        }
        QueryOrderByIdResponse orderByIdResponse = orderSdkAdapter.convent2QueryOrderByIdResponse(orderInfo);
        return orderByIdResponse;
    }

    @Override
    public QueryOrdersResponse queryOrderWithCoupon(String userId, String trackingNo) {

        com.freemud.application.sdk.api.ordercenter.response.BaseResponse response
                = orderSdkService.queryOrderWithCoupon(userId, trackingNo);
        return orderSdkAdapter.convent2QueryOrdersResponse(response);
    }

    @Override
    public BaseOrderResponse updateDownstreamThirdOrderCode(AssortmentSdkUpdateDownstreamThirdOrderCodeRequest assortmentSdkUpdateDownstreamThirdOrderCodeRequest) {
        UpdateDownstreamOrderCodeReq updateDownstreamOrderCodeReq = orderSdkAdapter.convert2NewOrderUpdateDownstreamThirdOrderCodeReq(assortmentSdkUpdateDownstreamThirdOrderCodeRequest);
        return orderSdkAdapter.convent2NewOrderUpdateThirdOrderCode(orderSdkService.updateDownstreamThirdOrderCode(updateDownstreamOrderCodeReq, assortmentSdkUpdateDownstreamThirdOrderCodeRequest.getTrackingNo()));
    }

    @Override
    public BaseOrderResponse updatePickUpGoodNo(OrderModifyRelatingCodeReq orderModifyRelatingCodeReq, String trackingNo) {
        return orderSdkAdapter.convent2UpdatePickUpGoodNo(orderSdkService.updatePickUpGoodNo(orderModifyRelatingCodeReq, trackingNo));
    }

    private void setTimeout(BaseQueryOrderRequest baseQueryOrderRequest,POSOrderOperationBaseReq request){
        String partnerId = baseQueryOrderRequest.getPartnerId();
        String storeCode = baseQueryOrderRequest.getShopId();
        String trackingNo = baseQueryOrderRequest.getTrackingNo();
        if (StringUtils.isEmpty(storeCode)) {
            return ;
        }
        StoreInfoRequest storeInfoRequest = new StoreInfoRequest();
        storeInfoRequest.setPartnerId(partnerId);
        storeInfoRequest.setStoreCode(storeCode);
        StoreResponse storeResponse = storeCenterService.getStoreInfo(storeInfoRequest, trackingNo);
        if (storeResponse == null || storeResponse.getBizVO() == null ) {
            return ;
        }
        StoreResponse.Configuration configuration = storeResponse.getBizVO().getStoreConfig();
        String orderWarnTime = storeResponse.getBizVO().getOrderWarnTime();
        Integer timeout = 0;
        //自配送外卖单
        if (configuration != null) {
            //外卖单
            if (OrderType.GENERAL_EXPRESS.equals(baseQueryOrderRequest.getOrderType()) || OrderType.RESERVED_EXPRESS.equals(baseQueryOrderRequest.getOrderType())) {
                if (StringUtils.isNotEmpty(configuration.getAutoTakeOutTakeOrderWorkflowFinishTime())) {
                    timeout = AutoOrderConfigTime.getTime(configuration.getAutoTakeOutTakeOrderWorkflowFinishTime());
                }
                //预约单
                if(OrderType.RESERVED_EXPRESS.equals(baseQueryOrderRequest.getOrderType())
                        && StringUtils.isNotEmpty(configuration.getAppointAutoTakeOutTakeOrderWorkflowFinishTime())){
                    timeout = AutoOrderConfigTime.getTime(configuration.getAppointAutoTakeOutTakeOrderWorkflowFinishTime());
                }
            } else {//自提、堂食单
                if (StringUtils.isNotEmpty(configuration.getAutoSelfmentionTakeOrderWorkflowFinishTime())) {
                    timeout = AutoOrderConfigTime.getTime(configuration.getAutoSelfmentionTakeOrderWorkflowFinishTime());
                }
                //自提、堂食预约单
                if((OrderType.RESERVED_DINE_IN.equals(baseQueryOrderRequest.getOrderType()) || OrderType.RESERVED_SELF_PICKUP.equals(baseQueryOrderRequest.getOrderType()))
                        && StringUtils.isNotEmpty(configuration.getAppointAutoSelfmentionTakeOrderWorkflowFinishTime())){
                    timeout = AutoOrderConfigTime.getTime(configuration.getAppointAutoSelfmentionTakeOrderWorkflowFinishTime());
                }
            }
        } else {
            timeout = 120;
        }
        //预约单提醒任务，触发放拉单队列
        if (OrderType.RESERVED_EXPRESS.equals(baseQueryOrderRequest.getOrderType())
                || OrderType.RESERVED_DINE_IN.equals(baseQueryOrderRequest.getOrderType())
                || OrderType.RESERVED_SELF_PICKUP.equals(baseQueryOrderRequest.getOrderType())){
            //外卖预约单
            if(OrderType.RESERVED_EXPRESS.equals(baseQueryOrderRequest.getOrderType()) &&
                    configuration != null && configuration.getDeliveryOrderWarnTime() != null){
                orderWarnTime = configuration.getDeliveryOrderWarnTime();
            }
            request.setRemindTime(getMinTime(orderWarnTime));
        }
        request.setTimeout(timeout);
    }


    public OrderTaskReq saveOrderTaskReq(String orderWarnTime, Long gmtExpect) {
        OrderTaskReq orderTaskReq = new OrderTaskReq();
        Date date = new Date(gmtExpect);
        long timeStamp = getMinTime(orderWarnTime) * 60 * 1000;
        Date warnDate = new Date(gmtExpect-timeStamp);
        orderTaskReq.setTaskTime(DateUtil.convert2String(date,DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        orderTaskReq.setProcessingTime(DateUtil.convert2String(warnDate,DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        return orderTaskReq;
    }

    public Integer getMinTime(String code) {
        Integer minTime = 0;
        if(StringUtils.isBlank(code)){
            return minTime;
        }
        switch (code) {
            case "1":
                minTime = 15;
                break;
            case "2":
                minTime = 30;
                break;
            case "3":
                minTime = 45;
                break;
            case "4":
                minTime = 60;
                break;
            case "5":
                minTime = 5;
                break;
            case "6":
                minTime = 10;
                break;
            default:
                minTime = 0;
        }
        return minTime;
    }

    /**
     * 查询门店的组织机构
     * @param partnerId
     * @param storeCode
     * @return
     */
    private List<String> getOrgIds(String partnerId, String storeCode) {
        GetOrgTreeListRequest request = new GetOrgTreeListRequest();
        request.setPartnerId(partnerId);
        request.setStoreCode(storeCode);
        BaseResponse<List<String>> orgList = storeCenterService.getOrgList(request, LogThreadLocal.getTrackingNo());
        if (orgList != null && ResponseResult.SUCCESS.getCode().equals(orgList.getCode())) {
            return orgList.getData();
        }
        return null;
    }
}
