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 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.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.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.adapter.OrderCenterSdkAdapter;
import com.freemud.application.sdk.api.ordercenter.constant.InterfaceAddressConstant;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.entities.v1.ProductBeanV1;
import com.freemud.application.sdk.api.ordercenter.enums.*;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.OrderStatusV1;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.OrderTypeV1;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.RefundStatusV1;
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.orderInfo.AfterSalesOrderResp;
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.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.response.vo.GetOrgTreeListResponse;
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.constant.CommonConstant;
import com.freemud.sdk.api.assortment.order.domain.ResponseCodeConstant;
import com.freemud.sdk.api.assortment.order.entities.promption.ActivityUpdateStockRequest;
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.service.OrderCenterSdkService;
import com.freemud.sdk.api.assortment.order.util.AssortOrderLogUtil;
import com.freemud.sdk.api.assortment.order.util.BeanUtil;
import com.freemud.sdk.api.assortment.order.vo.AssortmentOrderProductVo;
import com.google.gson.Gson;
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.beans.factory.annotation.Value;
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 OrderCenterSdkAdapter orderCenterSdkAdapter;
    @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;

    /**
     *  规避 发版时间配置的双虎
     */
    @Value("${avoid.version.upgrade.config:}")
    private String avoidVersionUpgradeConfig;

    @Value("${version.upgrade.weekDay:}")
    private List<Integer> weekDay;

    private static final String backOrdersChangeOrderStatusConsumerQueue = "program.backorders_change_order_status_consumer_queue";
    private static final String backOrdersNotifyActivityExchange = "program.backorders_notify_activity_exchange";

    @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.OrderBaseResp<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.getBaseCreateOrderRequest().getMenuType(),config.getOpenId());
        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.OrderBaseResp<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<OrderBeanV1> productOrderInfo = createFatherSonOrderResponse.getOrderBeanList().stream().filter(orderBeanTemp -> 1 == orderBeanTemp.getBizType()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(productOrderInfo)) {
            return CreateFatherSonOrderResponse.error("501", "");
        }
        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.getMenuType(),createFatherSonOrderRequest.getOpenId());
        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.OrderBaseResp<OrderInfoReqs> order = orderSdkService.createOrderByPlatform(request, baseCreateOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2NEWOrderInfoReqs(order);
    }

    /**
     *  请使用 订单服务的feign调用
     * @param orderBean
     * @param products
     * @param updateStockRequest
     * @param accounts
     * @param menuType
     * @param openId
     * @return
     */
    @Deprecated
    private BaseOrderResponse updateStockAndScore(OrderBeanV1 orderBean, List<CreateOrderProductRequest> products, ActivityUpdateStockRequest updateStockRequest,
                                                  List<CreateOrderAccountRequest> accounts, String menuType, String openId) {
        //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);
        // update by miaohui 20201030 for 【ID1018638】【C端服务端】活动库存接口调整对接
        // 原逻辑只检测扣减库存不为空时调用，现改为扣减库存不为空或参加活动不为空时调用
        if (activityUpdateStockRequest != null && (CollectionUtils.isNotEmpty(activityUpdateStockRequest.getStock()) || CollectionUtils.isNotEmpty(activityUpdateStockRequest.getActivityList()))) {
            com.freemud.application.sdk.api.promotioncenter.request.promotion.ActivityUpdateStockRequest req = this.convertSdkBean(activityUpdateStockRequest);
            BaseResponse activityResponse = promotionSdkService.subtractStock(req, "");
//            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);
                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);
                return BaseOrderResponse.getErrorBaseOrderResponse(userScoreResponse.getCode(), "积分不足");
            }
        }

        // 下单成锁定劵，冻结失败提示下单失败并冲正库存积分等,判断支付渠道，积分和svc卡直接核销，无需锁定10102 = svc卡支付 || 支付金额小于等于0
        //todo:统一流程 下单锁券再核销
        CouponRequest request = orderSdkAdapter.convert2PreCheckRequest(orderBean, accounts, openId);
        if (request != null) {
            request.setChannel_ids(getOrgCodes(orderBean.getCompanyId(),orderBean.getShopId()));
            BaseResponse<CouponLockResponse> couponLockResponseBaseResponse = offlineCouponSdkService.precheckAndLock(request, LogThreadLocal.getTrackingNo());
            if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, couponLockResponseBaseResponse.getCode())) {
                CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(), AfterSalesType.SYSTEM_CANCEL, "锁定券码失败", "", null);
                orderCancel(cancelOrderRequest);
                //失败异步冲正库存，取消订单
                backOrdersNotifyActivity(orderBean);
                return BaseOrderResponse.getErrorBaseOrderResponse(couponLockResponseBaseResponse.getCode(), couponLockResponseBaseResponse.getMessage());
            }
        }
        return BaseOrderResponse.getErrorBaseOrderResponse(RESPONSE_SUCCESS_STR, "");
    }

    List<String> getOrgCodes(String partnerId, String storeCode) {
        GetOrgTreeListRequest request = new GetOrgTreeListRequest();
        request.setPartnerId(partnerId);
        request.setStoreCode(storeCode);
        BaseResponse<GetOrgTreeListResponse> orgList = storeCenterService.getOrgTreeList(request, LogThreadLocal.getTrackingNo());
        if (orgList != null && ResponseCodeConstant.RESPONSE_SUCCESS_STR.equals(orgList.getCode())) {
            List<GetOrgTreeListResponse.OrgList> orgResponseList = orgList.getData().getOrgList();
            if (CollectionUtils.isEmpty(orgResponseList)){
                return null;
            }
            return orgResponseList.stream().map(org -> org.getOrganizationId()).collect(Collectors.toList());
        }
        return null;
    }

    /**
     *  注意该方法 只是为了兼容 sdk 的bean
     *  sdk的bean太老了,有字段没有赋值,但是不影响 这废弃接口调用
     *  上层接口需要废除,
     * @param activityUpdateStockRequest
     * @return
     */
    private com.freemud.application.sdk.api.promotioncenter.request.promotion.ActivityUpdateStockRequest convertSdkBean(ActivityUpdateStockRequest activityUpdateStockRequest){
        com.freemud.application.sdk.api.promotioncenter.request.promotion.ActivityUpdateStockRequest req = new com.freemud.application.sdk.api.promotioncenter.request.promotion.ActivityUpdateStockRequest();
        BeanUtil.convertBean(activityUpdateStockRequest,req);
        return req;
    }

    /**
     * 围餐更新库存和积分 
     */
    private BaseOrderResponse updateWcStockAndScore(OrderBeanV1 orderBean, List<CreateOrderProductRequest> products, ActivityUpdateStockRequest updateStockRequest,
                                                  List<CreateOrderAccountRequest> accounts, String menuType) {
        //扣减活动库存
        ActivityUpdateStockRequest activityUpdateStockRequest = orderSdkAdapter.convert2ActivityUpdateStockRequest(orderBean, updateStockRequest);
        // update by miaohui 20201030 for 【ID1018638】【C端服务端】活动库存接口调整对接
        // 原逻辑只检测扣减库存不为空时调用，现改为扣减库存不为空或参加活动不为空时调用
        if (activityUpdateStockRequest != null && (CollectionUtils.isNotEmpty(activityUpdateStockRequest.getStock()) || CollectionUtils.isNotEmpty(activityUpdateStockRequest.getActivityList()))) {
            com.freemud.application.sdk.api.promotioncenter.request.promotion.ActivityUpdateStockRequest req = this.convertSdkBean(activityUpdateStockRequest);
            BaseResponse activityResponse = promotionSdkService.subtractStock(req, "");
            ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(),
                    "subtractStock", JSONObject.toJSONString(activityUpdateStockRequest), JSONObject.toJSONString(activityResponse));
            if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, activityResponse.getCode())) {
                //失败异步冲正库存，取消订单
                backOrdersNotifyActivity(orderBean);
                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);
                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);
                return BaseOrderResponse.getErrorBaseOrderResponse(userScoreResponse.getCode(), "积分不足");
            }
        }
        return BaseOrderResponse.getErrorBaseOrderResponse(RESPONSE_SUCCESS_STR, "");
    }


    @Override
    public PayAccessResponse payAccess(ConfirmOrderRequest confirmOrderRequest) {
        PaySuccessReq request = new PaySuccessReq();
        request.setPartnerId(confirmOrderRequest.getPartnerId());
        request.setPayRequestNo(confirmOrderRequest.getPayVoucher());
        request.setCompleteOrderCode(confirmOrderRequest.getCompleteOrderCode());
        request.setOrderCode(confirmOrderRequest.getOrderId());
        request.setMealCodeRule(confirmOrderRequest.getMealCodeRule());
        request.setPickUpGoodsNo(confirmOrderRequest.getPickUpGoodsNo());
        // 引入门店基础服务 查询自动制作完成配置时间，预约单单独超时任务设置
        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));
            if(!StringUtils.isEmpty(confirmOrderRequest.getSpellGroupCode())){
                request.setSpellGroupCode(confirmOrderRequest.getSpellGroupCode());
            }
        }catch (Exception e){
            ErrorLog.printErrorLog("getMemberExtendInfoError",MEMBER_EXTEND_INFO,confirmOrderRequest,e);
        }
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp<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.setPartnerId(confirmOrderRequest.getPartnerId());
        request.setPayRequestNo(confirmOrderRequest.getPayVoucher());
        request.setCompleteOrderCode(confirmOrderRequest.getCompleteOrderCode());
        request.setOrderCode(confirmOrderRequest.getOrderId());
        // 引入门店基础服务 查询自动制作完成配置时间，预约单单独超时任务设置
        if(confirmOrderRequest.getTimeout() == null || confirmOrderRequest.getTimeout() == 0) {
            request.setTimeout(getMCCafePaySuccessTimeout(confirmOrderRequest,request));
        } else {
            request.setTimeout(confirmOrderRequest.getTimeout());
        }

        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);
            if (null == extendInfo.getData()) {
                extInfoDTO.setMemberLevel("");
                extInfoDTO.setPaidMember(false);
            } else {
                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.OrderBaseResp<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.OrderBaseResp<QueryOrderForUserResp> userorderResponse = orderSdkService.queryOrderForUser(request, queryOrdersRequest.getTrackingNo());
        return orderSdkAdapter.convent2QueryOrdersResponse(userorderResponse);
    }

    @Override
    public QueryOrdersResponse queryOrdersNew(QueryOrdersRequest queryOrdersRequest) {
        OrderUserConditionsReq request = orderSdkAdapter.convent2QueryOrdersRequest(queryOrdersRequest);
        request.setInvoiceState(queryOrdersRequest.getInvoiceState());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp<QueryOrderForUserResp> userorderResponse = orderSdkService.queryOrderNew(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.OrderBaseResp<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());
        request.setPartnerId(deleteOrderRequest.getPartnerId());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp 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 (OrderStatusV1.COMPLETE.getCode().equals(orderRefundRequest.getOrderStatusV1())) {
            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.setCancelReason(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,orderRefundRequest.getPartnerId());
        request.setOrderTask(orderTask);
        request.setOperationClient(orderRefundRequest.getOperationClient());
        request.setRefundState(orderRefundRequest.getRefundState());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp response = orderSdkService.createAfterSalesOrder(request, orderRefundRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

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

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

        if((configuration.getTimeTypeOfRefund() != null && configuration.getTimeTypeOfRefund().compareTo(2) == 0 ) || configuration.getTimeTypeOfRefund() == null){// 48小时之后
            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));
        }else if(configuration.getTimeTypeOfRefund() != null && configuration.getTimeTypeOfRefund().compareTo(1) == 0 ){// 指定时间
            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);
            // 判断当前时间是否已经超过门店设置的截至时间
            if(new Date().after(configTime)){
                today = DateUtil.convert2String(DateUtil.addDays(new Date(),1),DateUtil.FORMAT_YMD);
                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);
        } else {
            orderTask = null;
        }

        // fisherman [KA-20210702] 规避版本升级
        if (orderTask != null) {
           avoidVersionUpgrade(orderTask,partnerId);
        }
        return orderTask;
    }

    /**
     *  fisherman 规避版本升级
     *  周二周四晚 23:00开始发版, 服务器会存在宕机, 延迟定时器处理时间
     *  1.校验时间
     *  2.校验 apollo配置商户
     * @param orderTask
     */
    private void avoidVersionUpgrade(OrderTaskReq orderTask, String partnerId) {
        if (Objects.isNull(partnerId)) {
            return;
        }
        // 时间校验
        boolean checkResult = checkDate(orderTask);
        if (checkResult && StringUtils.isNotBlank(avoidVersionUpgradeConfig)) {
            // 读取 是否商户配置
            Map<String,Integer> map = JSON.parseObject(avoidVersionUpgradeConfig, Map.class);
            if (map.containsKey(partnerId)) {
                Integer addHours = map.get(partnerId);
                // 增加 时间
                String processingTime = orderTask.getProcessingTime();
                Date datet = DateUtil.convert2Date(processingTime, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
                Date date = DateUtil.addHours(datet, addHours);
                String resultTime = DateUtil.convert2String(date, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
                orderTask.setProcessingTime(resultTime);

                // 显示时间一起设置
                processingTime = orderTask.getProcessingTime();
                datet = DateUtil.convert2Date(processingTime, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
                date = DateUtil.addHours(datet, addHours);
                resultTime = DateUtil.convert2String(date, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
                orderTask.setTaskTime(resultTime);
            }

        }
    }

    private boolean checkDate(OrderTaskReq orderTask) {
        // 校验 是否 周二 周四
        String processingTime = orderTask.getProcessingTime();
        Calendar cal = Calendar.getInstance();
        Date datet = DateUtil.convert2Date(processingTime, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
        if (datet == null) {
            return false;
        }
        cal.setTime(datet);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        // 增加一个发版开关
        if (CollectionUtils.isNotEmpty(weekDay) && weekDay.size()>0) {
            if (weekDay.contains(w)) {
                // 校验时间 是否是 23:00 之后
                int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
                if (hourOfDay >= 23){
                    // 表示 设置时间为23点之后
                    return true;
                }
            }
        }else {
            if (CommonConstant.weekDay.contains(w)) {
                // 校验时间 是否是 23:00 之后
                int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
                if (hourOfDay >= 23){
                    // 表示 设置时间为23点之后
                   return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取门店自动配置信息
     *
     * @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){
        //合阔pos　商户未接单退款超时时间
        if(confirmOrderRequest.getNotAutomaticTwistTime() != null ){
            return confirmOrderRequest.getNotAutomaticTwistTime();
        }

        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() == OrderTypeV1.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.setPartnerId(orderEdit.getPartnerId());
        request.setExtInfo(orderEdit.getExtInfo());
        request.setOrderClient(OrderClientType.SAAS.getIndex());
        request.setOrderPayItem(orderEdit.getOrderPayItem());
        request.setPayChannel(orderEdit.getPayChannel());
        request.setPayChannelName(orderEdit.getPayChannelName());
        request.setPayChannelType(orderEdit.getPayChannelType());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp 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());
        request.setAfterSalesReason(cancelOrderRequest.getReason());
        //若为4，默认做【创建】+【同意并退款完成】，售后单状态为【完成】
        request.setCreateEvent(cancelOrderRequest.getCreateEvent());
        request.setAfterSerialNo(cancelOrderRequest.getRefundSerialNo());
        request.setOperator(cancelOrderRequest.getOperator());

        // 【华莱士20210510活动】新增加退款方式字段
        if(Objects.nonNull(cancelOrderRequest.getExtInfoReq())){
            request.setExtInfo(JSON.toJSONString(cancelOrderRequest.getExtInfoReq()));
        }

        //为空发起售后单
        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,cancelOrderRequest.getPartnerId());
            request.setOrderTask(orderTask);
        }
        request.setRefundDeliveryAmount(cancelOrderRequest.isRefundDeliveryAmount());
        request.setRefundState(cancelOrderRequest.getRefundState());
        request.setOperationClient(cancelOrderRequest.getOperationClient());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp response = orderSdkService.cancelOrder(request, cancelOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse queryOrderQueueIndex(BaseQueryOrderRequest baseQueryOrderRequest) {
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp<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.OrderBaseResp<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.OrderBaseResp<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.OrderBaseResp 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());
        request.setDispatchType(baseQueryOrderRequest.getDispatchType());
        request.setDispatchTimeout(baseQueryOrderRequest.getDispatchTimeout());
        request.setPartnerId(baseQueryOrderRequest.getPartnerId());
        // 引入门店基础服务 查询自动制作完成配置时间
        if (Objects.nonNull(baseQueryOrderRequest.getPreTimeout())) {
            request.setTimeout(baseQueryOrderRequest.getPreTimeout());
        }else {
            setTimeout(baseQueryOrderRequest,request);
        }
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp 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());
        request.setPartnerId(baseQueryOrderRequest.getPartnerId());
        // 引入门店基础服务 查询自动制作完成配置时间
        setTimeout(baseQueryOrderRequest,request);
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp 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());
        request.setOperationClient(cancelOrderRequest.getOperationClient());
        request.setRefundState(cancelOrderRequest.getRefundState());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp response = orderSdkService.cancelOrder(request, cancelOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse mcCafeOrderReject(CancelOrderRequest cancelOrderRequest, OrderBeanV1 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());
            request.setReqRemark(cancelOrderRequest.getReqRemark());
            request.setAfterSalesReason(cancelOrderRequest.getReason());
            //若为4，默认做【创建】+【同意并退款完成】，售后单状态为【完成】
            request.setCreateEvent(4);
            request.setOperator(cancelOrderRequest.getOperator());
            request.setAfterSerialNo(cancelOrderRequest.getRefundSerialNo());
            request.setOperationClient(cancelOrderRequest.getOperationClient());
            request.setRefundState(cancelOrderRequest.getRefundState());
            com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp response = orderSdkService.cancelOrder(request, cancelOrderRequest.getTrackingNo());
            return orderSdkAdapter.convent2BaseOrderResponse(response);
        } else {
            for(int i=0;i<orderBean.getRefundList().size();i++) {
                if (RefundStatusV1.APPLY_REFUND.getCodeV1().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());
                    request.setAdultRemark(cancelOrderRequest.getReqRemark());
                    com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp response = orderSdkService.adultApproveWithRefundComplete(request, cancelOrderRequest.getTrackingNo());
                    return orderSdkAdapter.convent2BaseOrderResponse(response);
                }
                if (RefundStatusV1.COMPLETE_REFUND.getCodeV1().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.setOperationClient(cancelOrderRequest.getOperationClient());
            orderRefundRequest.setRefundState(cancelOrderRequest.getRefundState());
            orderRefundRequest.setAfterSalesType(cancelOrderRequest.getAfterSalesType().getIndex() == null ? AfterSalesType.PARTNER_REJECT
                    : cancelOrderRequest.getAfterSalesType());
            orderRefundRequest.setReason(cancelOrderRequest.getReason());
            orderRefundRequest.setRemark(cancelOrderRequest.getReqRemark());
            orderRefundRequest.setOperator(cancelOrderRequest.getOperator());
            orderRefundRequest.setOrderStatusV1(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());
        request.setPartnerId(baseQueryOrderRequest.getPartnerId());
        Boolean isTakeOut = false;
        Integer timeOut   = 0;
        Integer takeOutTimeOut = (null==baseQueryOrderRequest.getTimeout() || baseQueryOrderRequest.getTimeout()==0) ? 180 : baseQueryOrderRequest.getTimeout();
        //是saas 外卖单 且是三方配送    调用门店服务查询外卖单自动完成时间
        if ((OrderType.GENERAL_EXPRESS.equals(baseQueryOrderRequest.getOrderType())
                || OrderType.RESERVED_EXPRESS.equals(baseQueryOrderRequest.getOrderType()))
                && StoreDeliveryMethod.THIRD.getCode().equals(baseQueryOrderRequest.getDeliveryType())) {
            isTakeOut = true;
        }
        StoreResponse.Configuration configuration = getStoreAutoConfiguration(baseQueryOrderRequest.getPartnerId(), baseQueryOrderRequest.getShopId(), baseQueryOrderRequest.getTrackingNo());
        if (configuration != null ) {
            //deliveryFinishedAfterMinute:自建外卖订单，商家自配送xx分钟后，订单状态更改为【已完成】;
            //appointAutoDeliveryTakeOrderWorkflowFinishTime: 预约自建外卖制作完成后自动流程时间 1:2小时;2:1小时;3:30分钟;4:15分钟;5:10分钟;6:5分钟;
            if(configuration.getDeliveryFinishedAfterMinute() == null
                    || configuration.getAppointAutoDeliveryTakeOrderWorkflowFinishTime() == null ){
                timeOut = isTakeOut ? takeOutTimeOut : 120;
            }
            if(configuration.getDeliveryFinishedAfterMinute()!=null && configuration.getDeliveryFinishedAfterMinute()>0){
                timeOut = isTakeOut ? takeOutTimeOut
                                    //: AutoOrderConfigTime.getTime(configuration.getDeliveryFinishedAfterMinute().toString());
                                    : configuration.getDeliveryFinishedAfterMinute();
                //request.setTimeout(timeOut);
            }
            if(StringUtils.isNotEmpty(baseQueryOrderRequest.getExpectTime()) && StringUtils.isNotEmpty(configuration.getAppointAutoDeliveryTakeOrderWorkflowFinishTime())){
                timeOut = isTakeOut ? takeOutTimeOut
                                    : AutoOrderConfigTime.getTime(configuration.getAppointAutoDeliveryTakeOrderWorkflowFinishTime());
                //request.setTimeout(AutoOrderConfigTime.getTime(configuration.getAppointAutoDeliveryTakeOrderWorkflowFinishTime()));
            }

        }else {
            timeOut = isTakeOut ? takeOutTimeOut : 120;
        }
        request.setTimeout(timeOut);

        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp 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.setPartnerId(baseQueryOrderRequest.getPartnerId());
        request.setRemark("已完成");
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp 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(Integer.parseInt(baseQueryOrderRequest.getOrderClient()));
        request.setAfterSalesCode(baseQueryOrderRequest.getAfterSalesCode());
        request.setAfterSerialNo(baseQueryOrderRequest.getRefundSerialNo());
        request.setAdultRemark(baseQueryOrderRequest.getReason());
        request.setOperator(baseQueryOrderRequest.getOperator());
        request.setOperationClient(baseQueryOrderRequest.getOperationClient());
        request.setRefundState(baseQueryOrderRequest.getRefundState());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp 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.OrderBaseResp 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(Integer.parseInt(baseQueryOrderRequest.getOrderClient()));
        request.setAfterSalesCode(baseQueryOrderRequest.getAfterSalesCode());
        request.setAfterSerialNo(baseQueryOrderRequest.getRefundSerialNo());
        request.setAdultRemark(baseQueryOrderRequest.getReason());
        request.setOperator(baseQueryOrderRequest.getOperator());
        request.setOperationClient(baseQueryOrderRequest.getOperationClient());
        request.setRefundState(baseQueryOrderRequest.getRefundState());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp response = orderSdkService.adultApproveWithGoodsReturned(request, baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse orderRefundReject(CancelOrderRequest cancelOrderRequest) {
        AfterSalesOperateReq request = new AfterSalesOperateReq();
        request.setOrderClient(cancelOrderRequest.getOrderClient());
        request.setPartnerId(cancelOrderRequest.getPartnerId());
        request.setOrderCode(cancelOrderRequest.getOrderId());
        request.setAfterSalesCode(cancelOrderRequest.getAfterSalesCode());
        request.setAdultRemark(cancelOrderRequest.getReason());
        request.setOperator(cancelOrderRequest.getOperator());
        if(Objects.equals(NewOrderStatus.ACCEPTED.getIndex(), cancelOrderRequest.getStatusV2())){
            StoreResponse.Configuration configuration = getStoreAutoConfiguration(cancelOrderRequest.getPartnerId(), cancelOrderRequest.getStoreId(), cancelOrderRequest.getTrackingNo());
            if (configuration != null) {
                if(StringUtils.isNotEmpty(configuration.getAutoSelfmentionMakerWorkflowFinishTime())){
                    request.setTimeout(AutoOrderConfigTime.getTime(configuration.getAutoSelfmentionMakerWorkflowFinishTime()));
                }
                if(StringUtils.isNotEmpty(cancelOrderRequest.getExpectTime()) && StringUtils.isNotEmpty(configuration.getAppointAutoSelfmentionMakerWorkflowFinishTime())){
                    request.setTimeout(AutoOrderConfigTime.getTime(configuration.getAppointAutoSelfmentionMakerWorkflowFinishTime()));
                }
            } else {
                request.setTimeout(120);
            }
        }
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp 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());
        request.setPartnerId(baseQueryOrderRequest.getPartnerId());
        // 调用门店服务查询自动完成配置信息
        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);
        }
        // 合阔pos商户订单不自动扭转
        if(baseQueryOrderRequest.getNotAutomaticTwist() != null && baseQueryOrderRequest.getNotAutomaticTwist()){
            request.setTimeout(0);
        }
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp 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.OrderBaseResp 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.OrderBaseResp<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.OrderBaseResp<StoreOrderStatisticResp> response = orderSdkService.queryStatisticStoreOrder(storeOrderStatisticReq, request.getTrackingNo());
        return orderSdkAdapter.convent2GetStatisticStoreOrderReportResponse(response);
    }

    @Override
    public OrderBaseResponse updateDeliveryInfoById(UpdateDeliveryInfoByIdRequest request) {
        OrderExpressReq expressReq = new OrderExpressReq();
        expressReq.setPartnerId(request.getPartnerId());
        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());
        expressReq.setExceptionDesc(request.getExceptionDesc());
        expressReq.setExceptionId(request.getExceptionId());
        expressReq.setOpType(request.getOpType());
        if(null !=request.getOrderClient() && com.google.common.base.Objects.equal(BizTypeEnum.MALL.getBizType(), request.getBizType()) && 0 == request.getOpType()){
            OrderTaskReq orderTask = new OrderTaskReq();
            orderTask.setTaskType(5);
            orderTask.setTimeout(1);
            //1000*60*60*24*15 毫秒（15天）
            long timeout = 1296000000;
//            long timeout = 3600000;
            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));
            //处理时间，当前时间加15天减1分钟
            String processingTime = DateUtil.convert2String(processingDate, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
            orderTask.setProcessingTime(processingTime);
            expressReq.setOrderTaskReq(orderTask);
            expressReq.setAutoReceiveTime(processingTime);
            expressReq.setOrderStatus(NewOrderStatus.DELIVERING.getIndex());
        }
        //【ID1031049】 订单接受配送分配骑手状态回调
        expressReq.setEstimateArriveTime(request.getEstimateArriveTime());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp 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.OrderBaseResp<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.OrderBaseResp<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.OrderBaseResp<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.OrderBaseResp 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.OrderBaseResp<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<OrderBeanV1> orderBeanList = new ArrayList<>();
            for (OrderInfoReqs orderInfoReqs : baseResponse.getResult()) {
                OrderBeanV1 orderBean = orderCenterSdkAdapter.convent2NEWOrderInfo(orderInfoReqs);
                orderBeanList.add(orderBean);
            }
            dataBean.setOrders(orderBeanList);
        }
        response.setData(dataBean);
        response.setErrcode(baseResponse.getCode() != null ? Integer.parseInt(baseResponse.getCode()) : 501);
        response.setErrmsg(baseResponse.getMessage());
        return response;
    }

    @Override
    public QueryRelatedOrderByCodeResp queryRelatedOrderByCode(QueryRelatedOrderByCodeRequest request) {
        QueryRelatedOrderByCodeReq queryRelatedOrderByCodeReq = orderSdkAdapter.convert2QueryRelatedOrderByCodeRequest(request);
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp<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.OrderBaseResp 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());
        //7,"运单异常"
        updateDeliveryInfoByIdRequest.setOrderSubState(7);
        updateAbnormalStateRequest.setPartnerId(request.getPartnerId());
        return updateDeliveryInfoById(updateDeliveryInfoByIdRequest);
    }

//    /**
//     * 冲正商品库存，活动库存,商品库存，订单取消，退款
//     *
//     * @param orderBean 订单信息
//     * @param transType TransTypeEnum 冲正类型
//     */
//    public void backOrdersNotifyActivity(OrderBeanV1 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(OrderBeanV1 orderBean) {
        if (null == orderBean) {
            return;
        }
        String oid = orderBean.getOid();
        Integer statusV1 = orderBean.getStatus();
        if (StringUtils.isEmpty(oid)) {
            return;
        }
        AssortOrderLogUtil.info("backOrdersStatusChange", oid, String.valueOf(statusV1));
        OrderStatusChangeRequestDto requestDto = new OrderStatusChangeRequestDto();
        requestDto.setOid(oid);
        requestDto.setOrderStatus(statusV1);
        requestDto.setOrderStatusV2(orderBean.getStatusV2());
        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, OrderBeanV1 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.OrderBaseResp<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.OrderBaseResp<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.OrderBaseResp<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<ProductBeanV1> 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(ProductBeanV1 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, ProductBeanV1> 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<ProductBeanV1> 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 -> {
                                ProductBeanV1 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.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)){
                backOrdersNotifyActivity(queryOrderByIdResponse.getData());
            }
        }
        /**
         * 加菜或者删菜的时候通知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(), PayStatusEnum.NOT_PAY.getCode())) {
                    OrderBeanV1 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.OrderBaseResp<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.OrderBaseResp 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));
    }

    @Override
    public QueryPartnerRefundCountResponse queryRefundCount(QueryStoreRefundCountRequest request) {

        QueryPartnerRefundCountResponse queryPartnerRefundCountResponse = new QueryPartnerRefundCountResponse();

        String trackingNo = LogThreadLocal.getTrackingNo();

        // 分页查询es的服务-待处理的退款单
        QueryAfterSalesOrderConditionsReq orderQueryRequestDto = new QueryAfterSalesOrderConditionsReq();
        orderQueryRequestDto.setPartnerId(request.getPartnerId());
        orderQueryRequestDto.setStoreIds(request.getStoreIds());
        // 订单的创建时间使用传过来的时间前推2天
        orderQueryRequestDto.setStartTimestamp(request.getStartTimestamp() - 172800);
        orderQueryRequestDto.setEndTimestamp(request.getEndTimestamp());
        orderQueryRequestDto.setStartAfterCreateTimestamp(request.getStartTimestamp());
        orderQueryRequestDto.setEndAfterCreateTimestamp(request.getEndTimestamp());
        List<Byte> afterSalesStatusList = new ArrayList<>();
        afterSalesStatusList.add(new Byte("1"));
        orderQueryRequestDto.setAfterSalesStatusList(afterSalesStatusList);
        orderQueryRequestDto.setPageNum(null); // pageNum 不传表示滚动查询
        orderQueryRequestDto.setPageSize(500);
        AfterSalesListResp pageResponse = null;
        try {
            pageResponse = orderDownLoadSdkService.queryAfterSalesOrderConditions(orderQueryRequestDto, trackingNo);
        } catch (Exception e) {
            ErrorLog.printErrorLog("查询ES服务商户门店退款订单数量ERR", InterfaceAddressConstant.QUERY_AFT_SALE_ORDER_LIST,request,e);
            queryPartnerRefundCountResponse.setErrcode(pageResponse.getCode());
            queryPartnerRefundCountResponse.setErrmsg(pageResponse.getMessage());
            return queryPartnerRefundCountResponse;
        }

        if (null == pageResponse || !Objects.equals(RESPONSE_SUCCESS_STR, pageResponse.getCode())) {
            AssortOrderLogUtil.info("查询ES服务商户门店退款订单数量ERR", pageResponse.getCode(), pageResponse.getMessage());
            queryPartnerRefundCountResponse.setErrcode(pageResponse.getCode());
            queryPartnerRefundCountResponse.setErrmsg(pageResponse.getMessage());
            return queryPartnerRefundCountResponse;
        }
        List<Map<String,Long>> storeCountList = new ArrayList<>();
        if(CollectionUtils.isEmpty(pageResponse.getResult())){
            AssortOrderLogUtil.info("未查询到ES服务商户门店退款订单数量");
            queryPartnerRefundCountResponse.setErrcode(pageResponse.getCode());
            queryPartnerRefundCountResponse.setErrmsg(pageResponse.getMessage());
            return buildQueryPartnerRefundCountResponse(request,storeCountList);
        }

        // 统计门店退款单数量
        statisticsCount(pageResponse.getResult(),storeCountList);

        QueryOrderByScrollRequest scrollRequest = new QueryOrderByScrollRequest();
        scrollRequest.setScrollId(pageResponse.getScrollId());
        scrollRequest.setVer(1);
        try {
            while (true) {
                BaseDownLoadResponse<List<AfterSalesOrderResp>> scrollResponse = orderDownLoadSdkService.queryAfterSalesOrderByScrollId(scrollRequest, LogThreadLocal.getTrackingNo());
                if (!Objects.equals(RESPONSE_SUCCESS_STR, scrollResponse.getCode())) {
                    break;
                }
                if (CollectionUtils.isEmpty(scrollResponse.getResult())) {
                    break;
                }
                statisticsCount(pageResponse.getResult(),storeCountList);
                scrollRequest.setScrollId( scrollResponse.getScrollId());
            }
        } catch (Exception e) {
            ErrorLog.printErrorLog("查询ES服务商户门店退款订单数量ERR", InterfaceAddressConstant.QUERY_AFT_SALE_ORDER_LIST,request,e);
            queryPartnerRefundCountResponse = new QueryPartnerRefundCountResponse();
            queryPartnerRefundCountResponse.setErrcode(pageResponse.getCode());
            queryPartnerRefundCountResponse.setErrmsg(pageResponse.getMessage());
            return queryPartnerRefundCountResponse;
        }

        return buildQueryPartnerRefundCountResponse(request,storeCountList);
    }

    /**
     * 统计每个门店的退款订单数量
     * @param afterSalesOrderResp
     * @param storeCountList
     */
    private void statisticsCount(List<AfterSalesOrderResp> afterSalesOrderResp,List<Map<String,Long>> storeCountList){
        Map<String,Long>  coutnMap =  afterSalesOrderResp.stream().collect(Collectors.groupingBy(AfterSalesOrderResp::getStoreId,Collectors.counting()));
        storeCountList.add(coutnMap);
    }

    /**
     * 求和每个门店的退款订单数量
     * @param storeId
     * @param storeCountList
     */
    private Long sumCount(String storeId,List<Map<String,Long>> storeCountList){
        Long sumCount = 0L;
        for(Map<String,Long> map :storeCountList){
            Long count = map.get(storeId);
            if(null != count){
                sumCount +=count;
            }
        }
        return sumCount;
    }

    /**
     * 构建查询商户退款数量返回值
     * @param request
     * @param storeCountList
     */
    private QueryPartnerRefundCountResponse buildQueryPartnerRefundCountResponse(QueryStoreRefundCountRequest request,List<Map<String,Long>> storeCountList){
        QueryPartnerRefundCountResponse queryPartnerRefundCountResponse = new QueryPartnerRefundCountResponse();
        QueryPartnerRefundCountResponse.PartnerRefundCount data = new QueryPartnerRefundCountResponse.PartnerRefundCount();
        data.setPartnerId(request.getPartnerId());
        List<QueryPartnerRefundCountResponse.StoreRefundCount> storeRefundCount = new ArrayList<>();
        for(String storeId : request.getStoreIds()){
            QueryPartnerRefundCountResponse.StoreRefundCount store = new QueryPartnerRefundCountResponse.StoreRefundCount();
            store.setStoreId(storeId);
            store.setCount(sumCount(storeId,storeCountList));
            storeRefundCount.add(store);
        }

        data.setStoreRefundCount(storeRefundCount);
        queryPartnerRefundCountResponse.setData(data);
        queryPartnerRefundCountResponse.setErrcode(RESPONSE_SUCCESS_STR);
        queryPartnerRefundCountResponse.setErrmsg("");
        return queryPartnerRefundCountResponse;
    }

    //saas 实时外卖  预约外卖都是 按3个小时流转
    private void setTimeout(BaseQueryOrderRequest baseQueryOrderRequest,POSOrderOperationBaseReq request){
        //合阔pos　商户订单状态不自动扭转
        if(baseQueryOrderRequest.getNotAutomaticTwist() != null && baseQueryOrderRequest.getNotAutomaticTwist()){
            return ;
        }
        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;
        Boolean isTakeOut = false;
        Integer takeOutTimeOut = (null==baseQueryOrderRequest.getTimeout() || baseQueryOrderRequest.getTimeout()==0) ? 180 : baseQueryOrderRequest.getTimeout();
        //是saas 外卖单 且是三方配送
        if ((OrderType.GENERAL_EXPRESS.equals(baseQueryOrderRequest.getOrderType())
                || OrderType.RESERVED_EXPRESS.equals(baseQueryOrderRequest.getOrderType()))
                && StoreDeliveryMethod.THIRD.getCode().equals(baseQueryOrderRequest.getDeliveryType())) {
            isTakeOut = true;
        }
        //自配送外卖单
        if (configuration != null) {
            //外卖单  店外快递实时-3常规外送   店外快递预约-4预约外送
            // 重要的事情重复三遍 saas 实时外卖  预约外卖都是 按3个小时流转
            if (OrderType.GENERAL_EXPRESS.equals(baseQueryOrderRequest.getOrderType()) || OrderType.RESERVED_EXPRESS.equals(baseQueryOrderRequest.getOrderType())) {
                //deliveryProcessingAfterMinute:自建外卖订单-实时单，商家自配送，门店接单xx分钟后，订单状态变更为配送中;
                //deliveryProcessingBeforeMinute: 自建外卖订单-预约单，商家自配送，预约商家前xx分钟，订单更改为配送中
                if(configuration.getDeliveryProcessingAfterMinute() == null
                        || configuration.getDeliveryProcessingBeforeMinute() == null ){
                    timeout = isTakeOut ? takeOutTimeOut : 120;
                }
                //自配送外卖单接单后自动流程时间
                if (configuration.getDeliveryProcessingAfterMinute()!=null && configuration.getDeliveryProcessingAfterMinute()>0) {
                    timeout = StoreDeliveryMethod.SELF.getCode().equals(baseQueryOrderRequest.getDeliveryType())
                            //? AutoOrderConfigTime.getTime(configuration.getDeliveryProcessingAfterMinute().toString())
                            ? configuration.getDeliveryProcessingAfterMinute()
                            : takeOutTimeOut;
                }
                //预约单
                if(OrderType.RESERVED_EXPRESS.equals(baseQueryOrderRequest.getOrderType())
                     && configuration.getDeliveryProcessingBeforeMinute() != null   &&  configuration.getDeliveryProcessingBeforeMinute()>0){
                    timeout = StoreDeliveryMethod.SELF.getCode().equals(baseQueryOrderRequest.getDeliveryType())
                              //? AutoOrderConfigTime.getTime(configuration.getDeliveryProcessingBeforeMinute().toString())
                              ? configuration.getDeliveryProcessingBeforeMinute()
                              : takeOutTimeOut;
                }
            }
            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 = isTakeOut ? takeOutTimeOut : 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;
    }

    @Override
    public QueryLineUpResponse queryLineUpOrder(QueryLineUpOrderReq queryLineUpOrderReq) {
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp<List<String>> response = orderSdkService.queryLineUpOrder(queryLineUpOrderReq, LogThreadLocal.getTrackingNo());
        return orderSdkAdapter.convent2QueryLineUpResponse(response);
    }

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

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


    @Override
    public BaseOrderResponse mallOrderRefundReturn(BaseQueryOrderRequest baseQueryOrderRequest) {
        AfterSalesExpressOperateReq request = new AfterSalesExpressOperateReq();
        request.setOrderCode(baseQueryOrderRequest.getOrderId());
        request.setPartnerId(baseQueryOrderRequest.getPartnerId());
//        request.setOrderClient(OrderClientType.SAASMALL.getIndex());
        request.setAfterSalesCode(baseQueryOrderRequest.getAfterSalesCode());
        request.setAfterSerialNo(baseQueryOrderRequest.getRefundSerialNo());
        request.setAdultRemark(baseQueryOrderRequest.getReason());
        request.setOperator(baseQueryOrderRequest.getOperator());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp response = orderSdkService.adultGoodsReturned(request, baseQueryOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

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



    @Override
    public BaseOrderResponse editAfterSalesExpress(EditAfterSalesExpressRequest afterSalesExpressRequest){
        AfterSalesExpressOperateReq request = new AfterSalesExpressOperateReq();
        request.setOrderClient(afterSalesExpressRequest.getOrderClient());
        request.setPartnerId(afterSalesExpressRequest.getPartnerId());
        request.setOrderCode(afterSalesExpressRequest.getOrderId());
        request.setAfterSalesCode(afterSalesExpressRequest.getAfterSalesCode());
        request.setAdultRemark("用户填写快递单号");
        request.setOperator(afterSalesExpressRequest.getOperator());
        request.setExpressChannelName(afterSalesExpressRequest.getExpressChannelName());
        request.setExpressNo(afterSalesExpressRequest.getExpressNo());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp response = orderSdkService.adultGoodsReturned(request, afterSalesExpressRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public BaseOrderResponse mallOrderRefundReject(CancelOrderRequest cancelOrderRequest) {
        AfterSalesOperateReq request = new AfterSalesOperateReq();
//        request.setOrderClient(OrderClientType.SAASMALL.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.OrderBaseResp response = orderSdkService.adultReject(request, cancelOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public OrderStateInfoResp queryOrderStateInfo(String orderCode, String partnerId, Byte orderClient, String trackNo) {
        BaseQueryOrderRequest request = new BaseQueryOrderRequest();
        request.setOrderId(orderCode);
        request.setPartnerId(partnerId);
        if (Objects.nonNull(orderClient) && !Objects.equals(orderClient,0) ){
            request.setOrderClient(orderClient.toString());
        }
        QueryByCodeResponse orderInfo = orderSdkService.getOrderInfo(request.getOrderClient(), request.getOrderId(),
                request.getThirdOrderCode(), 1, request.getTrackingNo());
        return orderSdkAdapter.convent2OrderStateInfoResp(orderInfo);
    }

    /**
     * 订单POS拒单 POS
     */
    @Override
    public BaseOrderResponse mallOrderReject(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.SAASMALL.getIndex());
        request.setCancelReason(cancelOrderRequest.getReason());
        //若为4，默认做【创建】+【同意并退款完成】，售后单状态为【完成】
        request.setCreateEvent(4);
        request.setOperator(cancelOrderRequest.getOperator());
        request.setAfterSerialNo(cancelOrderRequest.getRefundSerialNo());
        request.setOperationClient(cancelOrderRequest.getOperationClient());
        request.setRefundState(cancelOrderRequest.getRefundState());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp response = orderSdkService.cancelOrder(request, cancelOrderRequest.getTrackingNo());
        return orderSdkAdapter.convent2BaseOrderResponse(response);
    }

    @Override
    public AfterSalesListResp queryAfterSalesListFromDb(QueryAfterSalesOrderConditionsReq queryRequest, String trackNo) {
        return orderDownLoadSdkService.queryAfterSalesOrderFromDb(queryRequest, trackNo);
    }

    @Override
    public QueryOrdersResponse getOrderListByDb(QueryOrdersByConditionsRequest queryOrdersByConditionsRequest) {
        OrderConditionsReq request = orderSdkAdapter.convent2QueryOrdersByConditionsRequest(queryOrdersByConditionsRequest);
        BaseDownLoadResponse<List<OrderInfoReqs>> baseDownLoadResponse = orderDownLoadSdkService.queryOrderByDayFromDb(request, "");

        return orderSdkAdapter.convent2OrdersResponseByES(baseDownLoadResponse);
    }

    /**
     *  查询订单信息 基于基础服务
     * @param request
     * @return
     */
    @Override
    public QueryByCodeResponse queryOrderByIdV2(BaseQueryOrderRequest request) {
        QueryByCodeResponse orderInfo = orderSdkService.getOrderInfo(request.getOrderClient(), request.getOrderId(),
                request.getThirdOrderCode(), request.getWithOperationHistory(), request.getTrackingNo());
        return orderInfo;
    }
}
