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

import cn.freemud.base.constant.Version;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freemud.application.sdk.api.couponcenter.offline.domain.ProductRedeemVO;
import com.freemud.application.sdk.api.couponcenter.offline.domain.TransactionVO;
import com.freemud.application.sdk.api.couponcenter.offline.request.CouponLockRequest;
import com.freemud.application.sdk.api.couponcenter.offline.request.CouponRequest;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.membercenter.request.UserScoreRequest;
import com.freemud.application.sdk.api.ordercenter.adapter.OrderCenterSdkAdapter;
import com.freemud.application.sdk.api.ordercenter.entities.v1.*;
import com.freemud.application.sdk.api.ordercenter.enums.*;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.OrderSourceV1;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.OrderTypeV1;
import com.freemud.application.sdk.api.ordercenter.request.*;
import com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest;
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.*;
import com.freemud.application.sdk.api.stockapi.domain.ProductStocksVO;
import com.freemud.application.sdk.api.stockapi.request.UpdateStocksRequest;
import com.freemud.application.sdk.api.util.DateUtil;
import com.freemud.sdk.api.assortment.order.constant.CommonConstant;
import com.freemud.sdk.api.assortment.order.domain.OrderStatesVO;
import com.freemud.sdk.api.assortment.order.domain.ResponseCodeConstant;
import com.freemud.sdk.api.assortment.order.entities.other.OtherParamDTO;
import com.freemud.sdk.api.assortment.order.entities.promption.ActivityUpdateStockRequest;
import com.freemud.sdk.api.assortment.order.entities.promption.SubtractStockVO;
import com.freemud.sdk.api.assortment.order.enums.*;
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.request.stock.UpdateProductStockRequestDto;
import com.freemud.sdk.api.assortment.order.response.order.*;
import com.freemud.sdk.api.assortment.order.util.AssortOrderLogUtil;
import com.freemud.sdk.api.assortment.order.util.ClassUtils;
import com.freemud.sdk.api.assortment.order.util.WeightUtils;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class OrderSdkAdapter {

    private static MapperFacade mapper = new DefaultMapperFactory.Builder().build().getMapperFacade();


    private static final int STACK_SUB = 1;

    @Autowired
    private OrderCenterSdkAdapter orderCenterSdkAdapter;

    /**
     * 接单request
     *
     * @param operator
     * @param orderBean
     * @param otherParamDTO
     * @return
     */
    public BaseQueryOrderRequest getOrderConfirmRequest(String operator, OrderBeanV1 orderBean, OtherParamDTO otherParamDTO) {
        BaseQueryOrderRequest orderRequest = new BaseQueryOrderRequest();
        orderRequest.setOrderId(orderBean.getOid());
        orderRequest.setShopId(orderBean.getShopId());
        orderRequest.setHasSelfDelivery(true);
        orderRequest.setPartnerId(orderBean.getCompanyId());
//        orderRequest.setOrderType(getNewOrderTypeEnum(orderBean.getType(), orderBean.getGmtExpect()));
        orderRequest.setOrderType(OrderType.getOrderType(orderBean.getNewOrderType()));
        if (orderBean.getGmtExpect() != null && orderBean.getGmtExpect() != 0) {
            orderRequest.setExpectTime(cn.freemud.base.util.DateUtil.convert2String(new Date(orderBean.getGmtExpect()), cn.freemud.base.util.DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        }
        orderRequest.setOperator(operator);
        orderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());

        //配送信息为空，自配送
        if (orderBean.getAddInfo() == null || orderBean.getAddInfo().getDeliveryType() == null) {
            orderRequest.setDeliveryType(StoreDeliveryMethod.SELF.getCode());
        } else {
            orderRequest.setDeliveryType(orderBean.getAddInfo().getDeliveryType());
        }
        if (Objects.nonNull(otherParamDTO)) {
            orderRequest.setDispatchType(otherParamDTO.getDispatchType());
            orderRequest.setDispatchTimeout(otherParamDTO.getDispatchTimeout());
        }
        return orderRequest;
    }

    /**
     * 配送request
     * @param operator
     * @param orderBean
     * @return
     */
//    public BaseQueryOrderRequest getOrderDeliveryRequest(String operator, QueryOrdersResponse.DataBean.OrderBean orderBean){
//        BaseQueryOrderRequest orderDeliveryRequest = getOrderConfirmRequest(operator, orderBean);
//        if (orderBean.getType() == 1) {
//            orderDeliveryRequest.setOrderType(com.freemud.application.sdk.api.ordercenter.enums.OrderType.GENERAL_EXPRESS);
//        } else {
//            orderDeliveryRequest.setOrderType(com.freemud.application.sdk.api.ordercenter.enums.OrderType.GENERAL_SELF_PICKUP);
//        }
//        return orderDeliveryRequest;
//    }

    /**
     * 拒单request
     *
     * @param operator
     * @param reason
     * @param refundStatus
     * @param refundId
     * @param orderBean
     * @return
     */
    public CancelOrderRequest getCancelOrderRequest(String operator, String reason, PayRefundStatus refundStatus, String refundId, OrderBeanV1 orderBean) {
        CancelOrderRequest var1 = new CancelOrderRequest();
        var1.setPartnerId(orderBean.getCompanyId());
        var1.setOrderId(orderBean.getOid());
        var1.setReason(reason);
        if (Objects.equals(orderBean.getStatusV2(), NewOrderStatus.PLACE_AN_ORDER.getIndex())) {
            var1.setAfterSalesType(AfterSalesType.PARTNER_REJECT);
        } else {
            var1.setAfterSalesType(AfterSalesType.SYSTEM_CANCEL);
        }
        var1.setTrackingNo(UUID.randomUUID().toString());
        var1.setRefundSerialNo(refundId);
        // 退款状态为退款中：event为5，默认做【创建】+【同意并退货完成】，售后单状态【已退货】
        //退款状态为退款完成：event为4，默认做【创建】+【同意并退款完成】，售后单状态为【完成】
        var1.setCreateEvent(PayRefundStatus.SUCCESS.equals(refundStatus) ? AfterSalesCreateEvent.REFUND_COMPLETE.getCreateEvent() : AfterSalesCreateEvent.RETURN_COMPLETE.getCreateEvent());
        var1.setRefundState(PayRefundStatus.SUCCESS.equals(refundStatus) ? 4 : 2);
        var1.setOperator(operator);
        var1.setReason(reason);
        var1.setOrderClient(StringUtils.isEmpty(orderBean.getOrderClient()) ? OrderClientType.SAAS.getIndex() : Integer.valueOf(orderBean.getOrderClient()));
        return var1;
    }

    public CancelOrderRequest getRejectRefundRequest(String operator, String reason, OrderBeanV1 orderBean) {
        CancelOrderRequest var1 = new CancelOrderRequest();
        var1.setOrderId(orderBean.getOid());
        var1.setReason(reason);
        var1.setOrderClient(Integer.parseInt(orderBean.getOrderClient()));
        var1.setPartnerId(orderBean.getCompanyId());
        var1.setStoreId(orderBean.getShopId());
        if (orderBean.getGmtExpect() != null && orderBean.getGmtExpect() != 0) {
            var1.setExpectTime(cn.freemud.base.util.DateUtil.convert2String(new Date(orderBean.getGmtExpect()), cn.freemud.base.util.DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        }
        if (orderBean.getRefundList() != null && orderBean.getRefundList().size() != 0) {
            //新订单服务需要售后单code
            var1.setAfterSalesCode(orderBean.getRefundList().get(orderBean.getRefundList().size() - 1).getRid());
        }
        var1.setStatusV2(orderBean.getStatusV2());
        var1.setOperator(operator);
        return var1;
    }

    public CancelOrderRequest convent2CancelOrderRequest(String orderId, String partnerId, AfterSalesType afterSalesType,
                                                         String reason, String trackingNo, Long refund_id,String orderClient) {
        CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
        cancelOrderRequest.setOrderId(orderId);
        cancelOrderRequest.setPartnerId(partnerId);
        cancelOrderRequest.setAfterSalesType(afterSalesType);
        cancelOrderRequest.setReason(reason);
        cancelOrderRequest.setTrackingNo(trackingNo);
        cancelOrderRequest.setOperator("admin");
        //若为4，默认做【创建】+【同意并退款完成】，售后单状态为【完成】
        cancelOrderRequest.setCreateEvent(4);
        cancelOrderRequest.setRefundState(AfterSalesRefunStateEnum.STATE_1.getIndex());
        cancelOrderRequest.setOperationClient(OperationClientEnum.STATE_6.getIndex());
        cancelOrderRequest.setOrderClient(StringUtils.isEmpty(orderClient) ? OrderClientType.SAAS.getIndex() : Integer.valueOf(orderClient));
        if (refund_id != null) {
            cancelOrderRequest.setRefundSerialNo(refund_id.toString());
        }
        return cancelOrderRequest;
    }

    public BaseQueryOrderRequest getRefundAgreeRequest(String refund_id, String reason, String operator, OrderBeanV1 orderBean) {
        BaseQueryOrderRequest var1 = new BaseQueryOrderRequest();
        var1.setPartnerId(orderBean.getCompanyId());
        var1.setOrderId(orderBean.getOid());
        var1.setTrackingNo(LogThreadLocal.getTrackingNo());
        var1.setRefundSerialNo(refund_id);
        var1.setReason(reason);
        var1.setOperator(operator);
        var1.setOrderClient(orderBean.getOrderClient());
        if (orderBean.getRefundList() != null && orderBean.getRefundList().size() != 0) {
            //新订单服务需要售后单code
//            var1.setAfterSalesCode(orderBean.getRefundList().get(orderBean.getRefundList().size() - 1).getRid());
            // fisherman 按时间排序 拿最后一个
            List<RefundBeanV1> refundList = orderBean.getRefundList();
            Collections.sort(refundList, new Comparator<RefundBeanV1>() {
                @Override
                public int compare(RefundBeanV1 o1, RefundBeanV1 o2) {
                    Long aLong = Long.valueOf(o1.getCreateTime());
                    Long bLong = Long.valueOf(o2.getCreateTime());
                    if (bLong > aLong) {
                        return 1;
                    } else if (bLong < aLong) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            var1.setAfterSalesCode(refundList.get(0).getRid());

        }
        return var1;
    }

    /**
     * 老订单服务创建订单对象 转换成 新订单服务请求对象 fisherman
     */
    public com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest convent2NEWCreateOrderRequest(BaseCreateOrderRequest requestVO) {
        com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest request = new com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest();
        request.setPartnerId(requestVO.getCompanyId());
        request.setStoreId(requestVO.getShopId());
        request.setStoreUnifyId(requestVO.getStoreUnifyId());
        //1:线上支付 2:线下支付
        request.setPayType(1);
        request.setUserId(requestVO.getUserId());
        request.setUserName(requestVO.getUserName());
        request.setStoreName(requestVO.getShopName());
        request.setPayTime(requestVO.getPayTime());
        request.setThirdStoreId(requestVO.getThirdShopId());
        request.setThirdOrderCode(requestVO.getThirdOrderCode());
        request.setPayChannelType(requestVO.getPayChannelType());
//        if (requestVO.getOrderStatus() != null) {
//            request.setOrderState(getNewOrderStatus(requestVO.getOrderStatus().getCode()));
//        }
//        if (requestVO.getPayStatus() != null) {
//            request.setPayState(requestVO.getPayStatus().getCode());
//        }
        if (requestVO.getPayChannel() != null) {
            request.setPayChannel(requestVO.getPayChannel());
        }
        if (requestVO.getPayChannelName() != null) {
            request.setPayChannelName(requestVO.getPayChannelName());
        }
        if (requestVO.getGmtExpect() != null && requestVO.getGmtExpect() != 0) {
            request.setExpectTime(new Date(requestVO.getGmtExpect()));
        }
        //订单原始金额，单位分
        Long originalAmount = 0L;
        //用户在界面上看到的支付金额
        request.setSettlementAmount(requestVO.getAmount());
        //实际支付现金金额，扣除支付自生优惠，单位分
        request.setActualPayAmount(requestVO.getAmount());
        request.setOrderClient(requestVO.getOrderClient().getIndex());
//        if (requestVO.getOrderClient() != null) {
//            request.setOrderClient(requestVO.getOrderClient().getIndex());
//        } else {
//            request.setOrderClient(StringUtils.isEmpty(requestVO.getSource()) ? OrderClientType.SAAS.getIndex() : getNewOrderClient(requestVO.getSource()));
//        }
        // fisherman->预定单场景 bizType = 7  other:普通订单
        Integer bizType = requestVO.getBizType();
        // 双重判断,防止前端乱传参搞事情
        if (Objects.nonNull(bizType) && BizTypeEnum.ADVANCE_ORDER.getBizType().compareTo(bizType) == 0) {
            request.setBizType(BizTypeEnum.ADVANCE_ORDER.getBizType());
        } else if (Objects.nonNull(bizType) && BizTypeEnum.MALL.getBizType().compareTo(bizType) == 0) {
            request.setBizType(BizTypeEnum.MALL.getBizType());
        } else {
            // 20210730之前 默认设置为1
            request.setBizType(CommonConstant.INTEGER_ONE);
        }
//        request.setOrderType(getNewOrderType(requestVO.getOrderType(), requestVO.getGmtExpect(), request.getBizType()));
        request.setOrderType(requestVO.getNewOrderType().getIndex());
        request.setNote(requestVO.getRemark());
        request.setBarCounter(requestVO.getBarCounter());

        //订单market类型
        if (requestVO.getMarketingType() != null) {
            request.setMarketingType(ClassUtils.toInteger(requestVO.getMarketingType()));
        }

        //商品信息转换
        List<OrderItemCreateReq> orderItemList = new ArrayList<>();
        //优惠信息转换
        List<OrderSettlementCreateReq> orderSettlementCreateReqList = new ArrayList<>();
        //结算信息转换
        List<OrderCostCreateReq> orderCostCreateReqs = new ArrayList<>();
        // 更新订单商品详情信息
        originalAmount = updateOrderItemsAndSettlements(orderItemList, orderSettlementCreateReqList, orderCostCreateReqs, requestVO.getProducts(), requestVO.getAccounts(), requestVO.getCompanyId());
        //将优惠信息中的活动优惠按优先级排个序 （对接美团Pos需要）
        orderSettlementCreateReqList = this.sortSettlementCreateList(orderSettlementCreateReqList, requestVO);
        //增加总优惠记录
        if (!CollectionUtils.isEmpty(requestVO.getAccounts())) {
            addTotalDisaccountData(orderSettlementCreateReqList, requestVO);
        }
        //商品信息赋值
        request.setOrderItemList(orderItemList);
        //订单原始金额，单位分
        request.setOriginalAmount(originalAmount);
        //结算信息赋值
        request.setOrderCostDetailList(orderCostCreateReqs);
        //商品优惠信息赋值
        request.setOrderSettlementDetailList(orderSettlementCreateReqList);

        //收货人信息转换
        List<DeliveryContactInfoCreateReq> deliveryContactInfoList = new ArrayList<DeliveryContactInfoCreateReq>();
        DeliveryContactInfoCreateReq deliveryContactInfoCreateReq = new DeliveryContactInfoCreateReq();
        //地址类型 1:订单地址 2:售后单地址 3:配送员信息
        deliveryContactInfoCreateReq.setRelateObjectType(1);
        //联系方式类型 1:取件 2:收件
        deliveryContactInfoCreateReq.setInfoType(1);
        deliveryContactInfoCreateReq.setContactsName(requestVO.getContactsName());
        deliveryContactInfoCreateReq.setMobile(requestVO.getPhone());
        deliveryContactInfoCreateReq.setLatitude(StringUtils.isBlank(requestVO.getLatitude()) ? null : new BigDecimal(requestVO.getLatitude()));
        deliveryContactInfoCreateReq.setLongitude(StringUtils.isBlank(requestVO.getLongitude()) ? null : new BigDecimal(requestVO.getLongitude()));
        deliveryContactInfoCreateReq.setAddressDetail(requestVO.getAddress());
        deliveryContactInfoCreateReq.setProvince(requestVO.getProvince());
        deliveryContactInfoCreateReq.setCity(requestVO.getCity());
        deliveryContactInfoCreateReq.setRegion(requestVO.getRegion());
        JSONObject deliveryExtInfo = new JSONObject();
        deliveryExtInfo.put("receiveId", requestVO.getReceiveId());
        deliveryContactInfoCreateReq.setExtInfo(deliveryExtInfo.toJSONString());
        deliveryContactInfoList.add(deliveryContactInfoCreateReq);
        //第三方配送信息
        getThirdDeliveryInfo(deliveryContactInfoList, requestVO.getDeliveryType());
        request.setDeliveryContactInfoList(deliveryContactInfoList);
        //保存门店渠道信息
        request.setOrderExtended(requestVO.getOrderExtended());
        request.setOperator(requestVO.getOperator());
        request.setAppId(requestVO.getAppId());

        // 扩展字段（第三方商品分类编号）
        if (null != requestVO && null != requestVO.getOtherInfo()) {
            request.setExtInfo(JSONObject.toJSONString(requestVO.getOtherInfo()));
        }

        //订单重量
        Double orderWeight = sumOrderWeight(requestVO.getProducts());
        request.setWeight(orderWeight);

        // 买一赠一寄件信息
        if (requestVO.getChooseGoods() != null && !requestVO.getChooseGoods().isEmpty()) {
            request.setOrderSendCouponRespList(JSONArray.parseArray(JSONObject.toJSONString(requestVO.getChooseGoods()), CreateOrderRequest.ChooseGood.class));
        }
        // 【ID1030916】订单查询门店获取预计送达时间
        if (requestVO.getEstimateDeliveryCompleteTime() != null) {
            Date time = requestVO.getEstimateDeliveryCompleteTime();
            request.setEstimateDeliveryCompleteTime(time.getTime() + "");
        }
        request.setUserMobile(requestVO.getUserMobile());
        request.setUserSourceType(requestVO.getUserSourceType());
        request.setPhysicalGoodsFlag(requestVO.getPhysicalGoodsFlag());
        return request;
    }

    /**
     * 美团Pos对接的时候，需要将优惠信息排序
     *
     * @param orderSettlementCreateReqList
     * @param requestVo
     * @return List<OrderSettlementCreateReq> 排序后
     */
    private List<OrderSettlementCreateReq> sortSettlementCreateList(List<OrderSettlementCreateReq> orderSettlementCreateReqList, BaseCreateOrderRequest requestVo) {
        List<OrderSettlementCreateReq> result = new ArrayList<>();
        //订单参与的活动信息，这个list是已经按照活动优先级排好了
        List<CreateOrderAccountRequest> accountList = requestVo.getAccounts();
        if (CollectionUtils.isEmpty(accountList)) return result;
        for (CreateOrderAccountRequest account : accountList) {
            Iterator<OrderSettlementCreateReq> iterator = orderSettlementCreateReqList.iterator();
            while (iterator.hasNext()) {
                OrderSettlementCreateReq coa = iterator.next();
                if (Objects.equals(coa.getExternalObjectId(), account.getAccountId())) {
                    result.add(coa);
                    iterator.remove();
                }
            }
        }
        //此时iterator中还有元素的话，就是非促销的优惠数据，追加到后面
        result.addAll(orderSettlementCreateReqList);
        return result;
    }

    private void addTotalDisaccountData(List<OrderSettlementCreateReq> orderSettlementCreateReqList, BaseCreateOrderRequest requestVO) {
        OrderSettlementCreateReq createReq = new OrderSettlementCreateReq();
        createReq.setProductId("0");
        createReq.setProductSeq(0);
        createReq.setNumber(0);
        createReq.setExternalObjectId("");
        createReq.setSettlementType(205);
        //商家优惠
        createReq.setShopDiscountAmount(requestVO.getTotalDiscountAmount());
        //结算金额
        createReq.setSettlementAmount(requestVO.getAmount());
        createReq.setPlatformDiscountAmount(0L);
        //是否线上 false:不是 true:是
        createReq.setIsOnline(true);
        createReq.setExternalObjectName("优惠总金额");
        orderSettlementCreateReqList.add(createReq);
    }

    public com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest convent2NEWCreateMCCafeOrderRequest(BaseCreateOrderRequest requestVO) {
        com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest request = new com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest();
        request.setPartnerId(requestVO.getCompanyId());
        request.setStoreId(requestVO.getShopId());
        //1:线上支付 2:线下支付
        request.setPayType(1);
        request.setUserId(requestVO.getUserId());
        request.setUserName(requestVO.getUserName());
        request.setStoreName(requestVO.getShopName());
        request.setPayTime(requestVO.getPayTime());
        request.setThirdStoreId(requestVO.getThirdShopId());
        request.setThirdOrderCode(requestVO.getThirdOrderCode());
        request.setPayChannelType(requestVO.getPayChannelType());
//        if (requestVO.getOrderStatus() != null) {
//            request.setOrderState(getNewOrderStatus(requestVO.getOrderStatus().getCode()));
//        }
//        if (requestVO.getPayStatus() != null) {
//            request.setPayState(requestVO.getPayStatus().getCode());
//        }
        if (requestVO.getPayChannel() != null) {
            request.setPayChannel(requestVO.getPayChannel());
        }
        if (requestVO.getPayChannelName() != null) {
            request.setPayChannelName(requestVO.getPayChannelName());
        }
        if (requestVO.getGmtExpect() != null && requestVO.getGmtExpect() != 0) {
            request.setExpectTime(new Date(requestVO.getGmtExpect()));
        }
        //订单原始金额，单位分
        Long originalAmount = 0L;
        //用户在界面上看到的支付金额
        request.setSettlementAmount(requestVO.getAmount());
        //实际支付现金金额，扣除支付自生优惠，单位分
        request.setActualPayAmount(requestVO.getAmount());
        request.setOrderClient(requestVO.getOrderClient().getIndex());
//        if (requestVO.getOrderClient() != null) {
//            request.setOrderClient(requestVO.getOrderClient().getIndex());
//        } else {
//            request.setOrderClient(StringUtils.isEmpty(requestVO.getSource()) ? OrderClientType.SAAS.getIndex() : getNewOrderClient(requestVO.getSource()));
//        }
        //订单业务类型 1:普通订单 2:虚拟订单
        request.setBizType(1);
        request.setNote(requestVO.getRemark());
//        request.setOrderType(getNewOrderType(requestVO.getOrderType(), requestVO.getGmtExpect(), request.getBizType()));
        request.setOrderType(requestVO.getNewOrderType().getIndex());
        request.setBarCounter(requestVO.getBarCounter());

        //商品信息转换
        List<OrderItemCreateReq> orderItemList = new ArrayList<>();
        //优惠信息转换
        List<OrderSettlementCreateReq> orderSettlementCreateReqList = new ArrayList<>();
        //结算信息转换
        List<OrderCostCreateReq> orderCostCreateReqs = new ArrayList<>();
        // 更新订单商品详情信息
        originalAmount = updateMCCafeOrderItemsAndSettlements(orderItemList, orderSettlementCreateReqList, orderCostCreateReqs, requestVO.getProducts(), requestVO.getAccounts(), requestVO.getCompanyId());
        //商品信息赋值
        request.setOrderItemList(orderItemList);
        //订单原始金额，单位分
        request.setOriginalAmount(originalAmount);
        //结算信息赋值
        request.setOrderCostDetailList(orderCostCreateReqs);
        //商品优惠信息赋值
        request.setOrderSettlementDetailList(orderSettlementCreateReqList);

        //收货人信息转换
        List<DeliveryContactInfoCreateReq> deliveryContactInfoList = new ArrayList<DeliveryContactInfoCreateReq>();
        DeliveryContactInfoCreateReq deliveryContactInfoCreateReq = new DeliveryContactInfoCreateReq();
        //地址类型 1:订单地址 2:售后单地址 3:配送员信息
        deliveryContactInfoCreateReq.setRelateObjectType(1);
        //联系方式类型 1:取件 2:收件
        deliveryContactInfoCreateReq.setInfoType(1);
        deliveryContactInfoCreateReq.setContactsName(requestVO.getUserName());
        deliveryContactInfoCreateReq.setMobile(requestVO.getPhone());
        deliveryContactInfoCreateReq.setLatitude(StringUtils.isBlank(requestVO.getLatitude()) ? null : new BigDecimal(requestVO.getLatitude()));
        deliveryContactInfoCreateReq.setLongitude(StringUtils.isBlank(requestVO.getLongitude()) ? null : new BigDecimal(requestVO.getLongitude()));
        deliveryContactInfoCreateReq.setAddressDetail(requestVO.getAddress());
        deliveryContactInfoCreateReq.setProvince(requestVO.getProvince());
        deliveryContactInfoCreateReq.setCity(requestVO.getCity());
        deliveryContactInfoCreateReq.setRegion(requestVO.getRegion());
        JSONObject deliveryExtInfo = new JSONObject();
        deliveryExtInfo.put("receiveId", requestVO.getReceiveId());
        deliveryContactInfoCreateReq.setExtInfo(deliveryExtInfo.toJSONString());
        deliveryContactInfoList.add(deliveryContactInfoCreateReq);
        //第三方配送信息
        getThirdDeliveryInfo(deliveryContactInfoList, requestVO.getDeliveryType());
        request.setDeliveryContactInfoList(deliveryContactInfoList);
        //保存门店渠道信息
        request.setOrderExtended(requestVO.getOrderExtended());
        request.setOperator(requestVO.getOperator());
        request.setAppId(requestVO.getAppId());

        // 扩展字段（第三方商品分类编号）
        if (null != requestVO && null != requestVO.getOtherInfo()) {
            request.setExtInfo(JSONObject.toJSONString(requestVO.getOtherInfo()));
        }

        //订单重量
        Double orderWeight = sumOrderWeight(requestVO.getProducts());
        request.setWeight(orderWeight);
        return request;
    }


    @Deprecated
    public CreateFatherSonOrderReq convent2NEWCreateFatherSonOrderRequest(CreateFatherSonOrderRequest request) {
        CreateFatherSonOrderReq createFatherSonOrderReq = new CreateFatherSonOrderReq();
        createFatherSonOrderReq.setPartnerId(request.getPartnerId());
        List<CreateOrderRequest> orderList = new ArrayList<>();
        for (CreateFatherSonOrderRequest.OrderInfo orderInfo : request.getOrderInfoList()) {
            orderList.add(convertOrderInfo2CreateOrderRequest(orderInfo));
        }
        createFatherSonOrderReq.setOrders(orderList);
        createFatherSonOrderReq.setParentOrder(convertOrderInfo2CreateOrderRequest(request.getParentOrder()));
        createFatherSonOrderReq.setOperator(request.getOperator());
        return createFatherSonOrderReq;
    }

    @Deprecated
    private CreateOrderRequest convertOrderInfo2CreateOrderRequest(CreateFatherSonOrderRequest.OrderInfo orderInfo) {
        CreateOrderRequest createOrderRequest = new CreateOrderRequest();
        createOrderRequest.setStoreId(orderInfo.getShopId());
        //1:线上支付 2:线下支付
        createOrderRequest.setPayType(1);
        createOrderRequest.setUserId(orderInfo.getUserId());
        createOrderRequest.setUserName(orderInfo.getUserName());
        createOrderRequest.setStoreName(orderInfo.getShopName());
        createOrderRequest.setPartnerId(orderInfo.getPartnerId());
        createOrderRequest.setPayTime(orderInfo.getPayTime());
        createOrderRequest.setThirdStoreId(orderInfo.getThirdShopId());
//        if (orderInfo.getOrderStatus() != null) {
//            createOrderRequest.setOrderState(getNewOrderStatus(orderInfo.getOrderStatus().getCode()));
//        }
//        if (orderInfo.getPayStatus() != null) {
//            createOrderRequest.setPayState(orderInfo.getPayStatus().getCode());
//        }
        if (orderInfo.getPayChannel() != null) {
            createOrderRequest.setPayChannel(orderInfo.getPayChannel());
        }
        if (orderInfo.getPayChannelName() != null) {
            createOrderRequest.setPayChannelName(orderInfo.getPayChannelName());
        }
        if (orderInfo.getGmtExpect() != null && orderInfo.getGmtExpect() != 0) {
            createOrderRequest.setExpectTime(new Date(orderInfo.getGmtExpect()));
        }
        //订单原始金额，单位分
        Long originalAmount = 0L;
        //用户在界面上看到的支付金额
        createOrderRequest.setSettlementAmount(orderInfo.getAmount());
        //实际支付现金金额，扣除支付自生优惠，单位分
        createOrderRequest.setActualPayAmount(orderInfo.getAmount());
        //区分创建订单是会员卡订单还是商品订单
        createOrderRequest.setOrderClient(orderInfo.getOrderClient());

        //订单业务类型 1:普通订单 2:虚拟订单
        createOrderRequest.setBizType(orderInfo.getBizType());
        createOrderRequest.setIsParent(orderInfo.getIsParent());
        createOrderRequest.setNote(orderInfo.getRemark());
//        createOrderRequest.setOrderType(getNewOrderType(orderInfo.getOrderType(), orderInfo.getGmtExpect(), createOrderRequest.getBizType()));
        createOrderRequest.setBarCounter(orderInfo.getBarCounter());

        //商品信息转换
        List<OrderItemCreateReq> orderItemList = new ArrayList<OrderItemCreateReq>();
        //优惠信息转换
        List<OrderSettlementCreateReq> orderSettlementCreateReqList = new ArrayList<OrderSettlementCreateReq>();
        //结算信息转换
        List<OrderCostCreateReq> orderCostCreateReqs = new ArrayList<OrderCostCreateReq>();
        // 更新订单商品详情信息
        originalAmount = updateOrderItemsAndSettlements(orderItemList, orderSettlementCreateReqList, orderCostCreateReqs, orderInfo.getProducts(), orderInfo.getAccounts(), orderInfo.getPartnerId());
        //商品信息赋值
        createOrderRequest.setOrderItemList(orderItemList);
        //商品优惠信息赋值
        createOrderRequest.setOrderSettlementDetailList(orderSettlementCreateReqList);
        //订单原始金额，单位分
        createOrderRequest.setOriginalAmount(originalAmount);
        //结算信息赋值
        createOrderRequest.setOrderCostDetailList(orderCostCreateReqs);
        //收货人信息转换
        List<DeliveryContactInfoCreateReq> deliveryContactInfoList = new ArrayList<DeliveryContactInfoCreateReq>();
        DeliveryContactInfoCreateReq deliveryContactInfoCreateReq = new DeliveryContactInfoCreateReq();
        //地址类型 1:订单地址 2:售后单地址 3:配送员信息
        deliveryContactInfoCreateReq.setRelateObjectType(1);
        //联系方式类型 1:取件 2:收件
        deliveryContactInfoCreateReq.setInfoType(1);
        deliveryContactInfoCreateReq.setContactsName(orderInfo.getUserName());
        deliveryContactInfoCreateReq.setMobile(orderInfo.getPhone());
        deliveryContactInfoCreateReq.setLatitude(StringUtils.isBlank(orderInfo.getLatitude()) ? null : new BigDecimal(orderInfo.getLatitude()));
        deliveryContactInfoCreateReq.setLongitude(StringUtils.isBlank(orderInfo.getLongitude()) ? null : new BigDecimal(orderInfo.getLongitude()));
        deliveryContactInfoCreateReq.setAddressDetail(orderInfo.getAddress());
        deliveryContactInfoList.add(deliveryContactInfoCreateReq);
        //第三方配送信息
        getThirdDeliveryInfo(deliveryContactInfoList, null);
        createOrderRequest.setDeliveryContactInfoList(deliveryContactInfoList);
        //门店渠道信息
        createOrderRequest.setOrderExtended(orderInfo.getOrderExtended());
        return createOrderRequest;
    }

    /**
     * 获取第三方配送单信息
     *
     * @param deliveryContactInfoList
     */
    public void getThirdDeliveryInfo(List<DeliveryContactInfoCreateReq> deliveryContactInfoList, StoreDeliveryMethod deliveryType) {
        //if (addInfo != null && addInfo.getDeliveryType() != null && QueryDeliveryType.THIRD.getCode().equals(addInfo.getDeliveryType().getCode())) {
        if (deliveryType != null) {
            DeliveryContactInfoCreateReq deliveryinfo = new DeliveryContactInfoCreateReq();
            //地址类型 1:订单地址 2:售后单地址 3:配送员信息
            deliveryinfo.setRelateObjectType(3);
            deliveryinfo.setAddressDetail(deliveryType.getCode());
            deliveryContactInfoList.add(deliveryinfo);
        }
    }

    private Long convertCreateOrderCost(Long originalAmount, List<OrderSettlementCreateReq> orderSettlementCreateReqList, List<OrderCostCreateReq> orderCostCreateReqs, List<CreateOrderAccountRequest> accounts) {
        if (!CollectionUtils.isEmpty(accounts)) {
            AssortOrderLogUtil.info("fisherman 构建order_cost_detail数据", accounts, JSON.toJSONString(accounts));
            for (CreateOrderAccountRequest accountRequest : accounts) {
                //老订单服务 1=配送费;3=包装费
                if (QueryOrderAccountType.DELIVERY_AMOUNT.equals(accountRequest.getAccountType())
                        || QueryOrderAccountType.PACK_AMOUNT.equals(accountRequest.getAccountType())
                        || QueryOrderAccountType.CARD_ORIGINAL_AMOUNT.equals(accountRequest.getAccountType())
                        || QueryOrderAccountType.WITH_ORDER_BUY_COUPON_FEE.equals(accountRequest.getAccountType())) {
                    OrderCostCreateReq orderCostCreateReq = new OrderCostCreateReq();
                    orderCostCreateReq.setCostName(accountRequest.getName());
                    //新订单服务  1=包装费,2=运费,3=餐盒单价,4=餐盒数量
                    orderCostCreateReq.setCostType(getCostType(accountRequest.getAccountType()));
                    orderCostCreateReq.setActualCostAmount(accountRequest.getActualPrice() != null ? accountRequest.getActualPrice() : accountRequest.getPrice());
                    orderCostCreateReq.setCostAmount(accountRequest.getPrice());
                    originalAmount += accountRequest.getPrice();
                    orderCostCreateReq.setProductSeq(accountRequest.getSequence());
                    //1=订单,2=订单商品,3=售后单
                    orderCostCreateReq.setBillType(1);
                    orderCostCreateReq.setProductId(accountRequest.getProductId());
                    orderCostCreateReq.setNote(accountRequest.getNote());
                    orderCostCreateReqs.add(orderCostCreateReq);
                } else {
                    OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
                    orderSettlementCreateReq.setSettlementType(getDiscountType(accountRequest.getAccountType()));
                    orderSettlementCreateReq.setExternalObjectId(accountRequest.getAccountId());
                    orderSettlementCreateReq.setNote(accountRequest.getName());
                    orderSettlementCreateReq.setNumber(1);
                    //商家优惠
                    orderSettlementCreateReq.setShopDiscountAmount(accountRequest.getPrice());
                    //结算金额
                    orderSettlementCreateReq.setSettlementAmount(accountRequest.getPrice());
                    //是否线上 false:不是 true:是
                    orderSettlementCreateReq.setIsOnline(true);
                    orderSettlementCreateReq.setExtInfo(accountRequest.getAddInfo());
                    orderSettlementCreateReq.setProductId(accountRequest.getProductId());

                    orderSettlementCreateReqList.add(orderSettlementCreateReq);
                }
            }
        }
        return originalAmount;
    }

    /**
     * 转换订单费用类型
     *
     * @param queryOrderAccountType
     * @return
     */
    private Integer getCostType(QueryOrderAccountType queryOrderAccountType) {
        // 订单费用类型 1=包装费,2=运费,3=餐盒单价,4=餐盒数量,5=会员卡费用,10=麦咖啡月卡
        Integer type = 0;
        String code = queryOrderAccountType.getCode();

        switch (code) {
            case "PACK_AMOUNT":
                type = 1;
                break;
            case "DELIVERY_AMOUNT":
                type = 2;
                break;
            case "CARD_ORIGINAL_AMOUNT":
                type = 5;
                break;
            case "WITH_ORDER_BUY_COUPON_FEE":
                type = 10;
                break;
            default:
                break;
        }

        return type;
    }

    /**
     * 综合查询订单参数转化
     */
    public OrderUserConditionsReq convent2QueryOrdersRequest(QueryOrdersRequest queryOrdersRequest) {
        OrderUserConditionsReq orderConditionsReq = new OrderUserConditionsReq();

        orderConditionsReq.setPartnerId(queryOrdersRequest.getCompanyId());
        orderConditionsReq.setUserId(queryOrdersRequest.getUserId());
        orderConditionsReq.setUserIds(queryOrdersRequest.getUserIds());
        orderConditionsReq.setPageSize(queryOrdersRequest.getPageSize());
        orderConditionsReq.setPageNum(queryOrdersRequest.getPageNumber());
        orderConditionsReq.setNeedInvoice(queryOrdersRequest.getNeedInvoice());

        List<Integer> orderStatus = new ArrayList<>();
        if (queryOrdersRequest.getStatus() != null && queryOrdersRequest.getStatus().length != 0) {
            for (int i = 0; i < queryOrdersRequest.getStatus().length; i++) {
                orderStatus.add(getNewOrderStatus(queryOrdersRequest.getStatus()[i]));
            }
        }

        List<Integer> orderType = new ArrayList<>();
        if (queryOrdersRequest.getType() != null && queryOrdersRequest.getType().length != 0) {
            for (int i = 0; i < queryOrdersRequest.getType().length; i++) {
                //订单服务订单类型 1=外卖 4=自提，5=堂食
                //外卖平台订单类型 1=常规堂食，2=预约堂食，3=常规外送，4=预约外送，5=常规自取，6=预约自取
                if (queryOrdersRequest.getType()[i] == 1) {
                    orderType.add(3);
                    orderType.add(4);
                }
                if (queryOrdersRequest.getType()[i] == 4) {
                    orderType.add(5);
                    orderType.add(6);
                }
                if (queryOrdersRequest.getType()[i] == 5) {
                    orderType.add(1);
                    orderType.add(2);
                }
            }
        }

        orderConditionsReq.setPayStatus(queryOrdersRequest.getPayStatus() == null ? null : Arrays.asList(queryOrdersRequest.getPayStatus()));
        orderConditionsReq.setOrderStatus(orderStatus);
        orderConditionsReq.setOrderType(orderType);
        //退款的现在不查询，不用对接，existTakeCode不对接
//        List<Integer> orderClients = new ArrayList<>();
//        for (int i = 0; i < queryOrdersRequest.getSource().length; i++) {
//            if ("saas".equals(queryOrdersRequest.getSource()[i])) {
//                orderClients.add(OrderClientType.SAAS.getIndex());
//                orderClients.add(OrderClientType.ALIPAY.getIndex());
//            }
//            else if ("meals".equals(queryOrdersRequest.getSource()[i])) {
//                orderClients.add(OrderClientType.WAI_MEAL.getIndex());
//                orderClients.add(OrderClientType.ALIPAY.getIndex());
//            }
//            else if ("saasmall".equals(queryOrdersRequest.getSource()[i])) {
//                orderClients.add(OrderClientType.SAASMALL.getIndex());
//            }
//            else if ("app".equals(queryOrdersRequest.getSource()[i])) {
//                orderClients.add(OrderClientType.APP.getIndex());
//                orderClients.add(OrderClientType.ALIPAY.getIndex());
//            }
//            else if ("beautiful".equals(queryOrdersRequest.getSource()[i])) {
//                orderClients.add(OrderClientType.BEAUTIFUL.getIndex());
//                orderClients.add(OrderClientType.ALIPAY.getIndex());
//            }
//            else if ("cashier".equals(queryOrdersRequest.getSource()[i])) {
//                orderClients.add(OrderClientType.CASHIER.getIndex());
//            }
//        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startDate = sdf.parse(queryOrdersRequest.getStartDate());
            Date endDate = sdf.parse(queryOrdersRequest.getEndDate());
            orderConditionsReq.setStartTimestamp(startDate.getTime() / 1000);
            orderConditionsReq.setEndTimestamp(endDate.getTime() / 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        orderConditionsReq.setOrderClients(queryOrdersRequest.getOrderClients());
        orderConditionsReq.setBizTypes(queryOrdersRequest.getBizTypes());
        orderConditionsReq.setMarketingType(queryOrdersRequest.getMarketingType());
        orderConditionsReq.setMarketingTypes(queryOrdersRequest.getMarketingTypes());

        return orderConditionsReq;
    }

    /**
     * 综合查询订单参数转化
     */
    public OrderConditionsReq convent2QueryOrdersByConditionsRequest(QueryOrdersByConditionsRequest request) {
        OrderConditionsReq orderConditionsReq = new OrderConditionsReq();

        orderConditionsReq.setOrderCode(request.getOrderId());
        orderConditionsReq.setOrderCodes(request.getOrderIds());
        orderConditionsReq.setPartnerId(request.getCompanyId());
        orderConditionsReq.setPageSize(request.getPageSize());
        orderConditionsReq.setPageNum(request.getPageNumber() > 0 ? request.getPageNumber() : 0);
        orderConditionsReq.setMobile(request.getPhoneNo());
        orderConditionsReq.setStoreIds(request.getShopIds());
        orderConditionsReq.setPayStatuses(request.getPayStatuses());
        orderConditionsReq.setUserId(request.getUserId());
        orderConditionsReq.setThirdOrderCode(request.getThirdOrderCode());
        orderConditionsReq.setBizType(request.getBizType());
        if (request.getOrderStatuses() != null && request.getOrderStatuses().size() > 0) {
            List<Integer> orderStatusList = new ArrayList<>();
            for (Integer orderStatus : request.getOrderStatuses()) {
                Integer status = getNewOrderStatus(orderStatus);
                orderStatusList.add(status);
            }
            orderConditionsReq.setOrderStatuses(orderStatusList);
        }
        if (CollectionUtils.isNotEmpty(request.getOrderTypes())) {
            List<Integer> orderTypeList = request.getOrderTypes().stream().filter(orderType -> orderType != null && !orderType.equals(0)).collect(Collectors.toList());
            if (orderTypeList != null && orderTypeList.size() > 0) {
                List<Integer> orderTypes = new ArrayList<>();
                for (Integer orderType : orderTypeList) {
                    List<Integer> types = getNewOrderType(orderType);
                    orderTypes.addAll(types);
                }
                orderConditionsReq.setOrderTypes(orderTypes);
            }
        }

        //订单类型 1:(店内自取实时-常规堂食) 2:(店内自取预约-预约堂食) 3:(店外快递实时-常规外送) 4:(店外快递预约-预约外送) 5:(店外自取实时-常规自取) 6:(店外自取预约-预约自取)
        if (CollectionUtils.isNotEmpty(request.getNewOrderTypes())) {
            orderConditionsReq.setOrderTypes(request.getNewOrderTypes().stream().filter(orderType -> orderType != null && !orderType.equals(0)).collect(Collectors.toList()));
        }

        orderConditionsReq.setAfterSalesStatus(getOldRefoundStatus(request.getAfterSalesStatus()));
        List<Integer> orderClients = new ArrayList<>();
        if (request.getSource() != null && request.getSource().size() != 0) {
            for (String s : request.getSource()) {
                orderClients.add(getNewOrderClient(s));
            }
        }
        orderConditionsReq.setOrderClients(orderClients);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startDate = sdf.parse(request.getStartDate());
            Date endDate = sdf.parse(request.getEndDate());
            orderConditionsReq.setStartTimestamp(startDate.getTime() / 1000);
            orderConditionsReq.setEndTimestamp(endDate.getTime() / 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return orderConditionsReq;
    }

    /**
     * 新订单服务创建返回对象 转换成 老订单服务创建返回对象
     */
    public CreateOrderResponse convent2NEWOrderInfoReqs(OrderBaseResp<OrderInfoReqs> result) {
        CreateOrderResponse response = new CreateOrderResponse();
        response.setErrcode(Integer.parseInt(result.getCode()));
        response.setErrmsg(result.getMessage());
        /**
         * 为什么做这样的判断result.getResult().equals(new OrderInfoReqs())？
         * 我猜是因为基础服务异常返回的时候以前result返回了{}对象
         */
        if (result.getResult() == null || result.getResult().equals(new OrderInfoReqs())) {
            return response;
        }

        OrderBeanV1 data = orderCenterSdkAdapter.convent2NEWOrderInfo(result.getResult());
        response.setData(data);
        return response;
    }

    /**
     * 新订单服务创建父子订单返回对象 转换成 老订单服务创建返回对象
     */
    public CreateFatherSonOrderResponse convent2NEWFatherOrderInfoReqs(OrderBaseResp<List<OrderInfoReqs>> result) {
        CreateFatherSonOrderResponse response = new CreateFatherSonOrderResponse();
        response.setErrcode(Integer.parseInt(result.getCode()));
        response.setErrmsg(result.getMessage());
        if (result.getResult() == null) {
            return response;
        }
        List<OrderBeanV1> orderBeanList = new ArrayList<>();
        result.getResult().forEach(orderInfoReqs -> {
            OrderBeanV1 orderBean = orderCenterSdkAdapter.convent2NEWOrderInfo(orderInfoReqs);
            orderBeanList.add(orderBean);
        });

        response.setOrderBeanList(orderBeanList);
        return response;
    }

    /**
     * 新订单服务查询父子订单返回对象 转换成 老订单服务创建返回对象
     */
    public QueryRelatedOrderByCodeResp convent2QueryFatherOrderInfo(OrderBaseResp<List<OrderInfoReqs>> result) {
        QueryRelatedOrderByCodeResp response = new QueryRelatedOrderByCodeResp();
        response.setErrcode(Integer.parseInt(result.getCode()));
        response.setErrmsg(result.getMessage());
        if (CollectionUtils.isEmpty(result.getResult())) {
            return response;
        }
        List<OrderBeanV1> orderBeanList = new ArrayList<>();
        result.getResult().forEach(orderInfoReqs -> {
            OrderBeanV1 orderBean = orderCenterSdkAdapter.convent2NEWOrderInfo(orderInfoReqs);
            orderBeanList.add(orderBean);
        });

        response.setOrderBeanList(orderBeanList);
        return response;
    }

    /**
     * 新订单服务查询单个订单信息返回对象 转换成 老订单服务查询返回对象
     */
    public QueryOrderByIdResponse convent2QueryOrderByIdResponse(QueryByCodeResponse result) {
        QueryOrderByIdResponse response = new QueryOrderByIdResponse();
        if (result == null || result.getResult() == null) {
            return response;
        }
        response.setErrcode(Integer.parseInt(result.getCode()));
        response.setErrmsg(result.getMessage());
        if (result.getResult().getOrderCode() == null || "".equals(result.getResult().getOrderCode())) {
            return response;
        }
        OrderBeanV1 data = orderCenterSdkAdapter.convent2NEWOrderInfo(result.getResult());
        response.setData(data);
        return response;
    }

    /**
     * 新订单服务查询单个订单信息返回对象 转换成 老订单服务查询返回对象
     */
    public OrderDetailResponse convent2OrderDetailResponse(QueryByCodeResponse result) {
        OrderDetailResponse response = new OrderDetailResponse();
        if (result == null || result.getResult() == null) {
            return response;
        }
        response.setErrcode(Integer.parseInt(result.getCode()));
        response.setErrmsg(result.getMessage());
        if (result.getResult().getOrderCode() == null || "".equals(result.getResult().getOrderCode())) {
            return response;
        }
        OrderBeanV1 data = orderCenterSdkAdapter.convent2NEWOrderInfo(result.getResult());
        response.setData(data);
        return response;
    }


    /**
     * 老订单服务结算信息转化 order_account表
     */
    private List<AccountBeanV1> getOldOrderAccountList(List<OrderSettlementResp> orderSettlementResps,
                                                       List<OrderCostResp> orderCostResps) {
        List<AccountBeanV1> accountList = new ArrayList<AccountBeanV1>();

        //新订单服务优惠信息集合
        List<OrderSettlementResp> orderSettlementResps1 = orderSettlementResps == null ? new ArrayList<>() : orderSettlementResps;
        for (OrderSettlementResp orderSettlementResp : orderSettlementResps1) {
            if ("0".equals(orderSettlementResp.getProductId()) || StringUtils.isBlank(orderSettlementResp.getProductId())) {
                //第三方外卖订单会保存优惠总金额，不计为单个类型优惠
                if (OrderSettlementType.DISCOUNT_FEE.getIndex() == orderSettlementResp.getSettlementType().intValue()) {
                    continue;
                }
                AccountBeanV1 accountBean = new AccountBeanV1();
                accountBean.setAccountId(orderSettlementResp.getExternalObjectId());
                accountBean.setOrderId("");
                accountBean.setName(orderSettlementResp.getNote());
                accountBean.setNumber(1);
                accountBean.setPrice(orderSettlementResp.getSettlementAmount() == null ? 0L : orderSettlementResp.getSettlementAmount().longValue());
                //处理第三方外卖单优惠金额信息
                if (orderSettlementResp.getSettlementAmount() != null && orderSettlementResp.getSettlementAmount().intValue() > 0) {
                    long discountFee = 0 - Math.abs(orderSettlementResp.getSettlementAmount().longValue());
                    accountBean.setPrice(discountFee);
                }
                accountBean.setSequence(orderSettlementResp.getProductSeq());
                accountBean.setType(getOldOrderAccountType(orderSettlementResp.getSettlementType()));
                accountBean.setAddInfo(orderSettlementResp.getExtInfo());
                accountBean.setPlatformDiscountAmount(orderSettlementResp.getPlatformDiscountAmount());
                accountBean.setShopDiscountAmount(orderSettlementResp.getShopDiscountAmount());
                accountList.add(accountBean);
            }
        }

        //新订单 订单费用信息集合 餐盒费和包装费
        List<OrderCostResp> orderCostResps1 = orderCostResps == null ? new ArrayList<>() : orderCostResps;
        for (OrderCostResp orderCostResp : orderCostResps1) {
            AccountBeanV1 accountBean = new AccountBeanV1();
            accountBean.setAccountId(orderCostResp.getProductId());
            accountBean.setOrderId("");
            accountBean.setName(orderCostResp.getCostName());
            accountBean.setNumber(1);
            accountBean.setPrice(orderCostResp.getCostAmount().longValue());
            accountBean.setActualCostAmount(null != orderCostResp.getActualCostAmount() ? orderCostResp.getActualCostAmount().longValue() : 0);
            accountBean.setSequence(orderCostResp.getProductSeq());
            //新订单服务  1=包装费，2=运费，5=会员卡费用
            if (orderCostResp.getCostType() == 2) {
                accountBean.setType(OldOrderAccountType.DELIVERY_AMOUNT.getCode());
            }
            if (orderCostResp.getCostType() == 1) {
                accountBean.setType(OldOrderAccountType.PACK_AMOUNT.getCode());
            }
            if (orderCostResp.getCostType() == 5) {
                accountBean.setType(OldOrderAccountType.CARD_ORIGINAL_AMOUNT.getCode());
            }
            if (orderCostResp.getCostType() == 7) {
                accountBean.setType(OldOrderAccountType.DRIVER_FEE.getCode());
            }
            if (orderCostResp.getCostType() == 10) {
                accountBean.setType(OldOrderAccountType.WITH_ORDER_BUY_COUPON_FEE.getCode());
            }
            accountBean.setAddInfo("");
            accountList.add(accountBean);
        }
        return accountList;
    }

    /**
     * 老订单服务商品信息转化 order_product 和produce_discount 表
     */
    private List<ProductBeanV1> getOldOrderProductList(List<OrderSettlementResp> orderSettlementResps,
                                                       List<OrderItemResp> orderItemList) {
        List<ProductBeanV1> productList = new ArrayList<ProductBeanV1>();
        List<OrderItemResp> parentOrderItemList = orderItemList == null ? new ArrayList<>() : orderItemList.stream()
                .filter(item -> StringUtils.isEmpty(item.getParentProductId()) || ObjectUtils.equals("0", item.getParentProductId()))
                .collect(Collectors.toList());
        for (OrderItemResp orderItem : parentOrderItemList) {
            ProductBeanV1 productBean = getOldOrderProduct(orderSettlementResps, orderItem);
            if (ObjectUtils.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), orderItem.getProductType()) || ObjectUtils.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), orderItem.getProductType())) {
                // 获取套餐子商品列表
                productBean.setComboProduct(new ArrayList<>());
                String partnerProductId = orderItem.getProductId() + "_" + orderItem.getProductSeq();
                List<OrderItemResp> comboProducts = orderItemList.stream().filter(item -> ObjectUtils.equals(partnerProductId, item.getParentProductId())).collect(Collectors.toList());
                comboProducts.forEach(combo -> productBean.getComboProduct().add(getOldOrderProduct(orderSettlementResps, combo)));
                if (CollectionUtils.isNotEmpty(productBean.getComboProduct())) {
                    for (ProductBeanV1 comboProductBean : productBean.getComboProduct()) {
                        if (ObjectUtils.equals(ProductTypeEnum.MATERIAL_PRODUCT.getCode(), comboProductBean.getProductType())) {
                            comboProductBean.setMaterialProduct(new ArrayList<>());
                            String addProductId = comboProductBean.getProductId() + "_" + comboProductBean.getOpid();
                            List<OrderItemResp> materialProducts = orderItemList.stream().filter(item -> ObjectUtils.equals(addProductId, item.getParentProductId())).collect(Collectors.toList());
                            materialProducts.forEach(material -> comboProductBean.getMaterialProduct().add(getOldOrderProduct(new ArrayList<>(), material)));
                        }
                    }
                }
            }
            if (ObjectUtils.equals(ProductTypeEnum.MATERIAL_PRODUCT.getCode(), orderItem.getProductType())) {
                // 获取加料子商品列表
                productBean.setMaterialProduct(new ArrayList<>());
                String partnerProductId = orderItem.getProductId() + "_" + orderItem.getProductSeq();
                List<OrderItemResp> materialProducts = orderItemList.stream().filter(item -> ObjectUtils.equals(partnerProductId, item.getParentProductId())).collect(Collectors.toList());
                materialProducts.forEach(material -> productBean.getMaterialProduct().add(getOldOrderProduct(orderSettlementResps, material)));
            }

            if (StringUtils.isNotEmpty(productBean.getExtInfo())) {
                OrderProductAddInfoDto extInfo = JSONObject.parseObject(productBean.getExtInfo(), OrderProductAddInfoDto.class);
                productBean.setIsSendGoods(null == extInfo.getIsSendGoods() ? false : extInfo.getIsSendGoods());
                productBean.setCartGoodsUid(StringUtils.isEmpty(extInfo.getCartGoodsUid()) ? "" : extInfo.getCartGoodsUid());
                productBean.setOriginalGoodsUid(StringUtils.isEmpty(extInfo.getOriginalGoodsUid()) ? "" : extInfo.getOriginalGoodsUid());
            }

            productList.add(productBean);
        }
        if (null != productList && productList.size() > 0) {
            List<ProductBeanV1> originalProductLists = productList;

            for (ProductBeanV1 sendProductBean : productList) {
                sendProductBean.setIsPrint(true);
                if (null != sendProductBean.getIsSendGoods() && sendProductBean.getIsSendGoods() && StringUtils.isNotEmpty(sendProductBean.getOriginalGoodsUid())) {
                    sendProductBean.setIsPrint(false);
                }
                if (StringUtils.isNotEmpty(sendProductBean.getCartGoodsUid()) && null != sendProductBean.getIsSendGoods() && !sendProductBean.getIsSendGoods()) {
                    sendProductBean.setSendProduct(
                            originalProductLists.stream().filter(productBean -> productBean.getOriginalGoodsUid().equalsIgnoreCase(sendProductBean.getCartGoodsUid()) && productBean.getIsSendGoods() == true)
                                    .map(o -> JSON.parseObject(JSON.toJSONString(o), ProductBeanV1.class))
                                    .collect(Collectors.toList()));
                }
            }
        }
        return productList;
    }

    private ProductBeanV1 getOldOrderProduct(List<OrderSettlementResp> orderSettlementResps, OrderItemResp orderItemResp) {
        ProductBeanV1 productBean = new ProductBeanV1();
        productBean.setWeight(orderItemResp.getWeight());
        productBean.setCustomerCode(orderItemResp.getThirdProductId());
        productBean.setProductCode(orderItemResp.getProductCode());
        productBean.setNumber(orderItemResp.getProductQuantity());
        productBean.setOpid(orderItemResp.getProductSeq() == null ? null : orderItemResp.getProductSeq().toString());
        productBean.setSequence(orderItemResp.getProductSeq() == null ? 0 : orderItemResp.getProductSeq());
        productBean.setOrderId(orderItemResp.getOrderCode());
        productBean.setProductId(orderItemResp.getProductId());
        productBean.setParentProductId("");
        productBean.setPicture(orderItemResp.getProductPicUrl());
        productBean.setPrice(orderItemResp.getProductPrice().longValue());
        productBean.setSalePrice(orderItemResp.getSalePrice().longValue());
        productBean.setProductName(orderItemResp.getProductName());
        productBean.setProductForeignName(orderItemResp.getProductForeignName());
        productBean.setSpecification(orderItemResp.getProductSpec());
        productBean.setSpecificationName(orderItemResp.getProductSpecName());
        productBean.setSpecificationForeignName(orderItemResp.getProductForeignSpecName());
        productBean.setProductSharePrice(orderItemResp.getProductSharePrice());
        productBean.setSettlementPrice(orderItemResp.getSettlementPrice().longValue());
        productBean.setUnit(orderItemResp.getProductUnit());
        Map<String, String> map = new HashMap<String, String>();
        map.put("attributeNames", orderItemResp.getProductProperty());
        map.put("attributeForeignNames", orderItemResp.getProductForeignProperty());
        productBean.setAddInfo(JSONObject.toJSONString(map));
        productBean.setProductProperty(orderItemResp.getProductProperty());
        productBean.setProductForeignProperty(orderItemResp.getProductForeignProperty());
        productBean.setExtInfo(orderItemResp.getExtInfo());
        productBean.setNote(orderItemResp.getNote());

        // 套餐
        productBean.setParentProductId(orderItemResp.getParentProductId());
        productBean.setProductType(orderItemResp.getProductType());
        productBean.setId(orderItemResp.getId());

        // 拼单类型商品加购人相关信息
        productBean.setUserId(orderItemResp.getUserId());
        productBean.setOpenId(orderItemResp.getOpenId());
        productBean.setNickName(orderItemResp.getNickName());
        productBean.setPhotoUrl(orderItemResp.getPhotoUrl());
        productBean.setPackPrice(orderItemResp.getPackPrice());

        List<ProductDiscountV1> discountList = new ArrayList<ProductDiscountV1>();
        List<OrderSettlementResp> orderSettlementResps1 = orderSettlementResps == null ? new ArrayList<>() : orderSettlementResps;
        for (OrderSettlementResp orderSettlementResp : orderSettlementResps1) {
            if (ObjectUtils.equals(orderItemResp.getProductSeq(), orderSettlementResp.getProductSeq()) && orderItemResp.getProductSpec().equals(orderSettlementResp.getProductId())) {
                ProductDiscountV1 productDiscount = new ProductDiscountV1();
                productDiscount.setDiscountId(orderSettlementResp.getExternalObjectId());
                productDiscount.setDiscountDesc(orderSettlementResp.getNote());
                productDiscount.setDiscountType(getOldOrderAccountType(orderSettlementResp.getSettlementType()));
                productDiscount.setDiscountPrice(orderSettlementResp.getSettlementAmount().longValue());
                productDiscount.setDiscountQty(orderSettlementResp.getNumber());
                productDiscount.setDiscountAmount(orderSettlementResp.getShopDiscountAmount());
                //无数据
                productDiscount.setCustomerCode("");
                productDiscount.setAddInfo(orderSettlementResp.getExtInfo());
                productDiscount.setProductId(orderSettlementResp.getProductId());
                productDiscount.setExtInfo(orderSettlementResp.getExtInfo());
                discountList.add(productDiscount);
            }
        }
        productBean.setDiscountList(discountList);
        return productBean;
    }

    private List<RefundBeanV1> getOldOrderRefundList(List<AfterSalesOrderResp> afterSalesOrderRespList) {
        List<RefundBeanV1> refundBeans = new ArrayList<>();
        for (AfterSalesOrderResp afterSalesOrderResp : afterSalesOrderRespList) {
            RefundBeanV1 refundBean = new RefundBeanV1();
            refundBean.setOrderId(afterSalesOrderResp.getOrderCode());
            refundBean.setPrice(afterSalesOrderResp.getReqAmount() == null ? null : afterSalesOrderResp.getReqAmount().longValue());
            refundBean.setReason(afterSalesOrderResp.getAfterSalesReason());
            refundBean.setRemark(afterSalesOrderResp.getReqRemark());
            refundBean.setDecisionReason(afterSalesOrderResp.getAdultRemark());
            refundBean.setRid(afterSalesOrderResp.getAfterSalesCode());
            //售后单状态 1:待处理 2:退货中 3:拒绝退款 4:已退货 5:完成 6:取消
            refundBean.setStatus(getOldOrderRefundStatus(afterSalesOrderResp.getAfterSalesStatus()));
            refundBean.setCreateTime(afterSalesOrderResp.getCreateTime());
            refundBean.setExtInfo(afterSalesOrderResp.getExtInfo());
            if (StringUtils.isNotBlank(afterSalesOrderResp.getExtInfo())) {
                AfterOrderExtInfoDto extInfoDto = JSONObject.parseObject(afterSalesOrderResp.getExtInfo(), new TypeReference<AfterOrderExtInfoDto>() {
                }.getType());
                if (extInfoDto != null) {
                    RefundModeEnum refundModeEnum;
                    if ((refundModeEnum = RefundModeEnum.getByIndex(extInfoDto.getRefundMode())) != null) {
                        refundBean.setRefundMode(refundModeEnum.getIndex());
                        refundBean.setRefundModeDesc(refundModeEnum.getName());
                    }
                    refundBean.setBatchRefundId(extInfoDto.getBatchRefundId());
                }

            }

            refundBeans.add(refundBean);
        }
        return refundBeans;
    }

    private List<OperationHistoryV1> getOrderOperationHistory(List<OrderOperationHistoryResp> orderOperationHistoryResps) {
        List<OperationHistoryV1> operationHistories = new ArrayList<>();
        if (orderOperationHistoryResps == null) {
            return operationHistories;
        }
        for (OrderOperationHistoryResp operationHistoryResp : orderOperationHistoryResps) {
            OperationHistoryV1 operationHistory = new OperationHistoryV1();
            operationHistory.setCreateTime(operationHistoryResp.getCreateTime());
            operationHistory.setOperationDesc(operationHistoryResp.getOperationDesc());
            operationHistory.setOperationMethod(operationHistoryResp.getOperationMethod());
            operationHistory.setOrderCode(operationHistoryResp.getOrderCode());
            operationHistory.setOperationType(operationHistoryResp.getOperationType());
            operationHistory.setPartnerId(operationHistoryResp.getPartnerId());
            operationHistory.setStoreId(operationHistoryResp.getStoreId());
            operationHistory.setOperator(operationHistoryResp.getOperator());
            operationHistory.setUpdateTime(operationHistoryResp.getUpdateTime());
            operationHistory.setUpdateTimestamp(operationHistoryResp.getUpdateTimestamp());
            operationHistories.add(operationHistory);
        }
        return operationHistories;
    }

    public QueryOrdersResponse convent2OrdersResponseByES(BaseDownLoadResponse<List<OrderInfoReqs>> baseDownLoadResponse) {
        QueryOrdersResponse response = new QueryOrdersResponse();
        response.setErrcode(Integer.parseInt(baseDownLoadResponse.getCode()));
        response.setErrmsg(baseDownLoadResponse.getMessage());
        if (baseDownLoadResponse == null || CollectionUtils.isEmpty(baseDownLoadResponse.getResult())) {
            QueryOrdersResponse.DataBean dataBean = new QueryOrdersResponse.DataBean();
            dataBean.setOrders(new ArrayList<>());
            dataBean.setUpdateTimestamp(0L);
            dataBean.setCount(0);
            response.setData(dataBean);
            return response;
        }
        QueryOrdersResponse.DataBean dataBean = new QueryOrdersResponse.DataBean();
        dataBean.setCount(baseDownLoadResponse.getTotalNum());
        List<OrderBeanV1> orders = new ArrayList<>();
        for (OrderInfoReqs orderInfoReqs : baseDownLoadResponse.getResult()) {
            OrderBeanV1 data = orderCenterSdkAdapter.convent2NEWOrderInfo(orderInfoReqs);
            orders.add(data);
        }
        dataBean.setOrders(orders);
        response.setData(dataBean);
        return response;
    }

    /**
     * 信息订单信息 转化成 老订单信息
     */
    @Deprecated
    public OrderBeanV1 convent2NEWOrderInfo(OrderInfoReqs orderInfoReqs) {
        OrderBeanV1 data = new OrderBeanV1();
        if (Objects.nonNull(orderInfoReqs.getEstimateDeliveryCompleteTime())) {
            data.setEstimateDeliveryCompleteTime(Long.parseLong(orderInfoReqs.getEstimateDeliveryCompleteTime()));
        }
        data.setOrderClient(orderInfoReqs.getOrderClient().toString());
        data.setCompanyId(orderInfoReqs.getPartnerId());
        data.setShopId(orderInfoReqs.getStoreId());
        data.setShopName(orderInfoReqs.getStoreName());
        data.setOid(orderInfoReqs.getOrderCode());
        data.setOrderType(getOldOrderType(orderInfoReqs.getOrderType()));
        data.setNewOrderType(orderInfoReqs.getOrderType());
        data.setAmount(orderInfoReqs.getSettlementAmount() == null ? 0L : orderInfoReqs.getSettlementAmount().longValue());
        data.setSettlementAmount(orderInfoReqs.getSettlementAmount() == null ? 0L : orderInfoReqs.getSettlementAmount().longValue());
        data.setActualPayAmount(orderInfoReqs.getActualPayAmount() == null ? 0L : orderInfoReqs.getActualPayAmount().longValue());
        data.setUserId(orderInfoReqs.getUserId());
        data.setUserName(orderInfoReqs.getUserName());
//        data.setType(getOldOrderType(orderInfoReqs.getOrderType()));
        data.setNeedInvoice(orderInfoReqs.getNeedInvoice());
        data.setOriginalAmount(orderInfoReqs.getOriginalAmount());
        AddDeliveryInfoV1 addInfo = new AddDeliveryInfoV1();
        addInfo.setExpress(orderInfoReqs.getExpressChannelName());
        data.setExtInfo(orderInfoReqs.getExtInfo());
        data.setBarCounter(orderInfoReqs.getBarCounter());
        data.setThirdOrderCode(orderInfoReqs.getThirdOrderCode());
        data.setDinersNumber(orderInfoReqs.getDinersNumber());
        data.setThirdShopId(orderInfoReqs.getThirdStoreId());
        data.setDownstreamPosCode(orderInfoReqs.getDownstreamPosCode());
        data.setDownstreamThirdOrderCode(orderInfoReqs.getDownstreamThirdOrderCode());
        data.setAppId(orderInfoReqs.getAppId());

        //20201222 新增配送类型 ->【ID1021986】
        //【订单开放平台】订单详情查询接口增加配送类型字段
        data.setExpressType(orderInfoReqs.getExpressType());
        data.setUserMobile(orderInfoReqs.getUserMobile());

        if (orderInfoReqs.getOrderExtended() != null) {
            // 围餐门店英文名称
            data.setShopNameEn(orderInfoReqs.getOrderExtended().getStoreNameEn());
            data.setSpellGroupCode(orderInfoReqs.getOrderExtended().getSpellGroupCode());
        }

        if (orderInfoReqs.getAfterSalesOrderList() != null && orderInfoReqs.getAfterSalesOrderList().size() >= 1) {
            data.setAfterSalesOrderResp(orderInfoReqs.getAfterSalesOrderList().get(0));
        }

        if (orderInfoReqs.getDeliveryContactInfoList() != null && orderInfoReqs.getDeliveryContactInfoList().size() != 0) {
            for (DeliveryContactInfoResp deliveryContactInfoResp : orderInfoReqs.getDeliveryContactInfoList()) {
                //地址类型 1:订单地址 2:售后单地址 3:配送员信息
                if (deliveryContactInfoResp.getRelateObjectType() == 1) {
                    data.setReceiveProvince(orderInfoReqs.getDeliveryContactInfoList().get(0).getProvince());
                    data.setReceiveCity(orderInfoReqs.getDeliveryContactInfoList().get(0).getCity());
                    data.setReceiveRegion(orderInfoReqs.getDeliveryContactInfoList().get(0).getRegion());
                    data.setContactsName(orderInfoReqs.getDeliveryContactInfoList().get(0).getContactsName());
                    data.setAddress(orderInfoReqs.getDeliveryContactInfoList().get(0).getAddressDetail());
                    data.setPhone(orderInfoReqs.getDeliveryContactInfoList().get(0).getMobile());
                    addInfo.setExtInfo(deliveryContactInfoResp.getExtInfo());
                    if (orderInfoReqs.getDeliveryContactInfoList().get(0).getLatitude() != null
                            && orderInfoReqs.getDeliveryContactInfoList().get(0).getLongitude() != null) {
                        data.setLatitude(orderInfoReqs.getDeliveryContactInfoList().get(0).getLatitude().doubleValue());
                        data.setLongitude(orderInfoReqs.getDeliveryContactInfoList().get(0).getLongitude().doubleValue());
                        data.setTakeAddress(orderInfoReqs.getDeliveryContactInfoList().get(0).getAddressDetail());
                    }
                }
                if (deliveryContactInfoResp.getRelateObjectType() == 3) {
                    data.setRiderName(deliveryContactInfoResp.getContactsName());
                    data.setRiderPhone(deliveryContactInfoResp.getMobile());
                    addInfo.setDeliveryId(deliveryContactInfoResp.getThirdDeliveryId());
                    addInfo.setExpressNo(deliveryContactInfoResp.getExpressNo());
                    addInfo.setDeliveryType(deliveryContactInfoResp.getAddressDetail());
                    addInfo.setExpress(orderInfoReqs.getExpressChannelName());
                    addInfo.setDeliverStatus(orderInfoReqs.getDeliveryState());
                    addInfo.setRiderName(deliveryContactInfoResp.getContactsName());
                    addInfo.setRiderPhone(deliveryContactInfoResp.getMobile());
                    data.setAddInfo(addInfo);
                }
            }
        }
        data.setOperator(orderInfoReqs.getOperator());
        data.setOperateTime(orderInfoReqs.getUpdateTimestamp());
        if (CollectionUtils.isNotEmpty(orderInfoReqs.getOrderOperationHistoryList())) {
            List<OrderOperationHistoryResp> historyList = orderInfoReqs.getOrderOperationHistoryList();
            OrderOperationHistoryResp historyResp = historyList.get(historyList.size() - 1);
            data.setOperator(historyResp.getOperator());
            data.setOperateTime(historyResp.getUpdateTime());
        }
        data.setArriveShopTime("");
        data.setCancelReason(orderInfoReqs.getCancelReason());
        data.setRemark(orderInfoReqs.getNote());

        data.setShopAddress("");
        data.setShopPhone("");
        data.setCourierName("");
        data.setCourierPhone("");
        data.setCreateUser("");
        data.setCustomerOrder(orderInfoReqs.getThirdOrderCode());
        data.setEvaluateStatus(0);

        try {
            if (orderInfoReqs.getAcceptTime() != null) {
                data.setGmtAccept(Long.parseLong(orderInfoReqs.getAcceptTime()));
            }
            if (orderInfoReqs.getCreateTime() != null) {
                data.setGmtCreate(Long.parseLong(orderInfoReqs.getCreateTime()));
            }
            if (orderInfoReqs.getExpectTime() != null) {
                data.setGmtExpect(Long.parseLong(orderInfoReqs.getExpectTime()));
            }
            if (orderInfoReqs.getUpdateTime() != null) {
                data.setGmtModified(Long.parseLong(orderInfoReqs.getUpdateTime()));
            }
            if (orderInfoReqs.getPayTime() != null) {
                data.setGmtPay(Long.parseLong(orderInfoReqs.getPayTime()));
            }
            if (orderInfoReqs.getReceiveTime() != null) {
                data.setGmtCompleteTime(Long.parseLong(orderInfoReqs.getReceiveTime()));
                data.setGmtReceiveTime(Long.parseLong(orderInfoReqs.getReceiveTime()));
            }
            if (orderInfoReqs.getDeliveryTime() != null) {
                data.setGmtDelivery(Long.decode(orderInfoReqs.getDeliveryTime()));
            }
            if (null != orderInfoReqs.getAfterSalesOrderList() && orderInfoReqs.getAfterSalesOrderList().size() > 0) {
                AfterSalesOrderResp afterSalesOrderResp = orderInfoReqs.getAfterSalesOrderList().get(0);
                if (AfterSalesStatus.COMPLETE.getIndex() == afterSalesOrderResp.getAfterSalesStatus()) {
                    data.setGmtRefundFinish(Long.parseLong(afterSalesOrderResp.getUpdateTime()));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (orderInfoReqs.getAfterSalesOrderList() != null && orderInfoReqs.getAfterSalesOrderList().size() != 0) {
            data.setHasRefund(true);
        } else {
            data.setHasRefund(false);
        }
        data.setInvoiceInfo("");
        data.setOtherCode(orderInfoReqs.getPickUpGoodsNo());
        data.setPartition("");
        data.setPayChannel(orderInfoReqs.getPayChannel());
        data.setPayChannelName(orderInfoReqs.getPayChannelName());
        //1:未支付 2:已支付 3:已退款 4:部分退款
        data.setPayStatus(orderInfoReqs.getPayState());
        data.setPayType(orderInfoReqs.getPayType());
        data.setPayVoucher(orderInfoReqs.getPayRequestNo());
        data.setPosId(orderInfoReqs.getPosCode());
        data.setDaySeq(orderInfoReqs.getDaySeq());
        data.setSource(getOldSource(orderInfoReqs.getOrderClient()));
        data.setSourceName(getOldSourceName(orderInfoReqs.getOrderClient()));
        data.setStatus(getOldStatus(orderInfoReqs.getOrderState()));
        data.setStatusV2(orderInfoReqs.getOrderState());
        data.setQueueIndex("");
        data.setUserType("");
        data.setOperateTakeOrderTime(null);
        data.setOperateWaitPayTime(null);
        data.setOperateReceiptTime(null);
        data.setOperateDistributionTime(null);
        data.setOperateCompleteTime(null);
        data.setOperateCalcelTime(null);
        data.setOperatePefuseTime(null);
        data.setOperateCompleteMakeTime(null);

        //运单相关信息
        data.setDeliverStatus(orderInfoReqs.getDeliveryState() != null ? orderInfoReqs.getDeliveryState() : 0);
        data.setReceiveTime("");
        data.setDepatchTime("");
        data.setArriveShopTime("");
        data.setSendTime("");
        data.setCompleteTime("");
        data.setParentCode(orderInfoReqs.getParentCode());
        data.setIsParent(orderInfoReqs.getIsParent());
        data.setBizType(orderInfoReqs.getBizType());

        data.setAbnormalDesc(orderInfoReqs.getAbnormalDesc());
        data.setAbnormalState(orderInfoReqs.getAbnormalState());

        data.setWeight(orderInfoReqs.getWeight());
        List<ProductBeanV1> productList = getOldOrderProductList(orderInfoReqs.getOrderSettlementDetailList(), orderInfoReqs.getOrderItemList());
        data.setProductList(productList);

        List<AccountBeanV1> accountList = getOldOrderAccountList(orderInfoReqs.getOrderSettlementDetailList(), orderInfoReqs.getOrderCostDetailList());
        data.setAccountList(accountList);

        if (orderInfoReqs.getAfterSalesOrderList() != null && orderInfoReqs.getAfterSalesOrderList().size() != 0) {
            List<RefundBeanV1> refundList = getOldOrderRefundList(orderInfoReqs.getAfterSalesOrderList());
            data.setRefundList(refundList);
        }
        data.setOrderOperationHistoryList(getOrderOperationHistory(orderInfoReqs.getOrderOperationHistoryList()));
        data.setApportionDetails(getApportionDetails(orderInfoReqs));
        data.setOrderSettlementDetailList(orderInfoReqs.getOrderSettlementDetailList());
        if (Objects.nonNull(orderInfoReqs.getOrderSettlementDetailList())) {
            orderInfoReqs.getOrderSettlementDetailList().stream()
                    .filter(e -> Objects.equals(OrderSettlementType.SPELL_GROUP.getIndex(), e.getSettlementType())).findFirst().ifPresent(e -> data.setSpellGroupActivityCode(e.getExternalObjectId()));
        }
        //费用信息
        data.setOrderCostDetailList(orderInfoReqs.getOrderCostDetailList());
        data.setExpressChannelName(orderInfoReqs.getExpressChannelName());
        data.setExpressNo(orderInfoReqs.getExpressNo());
        data.setExpressChannelCode(orderInfoReqs.getExpressChannelCode());
        //发票信息
        data.setOrderInvoice(orderInfoReqs.getOrderInvoice());
        data.setPayChannelType(orderInfoReqs.getPayChannelType());
        data.setPickUpGoodsNo(orderInfoReqs.getPickUpGoodsNo());
        //todo:混合支付
        if (CollectionUtils.isNotEmpty(orderInfoReqs.getOrderPayItemCreateReqList())) {
            data.setOrderPayItem(this.getOrderItemPayList(orderInfoReqs.getOrderPayItemCreateReqList()));
        }

        //订单类型回传
        if (orderInfoReqs.getMarketingType() != null) {
            data.setMarketingType(ClassUtils.toByte(orderInfoReqs.getMarketingType()));
        }
        data.setExpressType(orderInfoReqs.getExpressType() == null ? 0 : orderInfoReqs.getExpressType());

        // 买一赠一寄件信息
        data.setOrderSendCouponRespList(orderInfoReqs.getOrderSendCouponRespList());

        // 设置 额外拓展字段信息
        OrderExtendedReq orderExtended = this.getOrderExtendedObj(orderInfoReqs.getOrderExtended());
        data.setOrderExtended(orderExtended);
        data.setNeedInvoice(orderInfoReqs.getNeedInvoice());
        return data;
    }

    private OrderExtendedReq getOrderExtendedObj(OrderExtendedReq orderExtended) {
        if (Objects.isNull(orderExtended)) {
            return null;
        }
        return OrderExtendedReq.builder().orderClientGroup(orderExtended.getOrderClientGroup())
                .orderClientGroupCode(orderExtended.getOrderClientGroupCode())
                .storeNameEn(orderExtended.getStoreNameEn())
                .spellGroupCode(orderExtended.getSpellGroupCode())
                .userPhone(orderExtended.getUserPhone())
                .sendWord(orderExtended.getSendWord())
                .agentPayerId(orderExtended.getAgentPayerId())
                .agentPayerName(orderExtended.getAgentPayerName())
                .build();
    }

    /**
     * 混合支付转换
     *
     * @param OrderPayItemReqs
     */
    private List<OrderPayItemResp> getOrderItemPayList(List<OrderPayItemResp> OrderPayItemReqs) {
        List<OrderPayItemResp> OrderPayItemList = new ArrayList<>(2);
        for (OrderPayItemResp orderPayItemReq : OrderPayItemReqs) {
            OrderPayItemResp orderPayItem = new OrderPayItemResp();
            orderPayItem.setOrderCode(orderPayItemReq.getOrderCode());
            orderPayItem.setOrderPayItemCode(orderPayItemReq.getOrderPayItemCode());
            orderPayItem.setPayAmount(orderPayItemReq.getPayAmount());
            orderPayItem.setPayChannelName(orderPayItemReq.getPayChannelName());
            orderPayItem.setPayChannelType(orderPayItemReq.getPayChannelType());
            orderPayItem.setTransId(orderPayItemReq.getTransId());
            OrderPayItemList.add(orderPayItem);
        }
        return OrderPayItemList;
    }

    public QueryOrdersResponse convent2QueryOrdersResponse(OrderBaseResp<QueryOrderForUserResp> baseResponse) {
        QueryOrdersResponse response = new QueryOrdersResponse();
        response.setErrcode(Integer.parseInt(baseResponse.getCode()));
        response.setErrmsg(baseResponse.getMessage());
        if (baseResponse.getResult() == null) {
            return response;
        }

        String json = JSONObject.toJSONString(baseResponse.getResult());
        JSONObject jsonObject = JSONObject.parseObject(json);
        QueryOrderForUserResp queryOrderForUserResp = jsonObject.toJavaObject(QueryOrderForUserResp.class);
        if (queryOrderForUserResp.getTotal() == null || queryOrderForUserResp.getTotal() == 0
                || CollectionUtils.isEmpty(queryOrderForUserResp.getItemList())) {
            return response;
        }

        QueryOrdersResponse.DataBean dataBean = new QueryOrdersResponse.DataBean();
        dataBean.setCount(queryOrderForUserResp.getTotal());
        List<OrderBeanV1> orders = new ArrayList<>();
        for (OrderInfoReqs orderInfoReqs : queryOrderForUserResp.getItemList()) {
            // fisherman 需要开放 private OrderExtendedReq orderExtended 用于订单页面数据展示
            OrderBeanV1 data = orderCenterSdkAdapter.convent2NEWOrderInfo(orderInfoReqs);
            orders.add(data);
        }
        dataBean.setOrders(orders);
        response.setData(dataBean);
        return response;
    }

    public PayAccessResponse convent2PayAccessResponse(OrderBaseResp<PaySuccessResp> baseResponse) {
        PayAccessResponse response = new PayAccessResponse();
        response.setErrcode(Integer.parseInt(baseResponse.getCode()));
        response.setErrmsg(baseResponse.getMessage());
        if (baseResponse.getResult() == null) {
            return response;
        }

        PayAccessResponse.DataBean dataBean = new PayAccessResponse.DataBean();
        dataBean.setDaySeq(baseResponse.getResult().getDaySeq().toString());
        dataBean.setQueueIndex(baseResponse.getResult().getQueueIndex().toString());
        dataBean.setTakeCode(baseResponse.getResult().getPickUpGoodsNo().toString());
        response.setData(dataBean);
        return response;
    }

    public BaseOrderResponse convent2BaseOrderResponse(OrderBaseResp baseResponse) {
        BaseOrderResponse response = new BaseOrderResponse();
        response.setErrcode(Integer.parseInt(baseResponse.getCode()));
        response.setErrmsg(baseResponse.getMessage());
        if (baseResponse.getResult() == null) {
            return response;
        }
        response.setData(baseResponse.getResult().toString());
        return response;
    }


    public OrderStatusTrackingInfoResponse convent2OrderStatusTrackingInfoResponse(OrderBaseResp<List<OrderTraceInfoResp>> baseResponse) {
        OrderStatusTrackingInfoResponse response = new OrderStatusTrackingInfoResponse();
        response.setErrcode(Integer.parseInt(baseResponse.getCode()));
        response.setErrmsg(baseResponse.getMessage());
        if (baseResponse.getResult() == null) {
            return response;
        }
        List<OrderTraceInfoResp> respList = mapper.mapAsList(baseResponse.getResult(), OrderTraceInfoResp.class);
        List<OrderStatusTrackingInfoResponse.OrderStatusTrackingInfo> trackingInfos = new ArrayList<>();
        for (OrderTraceInfoResp orderTraceInfoResp : respList) {
            OrderStatusTrackingInfoResponse.OrderStatusTrackingInfo trackingInfo = new OrderStatusTrackingInfoResponse.OrderStatusTrackingInfo();
            trackingInfo.setDesc(orderTraceInfoResp.getDescription());
            trackingInfo.setStatusName("");
            trackingInfo.setStatus(getOldStatus(orderTraceInfoResp.getTargetMasterState()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date statusTime = new Date(Long.parseLong(orderTraceInfoResp.getCreateTime()));
            trackingInfo.setStatusTime(sdf.format(statusTime));
            trackingInfos.add(trackingInfo);
        }
        response.setData(trackingInfos);
        return response;
    }


    /**
     * 转换订单优惠类型
     */
    public Integer getDiscountType(QueryOrderAccountType queryOrderAccountType) {
        //老订单服务订单优惠类型 2=满减优惠, 5=代金券, 6=商品券, 7=折扣券, 21=限时折扣金额,22=加价购,23=第二件N折,24=买M赠N,
        //0=其他优惠,1=新用户立减,2=满减,3=抵价券,4=套餐赠送,5=满赠,6=超时赔付,7=部分满减,9=使用红包,
        //10=代金券,11=提前下单立减活动,16=满免配送费,20=单品折扣,23=买赠,46=外卖加价购,47=超级加购,118=商品券,200=积分,
        //201=折扣,202=现金,203=微信,204=支付宝,205=优惠总金额,206=单品特价,207=买一送一,208=折扣券,215=会员卡优惠;
        // 新订单服务优惠类型枚举 OrderSettlementType
        Integer type = 0;
        String code = queryOrderAccountType.getCode();

        switch (code) {
            case "BUY_DISCOUNT":
                type = 2;
                break;
            case "COUPON":
                type = 10;
                break;
            case "B3S1_COUPON":
                type = 35;
                break;
            case "FREIGHT_COUPON":
                type = 99;
                break;
            case "PRODUCT_COUPON":
                type = 118;
                break;
            case "SEED_PRODUCT_COUPON":
                type = 37;
                break;
            case "EVM_PRODUCT_COUPON":
                type = 39;
                break;
            case "DISCOUNT_COUPON":
                type = 208;
                break;
            case "DISCOUNT_AMOUNT":
                type = 206;
                break;
            case "PREMIUM_EXCHANGE":
                type = 46;
                break;
            case "SUPER_PURCHASE":
                type = 47;
                break;
            case "SECOND_DISCOUNT":
                type = 20;
                break;
            case "BUYM_SENDN":
                type = 23;
                break;
            case "CUSTOMER_SCORE":
                type = 200;
                break;
            case "CARD_DISCOUNT_AMOUNT":
                type = 215;
                break;
            case "SET_MEAL":
                type = 211;
                break;
            case "XY_DISCOUNT":
                type = 104;
                break;
            case "TOTAL_DISCOUNT":
                type = 205;
                break;
            case "ONLINE_PAY":
                type = 218;
                break;
            case "OFFLINE_PAY":
                type = 219;
                break;
            case "FULL_DISTRIBUTION_FEE":
                type = 1014;
                break;
            case "MEMBER_PRICE_DISCOUNT":
                type = 220;
                break;
            case "GATHER_SPOT":
                type = 221;
                break;
            case "COCO_PRODUCT_CASH_COUPON":
                type = 36;
                break;
            case "FULL_BUYM_SENDN":
                type = 230;
                break;
            case "MONTH_CARD_TOTAL_DISCOUNT":
                type = 231;
                break;
            case "SINGLE_PRODUCT_REDUCTION":
                type = 22;
                break;
            case "FULL_M_COUNT_N_FOLD":
                type = 83;
                break;
            case "SCORE_PRODUCT_ACTIVITY":
                type = 28;
                break;
            default:
                break;
        }
        return type;
    }

    /**
     * 老订单类型转换新订单类型
     */
//    public Integer getNewOrderType(OrderTypeV1 orderType, Long gmtExpect, Integer bizType) {
//        //订单服务订单类型 1=外卖 4=自提，5=堂食
//        //外卖平台订单类型 1=常规堂食，2=预约堂食，3=常规外送，4=预约外送，5=常规自取，6=预约自取
//        boolean isAdvance = bizType != null && bizType.compareTo(BizTypeEnum.ADVANCE_ORDER.getBizType()) == 0;
//        Integer type = 0;
//        // 预定单 是额外的逻辑 --> 需要走实时单
//        if (isAdvance) {
//            switch (orderType) {
//                case TAKE_OUT:
//                    type = 3;
//                    break;
//                case COLLECT_GOODS:
//                    type = 5;
//                    break;
//                case EAT_IN:
//                    type = 1;
//                    break;
//                default:
//                    break;
//            }
//            return type;
//        }
//
//        switch (orderType) {
//            case TAKE_OUT:
//                if (gmtExpect == null || gmtExpect == 0L) {
//                    type = 3;
//                } else {
//                    type = 4;
//                }
//                break;
//            case COLLECT_GOODS:
//                if (gmtExpect == null || gmtExpect == 0L) {
//                    type = 5;
//                } else {
//                    type = 6;
//                }
//                break;
//            case EAT_IN:
//                if (gmtExpect == null || gmtExpect == 0L) {
//                    type = 1;
//                } else {
//                    type = 2;
//                }
//                break;
//            default:
//                break;
//        }
//
//        return type;
//    }

    /**
     * 新订单类型转换老订单类型
     */
    public Integer getOldOrderType(Integer type) {
        //订单服务订单类型 1=外卖 4=自提，5=堂食
        //外卖平台订单类型 1=常规堂食，2=预约堂食，3=常规外送，4=预约外送，5=常规自取，6=预约自取
        switch (type) {
            case 1:
                type = 5;
                break;
            case 2:
                type = 5;
                break;
            case 3:
                type = 1;
                break;
            case 4:
                type = 1;
                break;
            case 5:
                type = 4;
                break;
            case 6:
                type = 4;
                break;
            default:
                break;
        }

        return type;
    }

    public List<Integer> getNewOrderType(int type) {
        List<Integer> typeList = new ArrayList<>();
        if (5 == type) {
            typeList.add(1);
            typeList.add(2);
        } else if (1 == type) {
            typeList.add(3);
            typeList.add(4);
        } else if (4 == type) {
            typeList.add(5);
            typeList.add(6);
        }

        return typeList;
    }

    /**
     * 字符串渠道码转对应数字类型渠道码
     * saas->2
     *
     * @param name
     * @return
     */
    public Integer getNewOrderClient(String name) {
        Integer clientType = OrderSourceV1.getClientByCode(name);
        return clientType;
    }

    /**
     * 数字类型渠道码转字符类型渠道码
     * 2->saas
     *
     * @param orderClientType
     * @return
     */
    public String getOldSource(Integer orderClientType) {
        String name = OrderSourceV1.getCodeByClientType(orderClientType);
        return name;
    }

    /**
     * 数字类型渠道码转字符类型渠道码注释
     * 2-> saas 点餐
     *
     * @param orderClientType
     * @return
     */
    public String getOldSourceName(Integer orderClientType) {
        String name = OrderSourceV1.getDescByClientType(orderClientType);
        return name;
    }

    public Integer getOldStatus(Integer orderStatus) {
        //新订单服务 订单状态 1:待支付 2:下单 3:已接单 4:制作完成(待发货) 5:配送中 6:已完 7:已关闭
        switch (orderStatus) {
            case 1:
                orderStatus = 2;
                break;
            case 2:
                orderStatus = 1;
                break;
            case 4:
                orderStatus = 31;
                break;
            case 5:
                orderStatus = 4;
                break;
            case 6:
                orderStatus = 5;
                break;
            case 7:
                orderStatus = 6;
                break;
            default:
                break;
        }
        return orderStatus;
    }

    @Deprecated //使用订单枚举OrderStatusV1装换
    public Integer getNewOrderStatus(Integer orderStatus) {
        if (orderStatus == null) {
            return null;
        }
        //新订单服务 订单状态 1:待支付 2:下单 3:已接单 4:制作完成(待发货) 5:配送中 6:已完 7:已关闭
        switch (orderStatus) {
            case 1:
                orderStatus = 2;
                break;
            case 2:
                orderStatus = 1;
                break;
            case 4:
                orderStatus = 5;
                break;
            case 5:
                orderStatus = 6;
                break;
            case 6:
                orderStatus = 7;
                break;
            case 31:
                orderStatus = 4;
                break;
            default:
                break;
        }
        return orderStatus;
    }

//    /**
//     * 获取自定义信息
//     */
//    public OrderExtInfoDto getOrderExtInfo(OrderPayResponse orderPayResponse, OrderEditInfo orderEditInfo) {
//        OrderExtInfoDto orderExtInfoDto = new OrderExtInfoDto();
//        orderExtInfoDto.setOpenid(orderPayResponse.getOpenId());
//        String prepayId = "";
//        //TODO StringUtils 依赖修改
//        if (orderPayResponse.getPayOrder() != null && !StringUtils.isEmpty(orderPayResponse.getPayOrder().getPackageX())) {
//            String[] prepayIds = orderPayResponse.getPayOrder().getPackageX().split("=");
//            prepayId = prepayIds.length > 1 ? prepayIds[1] : "";
//        }
//        orderExtInfoDto.setPrepayId(prepayId);
//        orderExtInfoDto.setAppid(orderPayResponse.getWxAppid());
//        orderExtInfoDto.setExpireDate(orderEditInfo.getExpireDate());
//        orderExtInfoDto.setServiceTime(orderEditInfo.getServiceTime());
//        orderExtInfoDto.setPushOrderTime(orderEditInfo.getPushOrderTime());
//        orderExtInfoDto.setAccessToken(orderEditInfo.getAccessToken());
//        orderExtInfoDto.setSessionId(orderEditInfo.getSessionId());
//        orderExtInfoDto.setVersion(orderEditInfo.getVersion());
//        orderExtInfoDto.setTrackingNo(orderEditInfo.getTrackingNo());
//        return orderExtInfoDto;
//    }

    /**
     * 拉单返回参数转换
     */
    public QueryOrdersResponse convent2PullOrderResponse(OrderBaseResp baseResponse) {
        QueryOrdersResponse response = new QueryOrdersResponse();
        response.setErrcode(Integer.parseInt(baseResponse.getCode()));
        response.setErrmsg(baseResponse.getMessage());
        if (baseResponse.getResult() == null) {
            return response;
        }

        String json = JSONObject.toJSONString(baseResponse.getResult());
        JSONObject jsonObject = JSONObject.parseObject(json);
        PullOrderResponse queryOrderForUserResp = jsonObject.toJavaObject(PullOrderResponse.class);
        if (queryOrderForUserResp.getOrderPosRespList() == null || queryOrderForUserResp.getOrderPosRespList().size() == 0) {
            return response;
        }

        QueryOrdersResponse.DataBean dataBean = new QueryOrdersResponse.DataBean();
        dataBean.setCount(queryOrderForUserResp.getOrderPosRespList().size());
        List<OrderBeanV1> orders = new ArrayList<>();
        for (OrderInfoReqs orderInfoReqs : queryOrderForUserResp.getOrderPosRespList()) {
            OrderBeanV1 data = orderCenterSdkAdapter.convent2NEWOrderInfo(orderInfoReqs);
            orders.add(data);
        }
        dataBean.setUpdateTimestamp(queryOrderForUserResp.getUpdateTimestamp());
        dataBean.setOrders(orders);
        dataBean.setCount(orders.size());
        response.setData(dataBean);
        return response;
    }

    /**
     * 获取扣减库存信息
     *
     * @param orderBean       订单信息
     * @param products        订单商品列表
     * @param stockChangeType 库存改变类型
     * @return
     */
    public UpdateStocksRequest getUpdateProductStock(OrderBeanV1 orderBean, List<CreateOrderProductRequest> products, StockChangeType stockChangeType, String menuType) {
        UpdateStocksRequest updateStocksRequest = new UpdateStocksRequest();
        updateStocksRequest.setChannel(menuType);
        updateStocksRequest.setChangeType(stockChangeType.getCode());
        updateStocksRequest.setIsOversold(0);
        updateStocksRequest.setPartnerId(orderBean.getCompanyId());
        updateStocksRequest.setStoreId(orderBean.getShopId());
        updateStocksRequest.setTransNo(orderBean.getOid());
        updateStocksRequest.setTransTime(DateUtil.convert2String(new Date(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        List<ProductStocksVO> productStocks = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(products)) {
            products.forEach(product -> {
                if (product.getHasStockProudct() != null && product.getHasStockProudct()) {
                    ProductStocksVO productStocksVO = new ProductStocksVO();
                    productStocksVO.setProductId(product.getSpecification());
                    productStocksVO.setQty(product.getNumber());
                    productStocks.add(productStocksVO);

                }
            });
        }
        updateStocksRequest.setProductStocks(productStocks);
        return updateStocksRequest;
    }

    /**
     * 获取扣减库存信息
     *
     * @param orderBean       订单信息
     * @param products        订单商品列表
     * @param stockChangeType 库存改变类型
     * @return
     */
    public UpdateProductStockRequestDto getUpdateProductStockByFeign(OrderBeanV1 orderBean, List<CreateOrderProductRequest> products, StockChangeType stockChangeType, String menuType) {
        UpdateProductStockRequestDto updateStocksRequest = new UpdateProductStockRequestDto();
        updateStocksRequest.setChannel(menuType);
        updateStocksRequest.setChangeType(stockChangeType.getCode());
        updateStocksRequest.setIsOversold(0);
        updateStocksRequest.setPartnerId(orderBean.getCompanyId());
        updateStocksRequest.setStoreId(orderBean.getShopId());
        updateStocksRequest.setTransNo(orderBean.getOid());
        updateStocksRequest.setTransTime(DateUtil.convert2String(new Date(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        List<UpdateProductStockRequestDto.ProductStock> productStocks = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(products)) {
            /**
             *  别问代码为什么这么写  人家基础服务不处理这种逻辑
             *  本上扣什么库存 怎么扣 不应该由订单关注, 应该是商品服务自己去处理  反正我是挺无语的
             */
            products.forEach(product -> {
                // 套餐商品 基础服务为7 额外扣除库存逻辑
                if (Objects.nonNull(product.getOriginalProductType()) && ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode().compareTo(product.getOriginalProductType()) == 0) {
                    // 关联模式 把套餐传递过去 用于商品服务扣除 固定搭配的库存
                    if (product.getStockMode().compareTo(2) == 0) {
                        UpdateProductStockRequestDto.ProductStock productStocksVO = this.getProductStockVo(product);
                        productStocks.add(productStocksVO);
                    }else {
                        if (product.getHasStockProudct() != null && product.getHasStockProudct()) {
                            UpdateProductStockRequestDto.ProductStock productStocksVO = this.getProductStockVo(product);
                            productStocks.add(productStocksVO);
                        }
                    }
                    // 需要处理  过滤出 可选搭配
                    if (CollectionUtils.isNotEmpty(product.getComboProduct())) {
                        if (product.getStockMode().compareTo(2) == 0) {
                            product.getComboProduct().stream().filter(c -> !c.getIsFixedProduct()).forEach(groupProduct -> {
                                if (groupProduct.getHasStockProudct() != null && groupProduct.getHasStockProudct()) {
                                    UpdateProductStockRequestDto.ProductStock productStocksVO = this.getProductStockVo(groupProduct);
                                    productStocks.add(productStocksVO);
                                }
                            });
                        }

                    }
                } else {
                    if (product.getHasStockProudct() != null && product.getHasStockProudct()) {
                        UpdateProductStockRequestDto.ProductStock productStocksVO = this.getProductStockVo(product);
                        productStocks.add(productStocksVO);
                    }
                }
            });
        }
        updateStocksRequest.setProductStocks(productStocks);
        return updateStocksRequest;
    }

    private UpdateProductStockRequestDto.ProductStock getProductStockVo(CreateOrderProductRequest product) {
        UpdateProductStockRequestDto.ProductStock productStocksVO = new UpdateProductStockRequestDto.ProductStock();
        productStocksVO.setProductId(product.getSpecification());
        productStocksVO.setQty(product.getNumber());
        productStocksVO.setProductType(product.getOriginalProductType());
        return productStocksVO;
    }

    public ActivityUpdateStockRequest convert2ActivityUpdateStockRequest(OrderBeanV1 orderBean, ActivityUpdateStockRequest activityUpdateStockRequest) {
        if (activityUpdateStockRequest == null || orderBean == null) {
            return null;
        }
        activityUpdateStockRequest.setOrderId(orderBean.getOid());
        activityUpdateStockRequest.setPartnerCode(orderBean.getCompanyId());
        activityUpdateStockRequest.setStoreId(orderBean.getShopId());
        activityUpdateStockRequest.setVer("1");
        // add by miaohui 20201030 for 【ID1018638】【C端服务端】活动库存接口调整对接
        activityUpdateStockRequest.setUserId(orderBean.getUserId());
        activityUpdateStockRequest.setOrderCreateTime(DateUtil.getCurrentDate(DateUtil.FORMAT_yyyyMMdd_date));
        return activityUpdateStockRequest;
    }

    public ActivityUpdateStockRequest convert2ActivityUpdateStockRequest(OrderBeanV1 orderBean,
                                                                         List<SubtractStockVO> stockBeanDtos) {
        if (orderBean == null || CollectionUtils.isEmpty(stockBeanDtos)) {
            return null;
        }
        List<String> activityList = new ArrayList<>();
        // 只记录订单级别的活动ID
        if (CollectionUtils.isNotEmpty(stockBeanDtos)) {
            activityList.addAll(stockBeanDtos.stream().filter(ad -> StringUtils.isNotBlank(ad.getActivityCode())).map(SubtractStockVO::getActivityCode).distinct().collect(Collectors.toList()));
        }
        ActivityUpdateStockRequest updateStockRequest = new ActivityUpdateStockRequest();
        updateStockRequest.setStock(stockBeanDtos);
        updateStockRequest.setActivityList(activityList);
        updateStockRequest.setOrderId(orderBean.getOid());
        updateStockRequest.setPartnerCode(orderBean.getCompanyId());
        updateStockRequest.setStoreId(orderBean.getShopId());
        updateStockRequest.setVer("1");
        updateStockRequest.setUserId(orderBean.getUserId());
        updateStockRequest.setOrderCreateTime(DateUtil.getCurrentDate(DateUtil.FORMAT_yyyyMMdd_date));
        return updateStockRequest;
    }

    /**
     * 订单下载转换对象
     */
    public OrderConditionsReq convent2OrderConditionsReq(OrderDownloadRequest request) {
        OrderConditionsReq req = new OrderConditionsReq();
        req.setPartnerId(request.getCompanyId());
        Long startDate = DateUtil.convert2Date(request.getStartDate(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS).getTime() / 1000;
        Long endDate = DateUtil.convert2Date(request.getEndDate(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS).getTime() / 1000;
        req.setStartTimestamp(startDate);
        req.setEndTimestamp(endDate);
        req.setOrderCode(request.getOrderId());
        if (request.getOrderStatus() != null) {
            req.setOrderStatus(getNewOrderStatus(Integer.parseInt(request.getOrderStatus())));
        }
        List<Integer> orderTypes = new ArrayList<Integer>();
        //外卖
        if (Objects.equals(request.getOrderType(), OrderTypeV1.TAKE_OUT.getCode())) {
            orderTypes.add(OrderType.GENERAL_EXPRESS.getIndex());
            orderTypes.add(OrderType.RESERVED_EXPRESS.getIndex());
        }
        //自提
        if (Objects.equals(request.getOrderType(), OrderTypeV1.COLLECT_GOODS.getCode())) {
            orderTypes.add(OrderType.GENERAL_SELF_PICKUP.getIndex());
            orderTypes.add(OrderType.RESERVED_SELF_PICKUP.getIndex());
        }
        //堂食
        if (Objects.equals(request.getOrderType(), OrderTypeV1.EAT_IN.getCode())) {
            orderTypes.add(OrderType.GENERAL_DINE_IN.getIndex());
            orderTypes.add(OrderType.RESERVED_DINE_IN.getIndex());
        }
        req.setOrderTypes(orderTypes);
        List<Integer> orderClients = new ArrayList<Integer>();
        orderClients.add(getNewOrderClient(request.getSource()));
        req.setOrderClients(orderClients);
        req.setPageNum(request.getPageNumber());
        req.setPageSize(request.getPageSize());
        req.setMobile(request.getPhoneNo());
        req.setStoreIds(request.getShopIds());
        req.setUserName(request.getUserName());
        if (request.getRefundStatus() != null) {
            req.setAfterSalesStatus(Integer.valueOf(request.getRefundStatus()));
        }
        //支付状态条件查询
        if (CollectionUtils.isNotEmpty(request.getPayStatuses())) {
            req.setPayStatuses(request.getPayStatuses());
        }
        return req;
    }

    /**
     * 转换订单下载对象
     */
    public OrderDownloadResponse convent2OrderDownloadResponse(OrderBaseResp<QueryOrderForUserResp> response) {
        OrderDownloadResponse orderDownloadResponse = new OrderDownloadResponse();
        orderDownloadResponse.setErrmsg(response.getMessage());
        orderDownloadResponse.setErrcode(Integer.valueOf(response.getCode()));
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, response.getCode())) {
            return orderDownloadResponse;
        }
        if (response.getResult() != null && CollectionUtils.isNotEmpty(response.getResult().getItemList())) {
            List<OrderDownloadResponse.OrderDownload> data = convent2OrderDownloads(response.getResult().getItemList());
            orderDownloadResponse.setData(data);
            orderDownloadResponse.setTotalNum(response.getResult().getTotal());
        }
        return orderDownloadResponse;
    }

    /**
     * 判断是否是活动类型，决定是否扣除活动库存
     *
     * @param queryOrderAccountType
     * @return
     */
    public boolean isActivityTypes(QueryOrderAccountType queryOrderAccountType) {
        if (QueryOrderAccountType.BUY_DISCOUNT.equals(queryOrderAccountType) || QueryOrderAccountType.DISCOUNT_AMOUNT.equals(queryOrderAccountType)
                || QueryOrderAccountType.PREMIUM_EXCHANGE.equals(queryOrderAccountType)
                || QueryOrderAccountType.BUYM_SENDN.equals(queryOrderAccountType)) {
            return true;
        }
        return false;
    }

    /**
     * 下载数据转换
     *
     * @param orderDtos
     * @return
     */
    public List<OrderDownloadResponse.OrderDownload> convent2OrderDownloads(List<OrderInfoReqs> orderDtos) {
        List<OrderDownloadResponse.OrderDownload> downloads = new ArrayList<>();
        orderDtos.forEach(orderDto -> {
            OrderDownloadResponse.OrderDownload download = new OrderDownloadResponse.OrderDownload();
            download.setIgnoreProductPrice(1);
            download.setOid(orderDto.getOrderCode());
            download.setShopId(orderDto.getStoreId());
            download.setShopName(orderDto.getStoreName());
            download.setUserName(orderDto.getUserName());
            download.setSource(getOldSource(orderDto.getOrderClient()));
            download.setType(orderDto.getOrderType());
            download.setTypeStr(getNewOrderTypeDesc(orderDto.getOrderType()));
            download.setStatus(orderDto.getOrderState());
            download.setStatusStr(getNewOrderStatusDesc(orderDto.getOrderState()));
            download.setOrderAmount(orderDto.getOriginalAmount().intValue());
            download.setOrderAmountYuan(orderDto.getOriginalAmount().doubleValue() / 100);
            download.setAmount(orderDto.getSettlementAmount().intValue());
            download.setAmountYuan(orderDto.getSettlementAmount().doubleValue() / 100);
            download.setThirdOrderCode(orderDto.getThirdOrderCode());

            Integer packageFee = 0;
            Integer deliveryFee = 0;
            if (CollectionUtils.isNotEmpty(orderDto.getOrderCostDetailList())) {
                for (OrderCostResp detail : orderDto.getOrderCostDetailList()) {
                    //新订单服务  1=包装费,2=运费,3=餐盒单价,4=餐盒数量
                    if (detail.getCostType() == 1) {
                        packageFee = detail.getCostAmount().intValue();
                    }
                    if (detail.getCostType() == 2) {
                        deliveryFee = detail.getCostAmount().intValue();
                    }
                }
            }
            download.setPackageFee(packageFee);
            download.setPackageFeeYuan(packageFee.doubleValue() / 100);
            download.setDeliveryFee(deliveryFee);
            download.setDeliveryFeeYuan(deliveryFee.doubleValue() / 100);
            //是否是外卖
            boolean isTakeOut = OrderClientType.ELEME.getIndex() == orderDto.getOrderClient() || OrderClientType.EBAI.getIndex() == orderDto.getOrderClient() || OrderClientType.JD.getIndex() == orderDto.getOrderClient()
                    || OrderClientType.MEITUAN.getIndex() == orderDto.getOrderClient();
            Integer activityPrice = 0;
            String activeItem = "";
            for (OrderSettlementResp dto : orderDto.getOrderSettlementDetailList()) {
                if (205 != dto.getSettlementType() && (StringUtils.isEmpty(dto.getProductId()) || ObjectUtils.equals("0", dto.getProductId()))) {
                    if (dto.getSettlementAmount() != null) {
                        activityPrice += dto.getSettlementAmount().intValue();
                    }
                    activeItem = activeItem + " " + (isTakeOut ? dto.getExternalObjectName() : dto.getNote());
                }
            }
            download.setAcitviyCost(activityPrice);
            download.setAcitviyCostYuan(activityPrice.doubleValue() / 100);
            download.setAcivityItems(activeItem);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date gmtCreate = null;
            Date gmtPay = null;
            try {
                if (orderDto.getCreateTime() != null) {
                    gmtCreate = sdf.parse(sdf.format(Long.valueOf(orderDto.getCreateTime())));
                }
                if (orderDto.getPayTime() != null) {
                    gmtPay = sdf.parse(sdf.format(Long.valueOf(orderDto.getPayTime())));
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }

            download.setGmtCreate(gmtCreate);
            download.setGmtPay(gmtPay);

            download.setPayNo(orderDto.getPayRequestNo());
            //支付状态描述
            download.setPayStatus(PayStatusEnum.getByCode(orderDto.getPayState()).getDesc());

            if (CollectionUtils.isNotEmpty(orderDto.getDeliveryContactInfoList())) {
                boolean isThirdDelivery = false;
                for (DeliveryContactInfoResp info : orderDto.getDeliveryContactInfoList()) {
                    //地址类型 1:订单地址 2:售后单地址 3:配送员信息
                    if (1 == info.getRelateObjectType()) {
                        download.setPhone(info.getMobile());
                        download.setAddress(info.getAddressDetail());
                    }
                    if (3 == info.getRelateObjectType()) {
                        isThirdDelivery = true;
                        download.setRiderName(info.getContactsName());
                        download.setRiderPhone(info.getMobile());
                    }
                }
                if (ObjectUtils.equals(orderDto.getOrderType(), OrderType.GENERAL_EXPRESS.getIndex()) || ObjectUtils.equals(orderDto.getOrderType(), OrderType.RESERVED_EXPRESS.getIndex())) {
                    download.setDeliveryId(orderDto.getExpressNo());
                    download.setExpress(StringUtils.isEmpty(orderDto.getExpressChannelName()) && !isThirdDelivery ? "自配送" : orderDto.getExpressChannelName());
                    if (isThirdDelivery && StringUtils.isEmpty(orderDto.getExpressChannelName())) {
                        download.setExpress("三方配送");
                    }
                }
            }


            String prodNameList = "";
            String prodIds = "";
            Integer prodPrice = 0;
            int i = 0;

            for (OrderItemResp orderItemDto : orderDto.getOrderItemList()) {

                prodNameList += (isTakeOut ? orderItemDto.getProductName() : orderItemDto.getProductSpecName()) + "*" + orderItemDto.getProductQuantity();
                prodIds += orderItemDto.getProductId();
                prodPrice += orderItemDto.getProductPrice() == null ? 0 : orderItemDto.getProductPrice().intValue() * orderItemDto.getProductQuantity();

                ++i;

                if (i < orderDto.getOrderItemList().size()) {
                    prodNameList += ",";
                    prodIds += ",";
                }
            }
            download.setProductName(prodNameList);

            download.setProductId(prodIds);
            download.setProductNumber("0");
            download.setProductPrice(prodPrice);
            download.setProductPriceYuan(prodPrice.doubleValue() / 100);
            download.setProductDiscountAmountYuan(0.0);

            download.setProductAmount(prodPrice);
            download.setProductAmountYuan(prodPrice.doubleValue() / 100);
            if (orderDto.getOrderExtended() != null) {
                download.setOrganizationName(orderDto.getOrderExtended().getOrderClientGroup());
            }
            downloads.add(download);
        });
        return downloads;
    }

    /**
     * 每日营业额 参数转化
     *
     * @param request
     * @return
     */
    public StoreOrderStatisticReq convent2GetStatisticStoreOrderReportRequest(GetStatisticStoreOrderReportRequest request) {
        StoreOrderStatisticReq storeOrderStatisticReq = new StoreOrderStatisticReq();
        storeOrderStatisticReq.setPartnerId(request.getCompanyId());
        storeOrderStatisticReq.setStoreId(request.getShopId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = new Date(request.getStartTime());
        Date endDate = new Date(request.getEndTime());
        storeOrderStatisticReq.setStartTime(sdf.format(startDate));
        storeOrderStatisticReq.setEndTime(sdf.format(endDate));
        storeOrderStatisticReq.setOrderClient(OrderClientType.SAAS.getIndex());
        //新老订单状态转化
        List<Integer> stateList = new ArrayList<>();
        for (Integer i : request.getStatusList()) {
            stateList.add(getNewOrderStatus(i));
        }
        storeOrderStatisticReq.setStateList(stateList);
        return storeOrderStatisticReq;
    }

    public GetStatisticStoreOrderReportResponse convent2GetStatisticStoreOrderReportResponse(OrderBaseResp<StoreOrderStatisticResp> result) {
        GetStatisticStoreOrderReportResponse response = new GetStatisticStoreOrderReportResponse();
        response.setErrcode(Integer.parseInt(result.getCode()));
        response.setErrmsg(result.getMessage());
        if (result.getResult() == null) {
            return response;
        }
        GetStatisticStoreOrderReportResponse.StatisticStoreOrderReport data = new GetStatisticStoreOrderReportResponse.StatisticStoreOrderReport();
        data.setOrderCount(result.getResult().getOrderCount() == null ? null : result.getResult().getOrderCount().longValue());
        data.setTotalAmount(result.getResult().getTotalAmount() == null ? null : result.getResult().getTotalAmount().longValue());
        response.setData(data);
        return response;
    }

    /**
     * 新订单优惠活动类型转老订单
     *
     * @return
     */
    public Integer getOldOrderAccountType(int newOrderAccountType) {
        // 新订单服务枚举 OrderSettlementType
        switch (newOrderAccountType) {
            case 1:
                newOrderAccountType = OldOrderAccountType.NEW_USER_DISCOUNT.getCode();
                break;
            case 2:
                newOrderAccountType = OldOrderAccountType.BUY_DISCOUNT.getCode();
                break;
            case 3:
                newOrderAccountType = OldOrderAccountType.PRICE_DEDUCTION_COUPON.getCode();
                break;
            case 10:
                newOrderAccountType = OldOrderAccountType.COUPON.getCode();
                break;
            case 118:
                newOrderAccountType = OldOrderAccountType.PRODUCT_COUPON.getCode();
                break;
            case 37:
                newOrderAccountType = OldOrderAccountType.SEED_PRODUCT_COUPON.getCode();
                break;
            case 39:
                newOrderAccountType = OldOrderAccountType.EVM_PRODUCT_COUPON.getCode();
                break;
            case 208:
                newOrderAccountType = OldOrderAccountType.DISCOUNT_COUPON.getCode();
                break;
            case 206:
                newOrderAccountType = OldOrderAccountType.DISCOUNT_AMOUNT.getCode();
                break;
            case 46:
                newOrderAccountType = OldOrderAccountType.PREMIUM_EXCHANGE.getCode();
                break;
            case 20:
                newOrderAccountType = OldOrderAccountType.SECOND_DISCOUNT.getCode();
                break;
            case 23:
                newOrderAccountType = OldOrderAccountType.BUYM_SENDN.getCode();
                break;
            case 200:
                newOrderAccountType = OldOrderAccountType.CUSTOMER_SCORE.getCode();
                break;
            case 215:
                newOrderAccountType = OldOrderAccountType.CARD_DISCOUNT_AMOUNT.getCode();
                break;
            case 211:
                newOrderAccountType = OldOrderAccountType.SET_MEAL.getCode();
                break;
            case 104:
                newOrderAccountType = OldOrderAccountType.XY_DISCOUNT.getCode();
                break;
            case 205:
                newOrderAccountType = OldOrderAccountType.TOTAL_DISCOUNT.getCode();
                break;
            case 220:
                newOrderAccountType = OldOrderAccountType.MEMBER_PRICE_DISCOUNT.getCode();
                break;
            case 99:
                newOrderAccountType = OldOrderAccountType.FREIGHT_COUPON.getCode();
                break;
            case 36:
                newOrderAccountType = OldOrderAccountType.COCO_PRODUCT_CASH_COUPON.getCode();
                break;
            case 230:
                newOrderAccountType = OldOrderAccountType.FULL_BUYM_SENDN.getCode();
                break;
            case 231:
                newOrderAccountType = OldOrderAccountType.MONTH_CARD_TOTAL_DISCOUNT.getCode();
                break;
            case 22:
                newOrderAccountType = OldOrderAccountType.SINGLE_PRODUCT_REDUCTION.getCode();
                break;
            default:
                break;
        }
        return newOrderAccountType;
    }

    /**
     * 转换订单优惠类型
     */
    public Integer getNewDiscountType(Integer type) {
        //老订单类型枚举类 QueryOrderAccountType
        switch (type) {
            case 2:
                type = 2;
                break;
            case 5:
                type = 10;
                break;
            case 6:
                type = 118;
                break;
            case 7:
                type = 208;
                break;
            case 21:
                type = 206;
                break;
            case 22:
                type = 46;
                break;
            case 23:
                type = 20;
                break;
            case 24:
                type = 23;
                break;
            default:
                break;
        }
        return type;
    }

    /**
     * 退款状态转换
     *
     * @param newOrderAfterSalesStatus
     * @return
     */
    private Integer getOldOrderRefundStatus(Integer newOrderAfterSalesStatus) {
        //售后单状态 1:待处理 2:退货中 3:拒绝退款 4:已退货 5:完成 6:取消
        //退款状态  1 申请退款 2 同意退款 3 已退货 4 退款完成 5 拒绝退款
        switch (newOrderAfterSalesStatus) {
            case 1:
                newOrderAfterSalesStatus = 1;
                break;
            case 2:
                newOrderAfterSalesStatus = 2;
                break;
            case 3:
                newOrderAfterSalesStatus = 5;
                break;
            case 4:
                newOrderAfterSalesStatus = 3;
                break;
            case 5:
                newOrderAfterSalesStatus = 4;
                break;
            case 6:
                newOrderAfterSalesStatus = 6;
                break;
            default:
                break;
        }
        return newOrderAfterSalesStatus;
    }

    public String getNewOrderTypeDesc(Integer orderType) {
        String name = "";
        //外卖平台订单类型 1=常规堂食，2=预约堂食，3=常规外送，4=预约外送，5=常规自取，6=预约自取
        switch (orderType) {
            case 1:
                name = "常规堂食";
                break;
            case 2:
                name = "常规堂食";
                break;
            case 3:
                name = "常规外卖";
                break;
            case 4:
                name = "预约外卖";
                break;
            case 5:
                name = "常规自取";
                break;
            case 6:
                name = "预约自取";
                break;
            default:
                break;
        }
        return name;
    }


    public String getNewOrderStatusDesc(Integer orderStatus) {
        String name = "";
        //新订单服务 订单状态 1:待支付 2:下单 3:已接单 4:制作完成(待发货) 5:配送中 6:已完 7:已关闭
        switch (orderStatus) {
            case 1:
                name = "待支付";
                break;
            case 2:
                name = "下单";
                break;
            case 3:
                name = "已接单";
                break;
            case 4:
                name = "制作完成";
                break;
            case 5:
                name = "配送中";
                break;
            case 6:
                name = "完成";
                break;
            case 7:
                name = "已关闭";
                break;
            default:
                break;
        }
        return name;
    }


    /**
     * 组装活动号查询订单信息请求参数
     */
    public OrderDiscountReq convent2OrderDiscountReq(QueryOrdersByConditionsRequest request) {
        OrderDiscountReq orderDiscountReq = new OrderDiscountReq();

        orderDiscountReq.setPartnerId(request.getCompanyId());
        orderDiscountReq.setPageSize(request.getPageSize());
        orderDiscountReq.setPageNum(request.getPageNumber());
        //外部对象ID 如:活动ID
        List<String> externalObjectIds = new ArrayList<>();
        externalObjectIds.add(request.getDiscountId());
        orderDiscountReq.setExternalObjectIds(externalObjectIds);
        //结算类型 0:其他优惠 1:新用户立减 2:满减……
        List<Integer> settlementTypes = new ArrayList<>();
        for (Integer discountType : request.getDiscountTypes()) {
            settlementTypes.add(getNewDiscountType(discountType));
        }
        orderDiscountReq.setSettlementTypes(settlementTypes);
        orderDiscountReq.setStoreIds(request.getShopIds());
//        List<Integer> orderClients = new ArrayList<>();
        orderDiscountReq.setStartTime(request.getStartDate());
        orderDiscountReq.setEndTime(request.getEndDate());
        return orderDiscountReq;
    }

    /**
     * 组装查询退款单信息请求参数
     *
     * @param request
     * @return
     */
    public OrderRefundQueryReq convent2OrderRefundReq(QueryRefundOrdersRequest request) {
        OrderRefundQueryReq refundQueryReq = new OrderRefundQueryReq();
        refundQueryReq.setCreateTimeStart(DateFormatUtils.format(request.getStartTimestamp(), "yyyy-MM-dd HH:mm:ss"));
        refundQueryReq.setCreateTimeEnd(DateFormatUtils.format(request.getEndTimestamp(), "yyyy-MM-dd HH:mm:ss"));
        refundQueryReq.setStoreId(request.getStoreId());
        refundQueryReq.setPartnerId(request.getPartnerId());
        refundQueryReq.setAfterSalesStatusList(request.getRefundstatus());
        refundQueryReq.setPageNum(request.getPageNum());
        refundQueryReq.setPageSize(request.getPageSize());
        refundQueryReq.setOrderBy(request.getOrderBy());
        refundQueryReq.setCustomerMobile(request.getPhone());//手机号查询
        refundQueryReq.setOrderCode(request.getOrderId());//订单号
        refundQueryReq.setOrderStateList(request.getOrderStateList());
        refundQueryReq.setAfterSalesTypeList(request.getAfterSalesTypeList());
        return refundQueryReq;
    }

    public BatchQueryAfterSalesReq convent2BatchQueryAfterSalesReq(BatchQueryAfterSalesRequest request) {
        BatchQueryAfterSalesReq batchQueryAfterSalesReq = new BatchQueryAfterSalesReq();
        batchQueryAfterSalesReq.setStartTimestamp(request.getStartTimestamp());
        batchQueryAfterSalesReq.setEndTimestamp(request.getEndTimestamp());
        batchQueryAfterSalesReq.setPartnerId(request.getPartnerId());
        batchQueryAfterSalesReq.setStoreId(request.getStoreId());
        batchQueryAfterSalesReq.setAfterSalesStatues(request.getRefundstatus());
        batchQueryAfterSalesReq.setCount(request.getCount());
        return batchQueryAfterSalesReq;
    }

    /**
     * 组装批量订单状态查询参数请求
     *
     * @param request
     * @return
     */
    public QueryOrdersStateReq convent2BatchQueryOrderState(BatchOrdersStateRequest request) {
        QueryOrdersStateReq stateReq = new QueryOrdersStateReq();
        stateReq.setOrderCodes(request.getOrderCodes());
        stateReq.setPartnerId(request.getPartnerId());
        return stateReq;
    }

    /**
     * 组装批量订单状态查询响应
     *
     * @param baseResponse
     * @return
     */
    public BatchOrdersStateResponse convent2BatchQueryOrderStateResp(OrderBaseResp<List<QueryOrderStateResp>> baseResponse, BatchOrdersStateResponse response) {
        List<OrderStatesVO> orderStatesVOList = new ArrayList<>();
        if (baseResponse.getResult() != null) {
            for (QueryOrderStateResp queryOrderStateResp : baseResponse.getResult()) {
                OrderStatesVO orderStatesVO = new OrderStatesVO();
                orderStatesVO.setOrderCode(queryOrderStateResp.getOrderCode());
                Integer oldOrderStatus = getOldStatus(queryOrderStateResp.getOrderState());
                orderStatesVO.setOrderStatus(oldOrderStatus != null ? oldOrderStatus.toString() : "");
                orderStatesVOList.add(orderStatesVO);
            }
        }
        response.setItemList(orderStatesVOList);
        response.setErrCode(baseResponse.getCode() == null ? null : Integer.valueOf(baseResponse.getCode()));
        response.setErrMsg(baseResponse.getMessage());
        return response;
    }

    /**
     * 组装基础SDK中POS拉单所使用的请求
     *
     * @param batchQueryRequest
     * @return
     */
    public BatchQueryReq convent2BatchQueryReq(BatchQueryRequest batchQueryRequest) {
        BatchQueryReq request = new BatchQueryReq();
        if (batchQueryRequest == null) {
            return request;
        }
        request.setPartnerId(batchQueryRequest.getPartnerId());
        request.setStoreId(batchQueryRequest.getStoreId());
        request.setStartTimestamp(batchQueryRequest.getStartTimestamp());
        request.setEndTimestamp(batchQueryRequest.getEndTimestamp());
        request.setCount(batchQueryRequest.getCount());
        request.setNextOrderCode(batchQueryRequest.getNextOrderCode());
        request.setOrderClients(batchQueryRequest.getOrderClients());
        List<Integer> statues = new ArrayList<>();
        for (Integer state : batchQueryRequest.getOrderStatus()) {
            Integer statue = getNewOrderStatus(state);
            statues.add(statue);
        }
        request.setOrderStatuses(statues);
        return request;
    }

    /**
     * 组装聚合SDK中POS拉单所返回的响应
     *
     * @param baseResponse
     * @return
     */
    public BatchQueryResponse convent2BatchQueryResponse(OrderBaseResp<BatchQueryResp> baseResponse) {
        BatchQueryResponse response = new BatchQueryResponse();
        if (baseResponse == null) {
            return response;
        }
        response.setVer(baseResponse.getVer());
        response.setCode(baseResponse.getCode());
        response.setMessage(baseResponse.getMessage());
        BatchQueryResp result = baseResponse.getResult();
        if (result == null) {
            return response;
        }

        response.setPageNum(result.getPageNum());
        response.setPageSize(result.getPageSize());
        response.setPages(result.getPages());
        response.setTotal(result.getTotal());
        response.setNextOrderCode(result.getNextOrderCode());
        response.setNextStartTimestamp(result.getNextStartTimestamp());
        List<OrderBeanV1> itemList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(result.getItemList())) {
            for (OrderInfoReqs orderInfoReqs : result.getItemList()) {
                OrderBeanV1 orderBean = orderCenterSdkAdapter.convent2NEWOrderInfo(orderInfoReqs);
                itemList.add(orderBean);
            }
        }
        response.setItemList(itemList);

        return response;

    }

    /**
     * 积分扣减或冲正
     *
     * @param orderBean 订单
     * @param accounts  订单优惠明细
     * @param isReduce  是否扣减：true扣减；false冲正
     * @return
     */
    public UserScoreRequest convent2UserScoreRequest(OrderBeanV1 orderBean, List<CreateOrderAccountRequest> accounts, boolean isReduce) {
        if (CollectionUtils.isEmpty(accounts)) {
            return null;
        }
        Optional<CreateOrderAccountRequest> accountRequest = accounts.stream().filter(account -> account.getAccountType().getCode().equals(QueryOrderAccountType.CUSTOMER_SCORE.getCode())).findFirst();
        if (!accountRequest.isPresent() || accountRequest.get().getPrice() == 0) {
            return null;
        }
        UserScoreRequest userScoreRequest = new UserScoreRequest();
        userScoreRequest.setMemberId(orderBean.getUserId());
        userScoreRequest.setPartnerId(orderBean.getCompanyId());
        userScoreRequest.setReduceAmount(accountRequest.get().getPrice().intValue() * -1);
        userScoreRequest.setScoreOrderNo(orderBean.getOid());
        userScoreRequest.setChangeType(isReduce ? 2 : 1);
        userScoreRequest.setOperationType(isReduce ? 14 : 2);
        userScoreRequest.setStoreId(orderBean.getShopId());
        return userScoreRequest;
    }

    public CouponRequest convert2CouponVerificationRequest(OrderBeanV1 orderBean, List<CreateOrderAccountRequest> accounts) {
        if (CollectionUtils.isEmpty(accounts)) {
            return null;
        }
        Optional<CreateOrderAccountRequest> accountRequest = accounts.stream().filter(account -> account.getAccountType().equals(QueryOrderAccountType.COUPON) || account.getAccountType().equals(QueryOrderAccountType.PRODUCT_COUPON)
                || account.getAccountType().equals(QueryOrderAccountType.DISCOUNT_COUPON)).findFirst();
        if (!accountRequest.isPresent() || accountRequest.get().getPrice() == 0) {
            return null;
        }
        CreateOrderAccountRequest accountBean = accountRequest.get();
        List<ProductRedeemVO> products = new ArrayList<>();
        //商品券核销核销参数
        if (QueryOrderAccountType.PRODUCT_COUPON.equals(accountBean.getAccountType())) {
            for (int i = 0; i < orderBean.getProductList().size(); i++) {
                ProductBeanV1 productBean = orderBean.getProductList().get(i);
                String pid = StringUtils.isNotBlank(productBean.getSpecification()) ? productBean.getSpecification() : productBean.getProductId();
                if (!org.springframework.util.CollectionUtils.isEmpty(orderBean.getProductList().get(i).getDiscountList())) {
                    List<ProductDiscountV1> discounts = orderBean.getProductList().get(i).getDiscountList().stream().
                            filter(productDiscount -> productDiscount.getDiscountId().equals(accountBean.getAccountId())).collect(Collectors.toList());
                    for (ProductDiscountV1 productDiscount : discounts) {
                        if (productDiscount.getDiscountType() == null || productDiscount.getDiscountType() == 0) {
                            continue;
                        }
                        ProductRedeemVO couponCodeVerificationProductDto = new ProductRedeemVO();
                        couponCodeVerificationProductDto.setPid(pid);
                        couponCodeVerificationProductDto.setConsume_num(productDiscount.getDiscountQty());
                        couponCodeVerificationProductDto.setSeq(i + 1);
                        products.add(couponCodeVerificationProductDto);
                    }
                }
            }
        }
        ActivityChannelEnum activityChannelEnum = Objects.equals(OrderTypeV1.TAKE_OUT.getCode(), orderBean.getOrderType()) ? ActivityChannelEnum.delivery : ActivityChannelEnum.pickup;
        CouponRequest couponCodeVerificationDto = new CouponRequest();
        couponCodeVerificationDto.setVer(Integer.valueOf(Version.VERSION_1));
        couponCodeVerificationDto.setReqtype(71);
        couponCodeVerificationDto.setPartnerId(Integer.parseInt(orderBean.getCompanyId()));
        couponCodeVerificationDto.setChannel(activityChannelEnum.getCode());
        couponCodeVerificationDto.setStation_id("-1");
        couponCodeVerificationDto.setOperator_id("-1");
        couponCodeVerificationDto.setStore_id(orderBean.getShopId());
        //核销不需要核销通知
        couponCodeVerificationDto.setAppFlag("kgd.N");
        // 订单号 替换成唯一序号
        couponCodeVerificationDto.setTrans_id(orderBean.getOid());
        couponCodeVerificationDto.setBusiness_date(cn.freemud.base.util.DateUtil.convert2Str(new Date(), cn.freemud.base.util.DateUtil.FORMAT_yyyyMMdd));
        List<TransactionVO> transactions = new ArrayList<>();
        TransactionVO couponCodeVerificationTransDto = new TransactionVO();
        couponCodeVerificationTransDto.setCode(accountBean.getAccountId());
        couponCodeVerificationTransDto.setTotalAmount(-accountBean.getPrice());
        if (CollectionUtils.isNotEmpty(products)) {
            couponCodeVerificationTransDto.setProducts(products);
        }
        transactions.add(couponCodeVerificationTransDto);
        couponCodeVerificationDto.setTransactions(transactions);
        return couponCodeVerificationDto;

    }

    public Integer getOldRefoundStatus(Integer refoundStatus) {
        if (refoundStatus == null) {
            return null;
        }
        //售后单状态 1:待处理 2:退货中 3:拒绝退款 4:已退货 5:完成 6:取消
        //退款状态  1 申请退款 2 同意退款 3 已退货 4 退款完成 5 拒绝退款
        switch (refoundStatus) {
            case 1:
                refoundStatus = 1;
                break;
            case 2:
                refoundStatus = 2;
                break;
            case 5:
                refoundStatus = 3;
                break;
            case 3:
                refoundStatus = 4;
                break;
            case 4:
                refoundStatus = 5;
                break;
            default:
                break;
        }
        return refoundStatus;
    }

    public QueryRelatedOrderByCodeReq convert2QueryRelatedOrderByCodeRequest(QueryRelatedOrderByCodeRequest request) {
        QueryRelatedOrderByCodeReq queryRelatedOrderByCodeReq = new QueryRelatedOrderByCodeReq();
        queryRelatedOrderByCodeReq.setOrderClient(request.getOrderClient());
        queryRelatedOrderByCodeReq.setOrderCode(request.getOrderCode());
        queryRelatedOrderByCodeReq.setThirdOrderCode(request.getThirdOrderCode());
        queryRelatedOrderByCodeReq.setWithOperationHistory(request.getWithOperationHistory());
        queryRelatedOrderByCodeReq.setPartnerId(request.getPartnerId());
        return queryRelatedOrderByCodeReq;
    }

    public SdkNewOrderUpdateThirdOrderCodeReq convert2NewOrderUpdateThirdOrderCodeReq(AssortmentSdkUpdateThirdOrderCodeRequest assortmentSdkUpdateThirdOrderCodeRequest) {
        SdkNewOrderUpdateThirdOrderCodeReq sdkNewOrderUpdateThirdOrderCodeReq = new SdkNewOrderUpdateThirdOrderCodeReq();
        sdkNewOrderUpdateThirdOrderCodeReq.setOrderCode(assortmentSdkUpdateThirdOrderCodeRequest.getOrderCode());
        sdkNewOrderUpdateThirdOrderCodeReq.setThirdOrderCode(assortmentSdkUpdateThirdOrderCodeRequest.getThirdOrderCode());
        sdkNewOrderUpdateThirdOrderCodeReq.setPartnerId(assortmentSdkUpdateThirdOrderCodeRequest.getPartnerId());
        return sdkNewOrderUpdateThirdOrderCodeReq;
    }

    public UpdateDownstreamOrderCodeReq convert2NewOrderUpdateDownstreamThirdOrderCodeReq(AssortmentSdkUpdateDownstreamThirdOrderCodeRequest assortmentSdkUpdateDownstreamThirdOrderCodeRequest) {
        UpdateDownstreamOrderCodeReq codeReq = new UpdateDownstreamOrderCodeReq();
        codeReq.setOrderCode(assortmentSdkUpdateDownstreamThirdOrderCodeRequest.getOrderCode());
        codeReq.setDownstreamPosCode(assortmentSdkUpdateDownstreamThirdOrderCodeRequest.getDownstreamPosCode());
        codeReq.setDownstreamThirdOrderCode(assortmentSdkUpdateDownstreamThirdOrderCodeRequest.getDownstreamThirdOrderCode());
        codeReq.setPartnerId(assortmentSdkUpdateDownstreamThirdOrderCodeRequest.getPartnerId());
        return codeReq;
    }

    public BaseOrderResponse convent2NewOrderUpdateThirdOrderCode(OrderBaseResp updateThirdOrderCode) {
        BaseOrderResponse baseOrderResponse = new BaseOrderResponse();
        baseOrderResponse.setErrcode(updateThirdOrderCode.getCode() != null ? Integer.parseInt(updateThirdOrderCode.getCode()) : 501);
        baseOrderResponse.setErrmsg(updateThirdOrderCode.getMessage());
        return baseOrderResponse;

    }

    public BaseOrderResponse convent2UpdatePickUpGoodNo(OrderBaseResp baseResponse) {
        BaseOrderResponse baseOrderResponse = new BaseOrderResponse();
        baseOrderResponse.setErrcode(baseResponse.getCode() != null ? Integer.parseInt(baseResponse.getCode()) : 501);
        baseOrderResponse.setErrmsg(baseResponse.getMessage());
        return baseOrderResponse;

    }

    public SdkUpdateAbnormalState convert2SdkUpdateAbnormalState(AssortmentUpdateDeliveryAbnormalRequest request) {
        SdkUpdateAbnormalState result = new SdkUpdateAbnormalState();
        result.setOrderClient(OrderClientType.SAAS.getIndex());
        result.setAbnormalDesc(request.getAbnormalDesc());
        result.setAbnormalState(AbnormalStateEnum.ABNORMAL.getCode());
        result.setOrderCode(request.getOrderCode());
        result.setPartnerId(request.getPartnerId());
        result.setOperator(request.getOperator());
        return result;
    }


    /**
     * 老订单服务创建订单对象 转换成 新订单服务请求对象
     */
    public GroupCreateOrderRequest conventGroupCreateOrderRequest(AssortmentGroupCreateOrderRequest requestVO) {
        GroupCreateOrderRequest request = new GroupCreateOrderRequest();
        //围餐不存在预约时间
        request.setOrderType(1);//店内自取实时-1常规堂食
        request.setPartnerId(requestVO.getCompanyId());
        request.setStoreId(requestVO.getShopId());
        request.setOrderClient(requestVO.getOrderClient());
        request.setCompanySelfCode(requestVO.getThirdOrderCode());
        request.setStoreName(requestVO.getShopName());
        request.setStoreNameEn(requestVO.getShopNameEn());
        request.setPartnerName(requestVO.getCompanyName());
        request.setStoreUnifyId(requestVO.getShopCode());
        request.setUserId(requestVO.getUserId());
        request.setUserName(requestVO.getUserName());
        request.setNeedInvoice(requestVO.getNeedInvoice());
        request.setNote(requestVO.getRemark());
        request.setExtInfo(requestVO.getExtInfo());
        request.setBarCounter(requestVO.getBarCounter());
        request.setDinersNumber(requestVO.getDinersNumber());
        request.setOperator(requestVO.getOperator());
//        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
        //商品信息转换
        List<OrderItemCreateReq> orderItemList = new ArrayList<>();
        //优惠信息转换
        List<OrderSettlementCreateReq> orderSettlementCreateReqList = new ArrayList<>();
        List<CreateOrderProductRequest> products = requestVO.getProducts() == null ? new ArrayList<>() : requestVO.getProducts();
        // 更新订单商品详情信息
        updateOrderItemsAndSettlements(orderItemList, orderSettlementCreateReqList, new ArrayList<>(), products, new ArrayList<>(), requestVO.getCompanyId());
        //商品信息赋值
        request.setOrderItemList(orderItemList);
        return request;
    }

    /**
     * 老订单服务创建订单对象 转换成 新订单服务请求对象
     */
    public GroupOrderAffirmReq conventGroupAffirmOrderRequest(AssortmentGroupOrderAffirmRequest requestVO) {
        GroupOrderAffirmReq request = new GroupOrderAffirmReq();
        request.setOrderClient(requestVO.getOrderClient());
        request.setPartnerId(requestVO.getCompanyId());
        //1:线上支付 2:线下支付
        request.setPayType(requestVO.getPayType());
        request.setUserId(requestVO.getUserId());
        request.setUserName(requestVO.getUserName());
        request.setPayTime(requestVO.getPayTime());
        request.setOrderCode(requestVO.getOrderCode());
        request.setPayChannel(requestVO.getPayChannel());
        request.setPayChannelName(requestVO.getPayChannelName());
        request.setPayRequestNo(requestVO.getPayRequestNo());
        request.setPosCode(requestVO.getPosCode());
        request.setStoreUnifyId(requestVO.getShopCode());
        request.setDinersNumber(requestVO.getDinersNumber());
        request.setExtInfo(requestVO.getExtInfo());
        //订单原始金额，单位分
        Long originalAmount = 0L;
        //用户在界面上看到的支付金额
        request.setSettlementAmount(requestVO.getSettlementAmount());
        //实际支付现金金额，扣除支付自生优惠，单位分
        request.setActualPayAmount(requestVO.getActualPayAmount());
        request.setNote(requestVO.getRemark());
        request.setBarCounter(requestVO.getBarCounter());
        //商品信息转换
        List<OrderItemCreateReq> orderItemList = new ArrayList<>();
        //优惠信息转换
        List<OrderSettlementCreateReq> orderSettlementCreateReqList = new ArrayList<>();
        List<CreateOrderProductRequest> products = requestVO.getProducts() == null ? new ArrayList<>() : requestVO.getProducts();
        //结算信息转换
        List<OrderCostCreateReq> orderCostCreateReqs = new ArrayList<>();
        // 更新订单商品详情信息
        originalAmount = updateOrderItemsAndSettlements(orderItemList, orderSettlementCreateReqList, orderCostCreateReqs, products, requestVO.getAccounts(), requestVO.getCompanyId());
        //商品信息赋值
        request.setOrderItemList(orderItemList);
        //订单原始金额，单位分
        request.setOriginalAmount(originalAmount);
        //结算信息赋值
        request.setOrderCostDetailList(orderCostCreateReqs);
        //商品优惠信息赋值
        request.setOrderSettlementDetailList(orderSettlementCreateReqList);

        //收货人信息转换
        List<DeliveryContactInfoCreateReq> deliveryContactInfoList = new ArrayList<DeliveryContactInfoCreateReq>();
        DeliveryContactInfoCreateReq deliveryContactInfoCreateReq = new DeliveryContactInfoCreateReq();
        //地址类型 1:订单地址 2:售后单地址 3:配送员信息
        deliveryContactInfoCreateReq.setRelateObjectType(1);
        //联系方式类型 1:取件 2:收件
        deliveryContactInfoCreateReq.setInfoType(1);
        deliveryContactInfoCreateReq.setMobile(requestVO.getMobile());
        deliveryContactInfoCreateReq.setContactsName(requestVO.getUserName());
        deliveryContactInfoList.add(deliveryContactInfoCreateReq);
        request.setDeliveryContactInfoList(deliveryContactInfoList);
        request.setOperator(requestVO.getOperator());
        return request;
    }

    /**
     * @param result
     * @return
     */
    public AssortmentAffirmGroupOrderResponse conventGroupPaySuccessReqs(com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp<PaySuccessResp> result) {
        AssortmentAffirmGroupOrderResponse assortmentAffirmGroupOrderResponse = new AssortmentAffirmGroupOrderResponse();
        assortmentAffirmGroupOrderResponse.setErrcode(Integer.valueOf(result.getCode()));
        assortmentAffirmGroupOrderResponse.setErrmsg(result.getMessage());
        if (result.getResult() == null) {
            return assortmentAffirmGroupOrderResponse;
        }
        assortmentAffirmGroupOrderResponse.setPaySuccessResp(result.getResult());
        return assortmentAffirmGroupOrderResponse;
    }

    /**
     * 老订单服务创建订单对象 转换成 新订单服务请求对象
     */
    public GroupOrderUpdateReq conventGroupUpdateOrderRequest(AssortmentGroupUpdateOrderRequest requestVO) {
        GroupOrderUpdateReq request = new GroupOrderUpdateReq();
        request.setPayChannel(requestVO.getPayChannel());
        request.setPayChannelName(requestVO.getPayChannelName());
        request.setOrderClient(requestVO.getOrderClient());
        request.setPartnerId(requestVO.getCompanyId());
        //1:线上支付 2:线下支付
        request.setPayType(requestVO.getPayType());
        request.setUserId(requestVO.getUserId());
        request.setUserName(requestVO.getUserName());
        request.setPayTime(requestVO.getPayTime());
        request.setOrderCode(requestVO.getOrderCode());
        request.setPayChannel(requestVO.getPayChannel());
        request.setPayChannelName(requestVO.getPayChannelName());
        request.setPayRequestNo(requestVO.getPayRequestNo());
        request.setPosCode(requestVO.getPosCode());
        request.setStoreUnifyId(requestVO.getShopCode());
        request.setDinersNumber(requestVO.getDinersNumber());
        request.setThirdOrderCode(requestVO.getThirdOrderCode());
        //订单原始金额，单位分
        Long originalAmount = 0L;
        //用户在界面上看到的支付金额
        request.setSettlementAmount(requestVO.getSettlementAmount());
        //实际支付现金金额，扣除支付自生优惠，单位分
        request.setActualPayAmount(requestVO.getActualPayAmount());
        request.setNote(requestVO.getRemark());
        request.setBarCounter(requestVO.getBarCounter());
        //商品信息转换
        List<OrderItemCreateReq> orderItemList = new ArrayList<>();
        //优惠信息转换
        List<OrderSettlementCreateReq> orderSettlementCreateReqList = new ArrayList<>();
        List<CreateOrderProductRequest> products = requestVO.getProducts() == null ? new ArrayList<>() : requestVO.getProducts();
        // 结算信息转换
        List<OrderCostCreateReq> orderCostCreateReqs = new ArrayList<>();
        // 更新订单商品详情信息
        originalAmount = updateOrderItemsAndSettlements(orderItemList, orderSettlementCreateReqList, orderCostCreateReqs, products, requestVO.getAccounts(), requestVO.getCompanyId());
        //订单原始金额，单位分
        request.setOriginalAmount(originalAmount);
        //商品优惠信息赋值
        request.setOrderSettlementDetailList(orderSettlementCreateReqList);
        //如果是围餐订单，本次上线将用户的实际支付金额，用户界面上看到的实际现金金额更新为订单原始计算金额
        if (OrderClientType.WAI_MEAL.getIndex().equals(requestVO.getOrderClient())) {
            /*Long tempAmount = originalAmount/100;
            Long finalAmount = tempAmount * 100;*/
            //long settlementAmount = orderItemList.stream().filter(o -> StringUtils.isBlank(o.getParentProductId())).mapToLong(OrderItemCreateReq::getSettlementPrice).sum();
            request.setOriginalAmount(originalAmount);
            request.setActualPayAmount(requestVO.getSettlementAmount());
            request.setSettlementAmount(requestVO.getSettlementAmount());
        }
        //商品信息赋值
        request.setOrderItemList(orderItemList);
        request.setOperator(requestVO.getOperator());
        return request;
    }

    /**
     * 使用购物车商品信息  更新订单商品明细和优惠明细
     *
     * @param orderItemList                订单商品明细（返回）
     * @param orderSettlementCreateReqList 优惠明细（返回）
     * @param orderCostCreateReqs          费用明细（返回）
     * @param products                     购物车商品信息（入参）
     * @param partnerId                    商户号（入参）
     * @param accounts                     订单优惠和费用（入参）
     * @return 订单金额
     */
    public Long updateOrderItemsAndSettlements(List<OrderItemCreateReq> orderItemList, List<OrderSettlementCreateReq> orderSettlementCreateReqList, List<OrderCostCreateReq> orderCostCreateReqs,
                                               List<CreateOrderProductRequest> products, List<CreateOrderAccountRequest> accounts, String partnerId) {
        Long originalAmount = 0L;
        // 更新订单费用信息
        originalAmount = convertCreateOrderCost(originalAmount, orderSettlementCreateReqList, orderCostCreateReqs, accounts);
        // 更新商品属性信息
        if (CollectionUtils.isEmpty(products)) {
            return originalAmount;
        }
        Integer index = 1;
        for (CreateOrderProductRequest productRequest : products) {
            // 普通商品 订单转换
            productRequest.setOpid(index);
            originalAmount += updateOrderItemAndSettlement(productRequest, orderItemList, orderSettlementCreateReqList, productRequest, partnerId, "", false);
            if (ProductTypeEnum.MATERIAL_PRODUCT.getCode().equals(productRequest.getProductType())) {
                if (CollectionUtils.isNotEmpty(productRequest.getMaterialProduct())) {
                    // 父类商品productId=productId+seq
                    String partnerProductId = productRequest.getProductId() + "_" + index;
                    for (CreateOrderProductRequest material : productRequest.getMaterialProduct()) {
                        index++;
                        material.setOpid(index);
                        material.setSpecification(material.getProductId());
                        material.setSpecificationName(material.getProductName());
                        updateOrderItemAndSettlement(productRequest, orderItemList, orderSettlementCreateReqList, material, partnerId, partnerProductId, true);
                    }
                }
            }
            // 如果是套餐商品，需要转换当前商品行子集ComboProduct&GroupProduct（固定商品、可选商品）
            if (ObjectUtils.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), productRequest.getProductType()) || ObjectUtils.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), productRequest.getProductType())) {
                // 父类商品productId=productId+seq
                String partnerProductId = productRequest.getProductId() + "_" + index;
                if (CollectionUtils.isNotEmpty(productRequest.getComboProduct())) {
                    for (CreateOrderProductRequest combo : productRequest.getComboProduct()) {
                        index ++;
                        combo.setOpid(index);
                        updateOrderItemAndSettlement(productRequest, orderItemList, orderSettlementCreateReqList, combo, partnerId, partnerProductId, false);
                    }
//                    productRequest.getComboProduct().forEach(combo -> updateOrderItemAndSettlement(productRequest, orderItemList, orderSettlementCreateReqList, combo, partnerId, partnerProductId, false));
                }
            }
            index++;
        }
        return originalAmount;
    }

    private Long updateMCCafeOrderItemsAndSettlements(List<OrderItemCreateReq> orderItemList, List<OrderSettlementCreateReq> orderSettlementCreateReqList, List<OrderCostCreateReq> orderCostCreateReqs,
                                                      List<CreateOrderProductRequest> products, List<CreateOrderAccountRequest> accounts, String partnerId) {
        Long originalAmount = 0L;
        // 更新订单费用信息
        originalAmount = convertCreateOrderCost(originalAmount, orderSettlementCreateReqList, orderCostCreateReqs, accounts);
        // 更新商品属性信息
        if (CollectionUtils.isEmpty(products)) {
            return originalAmount;
        }
        Integer index = 1;
        Integer comboIndex = 1;
        for (CreateOrderProductRequest productRequest : products) {
            // 普通商品 订单转换
            productRequest.setOpid(index);
            originalAmount += updateMCCafeOrderItemAndSettlement(productRequest, orderItemList, orderSettlementCreateReqList, productRequest, partnerId, "", false);
            // 如果是套餐商品，需要转换当前商品行子集ComboProduct&GroupProduct（固定商品、可选商品）
            if (ObjectUtils.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), productRequest.getProductType()) || ObjectUtils.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), productRequest.getProductType())) {
                // 父类商品productId=productId+seq
                String parentProductId = productRequest.getProductId() + "_" + index;
                if (CollectionUtils.isNotEmpty(productRequest.getComboProduct())) {
                    for (CreateOrderProductRequest combo : productRequest.getComboProduct()) {
                        combo.setOpid(comboIndex);
                        updateMCCafeOrderItemAndSettlement(productRequest, orderItemList, orderSettlementCreateReqList, combo, partnerId, parentProductId, false);
                        if (CollectionUtils.isNotEmpty(combo.getMaterialProduct())) {
                            String addProductId = combo.getProductId() + "_" + comboIndex;
                            for (CreateOrderProductRequest material : combo.getMaterialProduct()) {
                                material.setSpecification(material.getProductId());
                                material.setSpecificationName(material.getProductName());
                                updateMCCafeOrderItemAndSettlement(productRequest, orderItemList, orderSettlementCreateReqList, material, partnerId, addProductId, true);
                            }
                        }
                        comboIndex++;
                    }
                }
            } else if (CollectionUtils.isNotEmpty(productRequest.getMaterialProduct())) {
                // 父类商品productId=productId+seq
                String addProductId = productRequest.getProductId() + "_" + index;
                for (CreateOrderProductRequest material : productRequest.getMaterialProduct()) {
                    material.setSpecification(material.getProductId());
                    material.setSpecificationName(material.getProductName());
                    updateMCCafeOrderItemAndSettlement(productRequest, orderItemList, orderSettlementCreateReqList, material, partnerId, addProductId, true);
                }
            }
            index++;
        }
        return originalAmount;
    }

    /**
     * 更新当前商品行，订单商品明细和优惠明细
     *
     * @param orderItemList                订单商品明细
     * @param orderSettlementCreateReqList 优惠明细
     * @param product                      当前商品行
     * @param partnerId                    商户号
     * @param parentProductId              套餐父商品Id
     * @return
     */
    private Long updateOrderItemAndSettlement(CreateOrderProductRequest productRequest, List<OrderItemCreateReq> orderItemList, List<OrderSettlementCreateReq> orderSettlementCreateReqList, CreateOrderProductRequest product, String partnerId, String parentProductId, Boolean isMaterial) {
        OrderItemCreateReq orderItemCreateReq = new OrderItemCreateReq();
        orderItemCreateReq.setId(product.getId());
        orderItemCreateReq.setPartnerId(partnerId);
        orderItemCreateReq.setProductName(product.getProductName());
        orderItemCreateReq.setProductForeignName(product.getProductForeignName());
        orderItemCreateReq.setProductId(product.getProductId());
        orderItemCreateReq.setOriginalProductType(product.getOriginalProductType());
        orderItemCreateReq.setProductSpec(product.getSpecification());
        orderItemCreateReq.setProductSpecName(product.getSpecificationName());
        orderItemCreateReq.setProductForeignSpecName(product.getSpecificationForeignName());
        orderItemCreateReq.setProductSeq(product.getOpid());
        orderItemCreateReq.setProductQuantity(product.getNumber());
        orderItemCreateReq.setProductPrice(product.getPrice());
        orderItemCreateReq.setIsDeleted(product.getIsDeleted() == null ? false : product.getIsDeleted());
        Long totalDiscountAmount = product.getTotalDiscountAmount() == null ? 0L : product.getTotalDiscountAmount();
        product.setTotalDiscountAmount(totalDiscountAmount);
        //总原价
        Long totalOriginalProductAmount = product.getPrice() * product.getNumber();
        /**
         * 称重菜
         * 如果没有称重重量视为0
         */
        if (ProductTypeEnum.WEIGHT_PRODUCT.getCode().equals(product.getProductType())) {
            Double weight = (product.getWeight() == null || product.getWeight() <= 0) ? 0 : product.getWeight();
            Double weightPrice = product.getPrice() * weight;
            Long settlementPrice = weightPrice == 0 ? 0 : weightPrice.longValue() - Math.abs(totalDiscountAmount);
            orderItemCreateReq.setSalePrice(settlementPrice);
            orderItemCreateReq.setSettlementPrice(settlementPrice);
            totalOriginalProductAmount = weightPrice.longValue();
        } else {
            Long settlementPrice = product.getPrice() * product.getNumber() - Math.abs(totalDiscountAmount);
            orderItemCreateReq.setSalePrice(settlementPrice / product.getNumber());
            orderItemCreateReq.setSettlementPrice(settlementPrice);
            /**
             * 套餐商品
             * 套餐原价 = 子商品总原价（称重菜原价*重量+普通商品原价*数量+可选商品原价*数量）   fisherman 新算价改动,套餐原价直接取 促销给的值, (因为套餐划线价问题)
             * 套餐结算价 = (套餐价设置为0) ？所有子商品结算价和 * 套餐数量 : 套餐原价*套餐数量-优惠价
             * 套餐售价 = 套餐结算价 / 套餐数量
             */
            if (ProductTypeEnum.SETMEAL_PRODUCT.getCode().equals(product.getProductType()) || ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode().equals(product.getProductType())) {
                if (CollectionUtils.isNotEmpty(product.getComboProduct())) {
                    // 套餐原价
//                    Long setmealProductTotalOriginalAmount = 0L;
                    // 套餐结算价
                    Long setmealTotalSettlementPrice = 0L;
                    for (CreateOrderProductRequest createOrderProductRequest : product.getComboProduct()) {
                        // 删除的不计算在内
                        if (createOrderProductRequest.getIsDeleted() != null && createOrderProductRequest.getIsDeleted()) {
                            continue;
                        }
                        Long comboProductTotalDiscountAmount = createOrderProductRequest.getTotalDiscountAmount() == null ? 0L : createOrderProductRequest.getTotalDiscountAmount();
                        if (ProductTypeEnum.WEIGHT_PRODUCT.getCode().equals(createOrderProductRequest.getProductType())) {
                            Double weight = (createOrderProductRequest.getWeight() == null || createOrderProductRequest.getWeight() <= 0) ? 0 : createOrderProductRequest.getWeight();
                            Double weightPrice = createOrderProductRequest.getPrice() * weight;
                            Long comboSettlementPrice = weightPrice == 0 ? 0 : weightPrice.longValue() - comboProductTotalDiscountAmount;
                            setmealTotalSettlementPrice += comboSettlementPrice;
//                            setmealProductTotalOriginalAmount += weightPrice.longValue();
                        } else {
                            Long numberPrice = createOrderProductRequest.getPrice() * createOrderProductRequest.getNumber();
                            Long comboSettlementPrice = numberPrice - comboProductTotalDiscountAmount;
                            setmealTotalSettlementPrice += comboSettlementPrice;
//                            setmealProductTotalOriginalAmount += numberPrice;
                        }
                    }
                    // 套餐原价  fisherman 新算价改动,套餐原价直接取 促销给的值, (因为套餐划线价问题)
                    orderItemCreateReq.setProductPrice(product.getPrice());
                    // 如果套餐没有设置价格取子商品结算价和，否则取套餐自身的结算价
                    setmealTotalSettlementPrice = product.getPrice() == 0 ? setmealTotalSettlementPrice : settlementPrice;
                    orderItemCreateReq.setSettlementPrice(setmealTotalSettlementPrice);
                    orderItemCreateReq.setSalePrice(setmealTotalSettlementPrice / product.getNumber());
//                    totalOriginalProductAmount = setmealProductTotalOriginalAmount;
                }
            }
        }
        orderItemCreateReq.setProductSharePrice(Math.abs(totalDiscountAmount) / product.getNumber());
        orderItemCreateReq.setProductUnit(product.getUnit());
        //获取商品属性
        OrderProductAddInfoDto addInfo = JSONObject.parseObject(product.getAddInfo(), OrderProductAddInfoDto.class);
        if (addInfo != null) {
            orderItemCreateReq.setProductProperty(addInfo.getAttributeNames());
            orderItemCreateReq.setProductForeignProperty(addInfo.getAttributeForeignNames());
        }
        orderItemCreateReq.setProductPicUrl(product.getPicture());
        orderItemCreateReq.setThirdProductId(product.getCustomerCode());
        orderItemCreateReq.setProductCode(product.getProductCode());
        orderItemCreateReq.setCategoryId(product.getCategoryId());
        orderItemCreateReq.setCategoryName(product.getCategoryName());
        //套餐商品
        if (StringUtils.isNotEmpty(parentProductId)) {
            orderItemCreateReq.setParentProductId(parentProductId); //套餐类商品父级商品id
        }
        orderItemCreateReq.setProductType(product.getProductType()); //套餐 type-6
        orderItemCreateReq.setWeight(product.getWeight()); //重量
        OrderProductAddInfoDto extInfo = new OrderProductAddInfoDto();
        //设置是否为套餐商品
        if (product.getIsFixedProduct() != null) {
            extInfo.setIsFixedProduct(product.getIsFixedProduct());
        }
        extInfo.setStockMode(product.getStockMode());
        extInfo.setStockLimit(product.getHasStockProudct());
        //第三方商品规格id
        if (StringUtils.isNotBlank(product.getThirdProductSpecId())) {
            extInfo.setThirdProductSpecId(product.getThirdProductSpecId());
        }
        if (StringUtils.isNotBlank(product.getSpuProductCode())) {
            extInfo.setSpuProductCode(product.getSpuProductCode());
        }
        //第三方商品属性id
        if (StringUtils.isNotBlank(product.getThirdProductPropertyId())) {
            extInfo.setThirdProductPropertyId(product.getThirdProductPropertyId());
        }
        if (StringUtils.isNotBlank(product.getThirdCategoryId())) {
            extInfo.setThirdCategoryId(product.getThirdCategoryId());
        }
        if (StringUtils.isNotBlank(product.getClassificationId())) {
            extInfo.setThirdCensusCategoryId(product.getClassificationId());
            extInfo.setThirdCensusCategoryName(product.getClassificationName());
        }
        if (CollectionUtils.isNotEmpty(product.getSpecialAttrs())) {
            extInfo.setSpecialAttrs(product.getSpecialAttrs());
        }
        if (0 != product.getTax()) {
            extInfo.setTax(product.getTax());
        }
        if (StringUtils.isNotBlank(product.getTaxId())) {
            extInfo.setTaxId(product.getTaxId());
        }
        if (StringUtils.isNotBlank(product.getCardId())) {
            extInfo.setCardId(product.getCardId());
        }
        if (StringUtils.isNotBlank(product.getCardCode())) {
            extInfo.setCardCode(product.getCardCode());
        }
        if (StringUtils.isNotBlank(product.getSplitIndex())) {
            extInfo.setSplitIndex(product.getSplitIndex());
        }
        if (product.getScore() != null) {
            extInfo.setScore(product.getScore());
        }
        if (StringUtils.isNotBlank(product.getLinkedId())) {
            extInfo.setLinkedId(product.getLinkedId());
        }
        extInfo.setStapleFood(product.getStapleFood());
        extInfo.setOriginalGoodsUid(product.getOriginalGoodsUid());
        extInfo.setCartGoodsUid(product.getCartGoodsUid());
        // todo 订单行扩展字段商品组
        extInfo.setProductGroupList(product.getProductGroupList());
        extInfo.setIsSendGoods(product.getIsSendGoods());
        // 是否需要积分，农工商发送积分需要判断商品是否是送积分的商品
        // 发积分的操作移到消费者，所以这个值需要保存下来
        if (product.getNeedBonus() != null) {
            extInfo.setNeedBonus(product.getNeedBonus());
        }

        if (product.getExtInfo() != null) {
            extInfo.setProductBindingCoupons(JSONArray.parseArray(product.getExtInfo(), ProductBindingCouponType.class));
        }

        orderItemCreateReq.setExtInfo(JSONObject.toJSONString(extInfo));

        // 拼单加购人信息 add by miaohui 2020.10.12 start
        orderItemCreateReq.setUserId(productRequest.getUserId());
        orderItemCreateReq.setOpenId(productRequest.getOpenId());
        orderItemCreateReq.setNickName(productRequest.getNickName());
        orderItemCreateReq.setPhotoUrl(productRequest.getPhotoUrl());
        orderItemCreateReq.setPackPrice(productRequest.getPackPrice());
        // 拼单加购人信息 add by miaohui 2020.10.12 end
        orderItemCreateReq.setProductSpuQuantity(product.getProductSpuQuantity());
        orderItemList.add(orderItemCreateReq);
        if (product.getTotalDiscountAmount() != null && product.getTotalDiscountAmount() > 0L && !isMaterial) {
            //优惠信息转换
            OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
            orderSettlementCreateReq.setProductId(product.getSpecification());
            orderSettlementCreateReq.setNumber(product.getNumber());
            orderSettlementCreateReq.setProductSeq(product.getOpid());
            orderSettlementCreateReq.setExternalObjectId(product.getDiscountId());
            //商家优惠
            orderSettlementCreateReq.setShopDiscountAmount(product.getTotalDiscountAmount());
            //结算金额
            orderSettlementCreateReq.setSettlementAmount(product.getTotalDiscountAmount());
            //是否线上 false:不是 true:是
            orderSettlementCreateReq.setIsOnline(true);
            orderSettlementCreateReq.setSettlementType(0);
            orderSettlementCreateReqList.add(orderSettlementCreateReq);
        }
        // 设置商品行优惠明细
        if (CollectionUtils.isNotEmpty(product.getAccounts())) {
            for (CreateOrderAccountRequest accountRequest : product.getAccounts()) {
                //优惠信息转换
                OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
                orderSettlementCreateReq.setProductId(accountRequest.getProductId());
                orderSettlementCreateReq.setNumber(accountRequest.getDiscountQty());
                orderSettlementCreateReq.setProductSeq(product.getOpid());
                orderSettlementCreateReq.setExternalObjectId(accountRequest.getAccountId());
                //商家优惠
                orderSettlementCreateReq.setShopDiscountAmount(accountRequest.getPrice());
                //结算金额
                orderSettlementCreateReq.setSettlementAmount(accountRequest.getPrice());
                //是否线上 false:不是 true:是
                orderSettlementCreateReq.setIsOnline(true);
                orderSettlementCreateReq.setSettlementType(getDiscountType(accountRequest.getAccountType()));
                orderSettlementCreateReq.setNote(accountRequest.getName());
                orderSettlementCreateReq.setExtInfo(accountRequest.getAddInfo());
                orderSettlementCreateReqList.add(orderSettlementCreateReq);
            }

        }
        return orderItemCreateReq.getIsDeleted() ? 0 : totalOriginalProductAmount;
    }

    /**
     * 更新当前商品行，订单商品明细和优惠明细
     *
     * @param orderItemList                订单商品明细
     * @param orderSettlementCreateReqList 优惠明细
     * @param product                      当前商品行
     * @param partnerId                    商户号
     * @param parentProductId              套餐父商品Id
     * @return
     */
    private Long updateMCCafeOrderItemAndSettlement(CreateOrderProductRequest productRequest, List<OrderItemCreateReq> orderItemList, List<OrderSettlementCreateReq> orderSettlementCreateReqList, CreateOrderProductRequest product, String partnerId, String parentProductId, Boolean isMaterial) {
        OrderItemCreateReq orderItemCreateReq = new OrderItemCreateReq();
        orderItemCreateReq.setId(product.getId());
        orderItemCreateReq.setPartnerId(partnerId);
        orderItemCreateReq.setProductName(product.getProductName());
        orderItemCreateReq.setProductForeignName(product.getProductForeignName());
        orderItemCreateReq.setProductId(product.getProductId());
        orderItemCreateReq.setProductSpec(product.getSpecification());
        orderItemCreateReq.setProductSpecName(product.getSpecificationName());
        orderItemCreateReq.setProductForeignSpecName(product.getSpecificationForeignName());
        orderItemCreateReq.setProductSeq(product.getOpid());
        orderItemCreateReq.setProductQuantity(product.getNumber());
        orderItemCreateReq.setProductPrice(product.getPrice());
        orderItemCreateReq.setIsDeleted(product.getIsDeleted() == null ? false : product.getIsDeleted());
        Long totalDiscountAmount = product.getTotalDiscountAmount() == null ? 0L : product.getTotalDiscountAmount();
        product.setTotalDiscountAmount(totalDiscountAmount);
        //总原价
        Long totalOriginalProductAmount = product.getPrice() * product.getNumber();
        /**
         * 称重菜
         * 如果没有称重重量视为0
         */
        if (ProductTypeEnum.WEIGHT_PRODUCT.getCode().equals(product.getProductType())) {
            Double weight = (product.getWeight() == null || product.getWeight() <= 0) ? 0 : product.getWeight();
            Double weightPrice = product.getPrice() * weight;
            Long settlementPrice = weightPrice == 0 ? 0 : weightPrice.longValue() - totalDiscountAmount;
            orderItemCreateReq.setSalePrice(settlementPrice);
            orderItemCreateReq.setSettlementPrice(settlementPrice);
            totalOriginalProductAmount = weightPrice.longValue();
        } else {
            Long settlementPrice = product.getPrice() * product.getNumber() - totalDiscountAmount;
            orderItemCreateReq.setSalePrice(settlementPrice / product.getNumber());
            orderItemCreateReq.setSettlementPrice(settlementPrice);
        }
        orderItemCreateReq.setProductSharePrice(totalDiscountAmount / product.getNumber());
        orderItemCreateReq.setProductUnit(product.getUnit());
        //获取商品属性
        OrderProductAddInfoDto addInfo = JSONObject.parseObject(product.getAddInfo(), OrderProductAddInfoDto.class);
        if (addInfo != null) {
            orderItemCreateReq.setProductProperty(addInfo.getAttributeNames());
            orderItemCreateReq.setProductForeignProperty(addInfo.getAttributeForeignNames());
        }
        orderItemCreateReq.setProductPicUrl(product.getPicture());
        orderItemCreateReq.setThirdProductId(product.getCustomerCode());
        orderItemCreateReq.setProductCode(product.getProductCode());
        orderItemCreateReq.setCategoryId(product.getCategoryId());
        orderItemCreateReq.setCategoryName(product.getCategoryName());
        //套餐商品
        if (StringUtils.isNotEmpty(parentProductId)) {
            orderItemCreateReq.setParentProductId(parentProductId); //套餐类商品父级商品id
        }
        orderItemCreateReq.setProductType(product.getProductType()); //套餐 type-6
        orderItemCreateReq.setWeight(product.getWeight()); //重量
        OrderProductAddInfoDto extInfo = new OrderProductAddInfoDto();
        //设置是否为套餐商品
        if (product.getIsFixedProduct() != null) {
            extInfo.setIsFixedProduct(product.getIsFixedProduct());
        }
        //第三方商品规格id
        if (StringUtils.isNotBlank(product.getThirdProductSpecId())) {
            extInfo.setThirdProductSpecId(product.getThirdProductSpecId());
        }
        //第三方商品属性id
        if (StringUtils.isNotBlank(product.getThirdProductPropertyId())) {
            extInfo.setThirdProductPropertyId(product.getThirdProductPropertyId());
        }
        if (StringUtils.isNotBlank(product.getThirdCategoryId())) {
            extInfo.setThirdCategoryId(product.getThirdCategoryId());
        }
        if (StringUtils.isNotBlank(product.getClassificationId())) {
            extInfo.setThirdCensusCategoryId(product.getClassificationId());
            extInfo.setThirdCensusCategoryName(product.getClassificationName());
        }
        if (CollectionUtils.isNotEmpty(product.getSpecialAttrs())) {
            extInfo.setSpecialAttrs(product.getSpecialAttrs());
        }
        if (0 != product.getTax()) {
            extInfo.setTax(product.getTax());
        }
        if (StringUtils.isNotBlank(product.getTaxId())) {
            extInfo.setTaxId(product.getTaxId());
        }
        if (StringUtils.isNotBlank(product.getCardId())) {
            extInfo.setCardId(product.getCardId());
        }
        if (StringUtils.isNotBlank(product.getCardCode())) {
            extInfo.setCardCode(product.getCardCode());
        }
        if (StringUtils.isNotBlank(product.getSplitIndex())) {
            extInfo.setSplitIndex(product.getSplitIndex());
        }
        if (null != product.getProductGroupId()) {
            extInfo.setProductGroupId(product.getProductGroupId());
        }
        if (null != product.getIsSendGoods() && product.getIsSendGoods()) {
            extInfo.setIsSendGoods(true);
        }
        extInfo.setIsMonthCard(product.getIsMonthCard());
        extInfo.setIsB3S1Coupon(product.getIsB3S1Coupon());
        extInfo.setStapleFood(product.getStapleFood());

        extInfo.setOriginalGoodsUid(product.getOriginalGoodsUid());
        extInfo.setCartGoodsUid(product.getCartGoodsUid());
        // todo 订单行扩展字段商品组
        extInfo.setProductGroupList(product.getProductGroupList());
        // 是否需要积分，农工商发送积分需要判断商品是否是送积分的商品
        // 发积分的操作移到消费者，所以这个值需要保存下来
        if (product.getNeedBonus() != null) {
            extInfo.setNeedBonus(product.getNeedBonus());
        }

        orderItemCreateReq.setExtInfo(JSONObject.toJSONString(extInfo));

        // 拼单加购人信息 add by miaohui 2020.10.12 start
        orderItemCreateReq.setUserId(productRequest.getUserId());
        orderItemCreateReq.setOpenId(productRequest.getOpenId());
        orderItemCreateReq.setNickName(productRequest.getNickName());
        orderItemCreateReq.setPhotoUrl(productRequest.getPhotoUrl());
        orderItemCreateReq.setPackPrice(productRequest.getPackPrice());
        // 拼单加购人信息 add by miaohui 2020.10.12 end

        orderItemList.add(orderItemCreateReq);
        if (product.getTotalDiscountAmount() != null && product.getTotalDiscountAmount() > 0L && !isMaterial) {
            //优惠信息转换
            OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
            orderSettlementCreateReq.setProductId(product.getSpecification());
            orderSettlementCreateReq.setNumber(product.getNumber());
            orderSettlementCreateReq.setProductSeq(product.getOpid());
            orderSettlementCreateReq.setExternalObjectId(product.getDiscountId());
            //商家优惠
            orderSettlementCreateReq.setShopDiscountAmount(product.getTotalDiscountAmount());
            //结算金额
            orderSettlementCreateReq.setSettlementAmount(product.getTotalDiscountAmount());
            //是否线上 false:不是 true:是
            orderSettlementCreateReq.setIsOnline(true);
            orderSettlementCreateReq.setSettlementType(0);
            orderSettlementCreateReqList.add(orderSettlementCreateReq);
        }
        // 设置商品行优惠明细
        if (CollectionUtils.isNotEmpty(product.getAccounts())) {
            for (CreateOrderAccountRequest accountRequest : product.getAccounts()) {
                //优惠信息转换
                OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
                orderSettlementCreateReq.setProductId(accountRequest.getProductId());
                orderSettlementCreateReq.setNumber(accountRequest.getDiscountQty());
                orderSettlementCreateReq.setProductSeq(product.getOpid());
                orderSettlementCreateReq.setExternalObjectId(accountRequest.getAccountId());
                //商家优惠
                orderSettlementCreateReq.setShopDiscountAmount(accountRequest.getPrice());
                //结算金额
                orderSettlementCreateReq.setSettlementAmount(accountRequest.getPrice());
                //是否线上 false:不是 true:是
                orderSettlementCreateReq.setIsOnline(true);
                orderSettlementCreateReq.setSettlementType(getDiscountType(accountRequest.getAccountType()));
                orderSettlementCreateReq.setNote(accountRequest.getName());
                orderSettlementCreateReq.setExtInfo(accountRequest.getAddInfo());
                orderSettlementCreateReqList.add(orderSettlementCreateReq);
            }

        }
        return orderItemCreateReq.getIsDeleted() ? 0 : totalOriginalProductAmount;
    }

    public GroupOrderClearReq convertAssortmentSdkUpdateOrderProductInfoRequestTo(AssortmentSdkUpdateOrderProductInfoRequest updateOrderProductInfoRequest) {
        GroupOrderClearReq groupOrderClearReq = new GroupOrderClearReq();
        groupOrderClearReq.setOrderClient(updateOrderProductInfoRequest.getOrderClient());
        groupOrderClearReq.setOrderCode(updateOrderProductInfoRequest.getOrderCode());
        groupOrderClearReq.setThirdOrderCode(updateOrderProductInfoRequest.getThirdOrderCode());
        groupOrderClearReq.setPartnerId(updateOrderProductInfoRequest.getPartnerId());
        return groupOrderClearReq;
    }

    public BaseQueryOrderRequest convertAssortmentSdkUpdateOrderProductInfoRequestToBaseQueryOrderRequest(AssortmentSdkUpdateOrderProductInfoRequest updateOrderProductInfoRequest) {
        BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
        baseQueryOrderRequest.setOrderClient(updateOrderProductInfoRequest.getOrderClient() + "");
        baseQueryOrderRequest.setOrderId(updateOrderProductInfoRequest.getOrderCode());
        baseQueryOrderRequest.setThirdOrderCode(updateOrderProductInfoRequest.getThirdOrderCode());
        baseQueryOrderRequest.setPartnerId(updateOrderProductInfoRequest.getPartnerId());
        baseQueryOrderRequest.setTrackingNo(updateOrderProductInfoRequest.getTrackingNo());
        return baseQueryOrderRequest;
    }

    public AssortmentGroupUpdateOrderRequest convertAssortmentSdkUpdateOrderProductInfoRequestToAssortmentGroupUpdateOrderRequest(AssortmentSdkUpdateOrderProductInfoRequest updateOrderProductInfoRequest) {
        AssortmentGroupUpdateOrderRequest assortmentGroupUpdateOrderRequest = new AssortmentGroupUpdateOrderRequest();
        assortmentGroupUpdateOrderRequest.setOrderCode(updateOrderProductInfoRequest.getOrderCode());
        assortmentGroupUpdateOrderRequest.setCompanyId(updateOrderProductInfoRequest.getPartnerId());
        assortmentGroupUpdateOrderRequest.setOrderClient(updateOrderProductInfoRequest.getOrderClient());
        assortmentGroupUpdateOrderRequest.setThirdOrderCode(updateOrderProductInfoRequest.getThirdOrderCode());
        assortmentGroupUpdateOrderRequest.setTrackingNo(updateOrderProductInfoRequest.getTrackingNo());
        //修改餐具商品数量
        if (updateOrderProductInfoRequest.getDinersNumber() != null && updateOrderProductInfoRequest.getDinersNumber() != 0) {
            updateOrderProductInfoRequest.getOrderItemList().stream()
                    .filter(var -> ProductTypeEnum.TABLEWARE_PRODUCT.getCode().equals(var.getProductType()))
                    .forEach(each -> {
                        each.setNumber(updateOrderProductInfoRequest.getDinersNumber());
                    });
        }
        assortmentGroupUpdateOrderRequest.setProducts(updateOrderProductInfoRequest.getOrderItemList());
        assortmentGroupUpdateOrderRequest.setDinersNumber(updateOrderProductInfoRequest.getDinersNumber());
        assortmentGroupUpdateOrderRequest.setActualPayAmount(updateOrderProductInfoRequest.getActualPayAmount());
        assortmentGroupUpdateOrderRequest.setOriginalAmount(updateOrderProductInfoRequest.getOriginalAmount());
        assortmentGroupUpdateOrderRequest.setPayType(updateOrderProductInfoRequest.getPayType());
        assortmentGroupUpdateOrderRequest.setSettlementAmount(updateOrderProductInfoRequest.getSettlementAmount());
        assortmentGroupUpdateOrderRequest.setUserId(updateOrderProductInfoRequest.getUserId());
        assortmentGroupUpdateOrderRequest.setUserName(updateOrderProductInfoRequest.getUserName());
        assortmentGroupUpdateOrderRequest.setOperator(updateOrderProductInfoRequest.getUserName());
        assortmentGroupUpdateOrderRequest.setAccounts(updateOrderProductInfoRequest.getAccounts());
        assortmentGroupUpdateOrderRequest.setUpdateAccounts(updateOrderProductInfoRequest.isUpdateAccounts());
        assortmentGroupUpdateOrderRequest.setPayChannel(updateOrderProductInfoRequest.getPayChannel());
        assortmentGroupUpdateOrderRequest.setPayChannelName(updateOrderProductInfoRequest.getPayChannelName());
        return assortmentGroupUpdateOrderRequest;
    }

    public CreateOrderProductRequest convertOrderBeanProductBean2CreateOrderProductRequest(ProductBeanV1 productBean, String trackingNo) {
        CreateOrderProductRequest createOrderProductRequest = new CreateOrderProductRequest();
        createOrderProductRequest.setProductCode(productBean.getProductCode());
        createOrderProductRequest.setProductName(productBean.getProductName());
        createOrderProductRequest.setProductForeignName(productBean.getProductForeignName());
        createOrderProductRequest.setNumber(productBean.getNumber());
        createOrderProductRequest.setParentProductId(productBean.getParentProductId());
        createOrderProductRequest.setTrackingNo(trackingNo);
        createOrderProductRequest.setAddInfo(productBean.getAddInfo());
        createOrderProductRequest.setForeignAddInfo(productBean.getForeignAddInfo());
        createOrderProductRequest.setProductId(productBean.getProductId());
        createOrderProductRequest.setSpecification(productBean.getSpecification());
        createOrderProductRequest.setSpecificationName(productBean.getSpecificationName());
        createOrderProductRequest.setSpecificationForeignName(productBean.getSpecificationName());

        createOrderProductRequest.setCustomerCode(productBean.getCustomerCode());
        createOrderProductRequest.setSequence(productBean.getSequence());
        createOrderProductRequest.setPrice(productBean.getPrice());
        Long orginalTotalAmount = productBean.getPrice() * productBean.getNumber();
        if (Objects.equals(productBean.getProductType(), ProductTypeEnum.WEIGHT_PRODUCT.getCode())) {
            orginalTotalAmount = new BigDecimal(productBean.getPrice() + "").multiply(productBean.getWeight()).longValue();
        }
        createOrderProductRequest.setTotalDiscountAmount(orginalTotalAmount - productBean.getSettlementPrice());
        createOrderProductRequest.setUnit(productBean.getUnit());
        createOrderProductRequest.setId(productBean.getId());
        createOrderProductRequest.setProductType(productBean.getProductType());
        OrderProductAddInfoDto extInfo = JSONObject.parseObject(productBean.getExtInfo(), OrderProductAddInfoDto.class);
        if (extInfo != null) {
            createOrderProductRequest.setIsFixedProduct(extInfo.getIsFixedProduct());
            createOrderProductRequest.setThirdProductSpecId(extInfo.getThirdProductSpecId());
            createOrderProductRequest.setThirdProductPropertyId(extInfo.getThirdProductPropertyId());
        }

        if (productBean.getWeight() != null) {
            createOrderProductRequest.setWeight(productBean.getWeight().doubleValue());
        }

        if (CollectionUtils.isNotEmpty(productBean.getComboProduct())) {
            List<CreateOrderProductRequest> comboProductList = new ArrayList<>();
            productBean.getComboProduct().forEach(comboProductBean -> {
                comboProductList.add(this.convertOrderBeanProductBean2CreateOrderProductRequest(comboProductBean, trackingNo));
            });
            createOrderProductRequest.setComboProduct(comboProductList);
        }
        return createOrderProductRequest;
    }


    /**
     * 均摊明细
     *
     * @param orderInfoReqs
     * @return
     */
    private List<OrderSettlementResp> getApportionDetails(OrderInfoReqs orderInfoReqs) {
        List<OrderSettlementResp> orderSettlementList = new ArrayList<>();

        List<OrderSettlementResp> orderSettlements = orderInfoReqs.getOrderSettlementDetailList();
        if (CollectionUtils.isNotEmpty(orderSettlements)) {
            Map<String, OrderItemResp> orderItemMap = orderInfoReqs.getOrderItemList().stream().collect(Collectors.toMap(OrderItemResp::getPartnerId, orderItemResp -> orderItemResp, (key1, key2) -> key2));
            for (OrderSettlementResp orderSettlementResp : orderSettlements) {
                OrderSettlementResp orderSettlement = new OrderSettlementResp();
                orderSettlement.setProductId(orderSettlementResp.getProductId());
                if (orderItemMap.get(orderSettlementResp.getProductId()) != null) {
                    orderSettlement.setProductName(orderItemMap.get(orderSettlementResp.getProductId()).getProductName());
                }
                orderSettlement.setProductSeq(orderSettlementResp.getProductSeq());
                orderSettlement.setExternalObjectId(orderSettlementResp.getExternalObjectId());
                orderSettlement.setExternalObjectName(orderSettlementResp.getExternalObjectName());
                orderSettlement.setExternalObjectSubId(null);
                orderSettlement.setIgnoreInDiscountAmount(orderSettlementResp.getIgnoreInDiscountAmount());
                orderSettlement.setSettlementType(orderSettlementResp.getSettlementType());
                if (orderSettlementResp.getSettlementType() != null && orderSettlementResp.getSettlementType().intValue() == 23
                        && "setMeal".equals(orderSettlementResp.getExternalObjectId())) {
                    orderSettlement.setSettlementTypeName("套餐");
                } else {
                    orderSettlement.setSettlementTypeName(getOrderSettlementTypeName(orderSettlementResp.getSettlementType()));
                }
                orderSettlement.setSettlementAmount(orderSettlementResp.getSettlementAmount());
                orderSettlement.setNote(orderSettlementResp.getNote());
                orderSettlement.setNumber(orderSettlementResp.getNumber());
                orderSettlement.setPlatformDiscountAmount(orderSettlementResp.getPlatformDiscountAmount());
                orderSettlement.setShopDiscountAmount(orderSettlementResp.getShopDiscountAmount());
                orderSettlement.setAgentDiscountAmount(orderSettlementResp.getAgentDiscountAmount());
                orderSettlement.setCarrierDiscountAmount(orderSettlementResp.getCarrierDiscountAmount());
                orderSettlement.setShopAmount(orderSettlementResp.getShopAmount());
                orderSettlement.setPlatformServiceAmount(orderSettlementResp.getPlatformServiceAmount());
                if (orderSettlementResp.getProspectiveAmount() != null) {
                    orderSettlement.setProspectiveAmount(orderSettlementResp.getProspectiveAmount());
                } else {
                    orderSettlement.setProspectiveAmount(new BigDecimal(0));
                }
                orderSettlementList.add(orderSettlement);
            }
        }
        return orderSettlementList;
    }

    /**
     * 优惠类型描述
     *
     * @param settlementType
     * @return
     */
    private String getOrderSettlementTypeName(int settlementType) {
        // 新订单服务枚举 OrderSettlementType
        String name = "";
        switch (settlementType) {
            case 2:
                name = OrderSettlementType.FULL_REDUCTION.getName();
                break;
            case 3:
                name = OrderSettlementType.COUPON.getName();
                break;
            case 4:
                name = OrderSettlementType.GIFT_GIVING.getName();
                break;
            case 5:
                name = OrderSettlementType.FULL_GIFTS.getName();
                break;
            case 10:
                name = OrderSettlementType.CASH_COUPON.getName();
                break;
            case 12:
                name = OrderSettlementType.INCREASE_PURCHASE.getName();
                break;
            case 20:
                name = OrderSettlementType.ITEM_DISCOUNT.getName();
                break;
            case 23:
                name = OrderSettlementType.ONE_BY_ONE.getName();
                break;
            case 46:
                name = OrderSettlementType.INCREASE_PURCHASE.getName();
                break;
            case 118:
                name = OrderSettlementType.PRODUCT_COUPON.getName();
                break;
            case 200:
                name = OrderSettlementType.POINTS.getName();
                break;
            case 206:
                name = OrderSettlementType.ITEM_SPECIAL_PRICE.getName();
                break;
            case 207:
                name = OrderSettlementType.ONE_BY_ONE.getName();
                break;
            case 208:
                name = OrderSettlementType.DISCOUNT_COUPON.getName();
                break;
            case 1014:
                name = OrderSettlementType.FULL_DISTRIBUTION_FEE.getName();
                break;
            default:
                break;
        }
        return name;
    }

    /**
     * 计算所有商品的重量 单位g
     */
    public Double sumOrderWeight(List<CreateOrderProductRequest> products) {
        Double totalWeight = 0D;
        if (CollectionUtils.isEmpty(products)) {
            return totalWeight;
        }
        for (CreateOrderProductRequest productRequest : products) {
            Integer qty = productRequest.getNumber() == null ? 0 : productRequest.getNumber();
            if (ObjectUtils.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), productRequest.getProductType()) || ObjectUtils.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), productRequest.getProductType())) {
                if (CollectionUtils.isNotEmpty(productRequest.getComboProduct())) {
                    Double comboProductTotalWeight = productRequest.getComboProduct().stream().map(t -> {
                        Integer comboQty = t.getNumber() == null ? 0 : t.getNumber();
                        return WeightUtils.changeToG(t.getWeight(), t.getUnit()) * comboQty;
                    }).reduce(0D, Double::sum);
                    totalWeight += comboProductTotalWeight * qty;
                }
            } else {
                totalWeight += WeightUtils.changeToG(productRequest.getWeight(), productRequest.getUnit()) * qty;
            }
        }
        return totalWeight;
    }


    /**
     * 匹配订单类型
     *
     * @param orderType
     * @return
     */
    public OrderType getNewOrderTypeEnum(Integer orderType, Long gmtExpect) {
        if (orderType == null) {
            return null;
        }

        switch (orderType) {
            case 1:
                // 外卖
                if (gmtExpect == null || gmtExpect == 0L) {
                    return OrderType.GENERAL_EXPRESS;
                } else {
                    return OrderType.RESERVED_EXPRESS;
                }
            case 4:
                // 自取
                if (gmtExpect == null || gmtExpect == 0L) {
                    return OrderType.GENERAL_SELF_PICKUP;
                } else {
                    return OrderType.RESERVED_SELF_PICKUP;
                }
            case 5:
                // 堂食
                if (gmtExpect == null || gmtExpect == 0L) {
                    return OrderType.GENERAL_DINE_IN;
                } else {
                    return OrderType.RESERVED_DINE_IN;
                }
            default:
                return null;
        }
    }

    /**
     * 异常单转换
     *
     * @param abnormalState
     * @return
     */
    public String getAbnormalName(Integer abnormalState) {
        String name = "";
        switch (abnormalState) {
            case 0: {
                name = "正常";
                break;
            }
            case 1: {
                name = "系统接单异常";
                break;
            }
            case 2: {
                name = "骑手上报异常";
                break;
            }
            case 3: {
                name = "系统退单异常";
                break;
            }
        }
        return name;
    }

    /**
     * 获取订单信息
     *
     * @param orderStatus
     * @return
     */
    public String getOrderStatusValue(Integer orderStatus) {
        String name = "";
        switch (orderStatus) {
            case 1: {
                name = "待审核";
                break;
            }
            case 6: {
                name = "审核通过";
                break;
            }
            case 7: {
                name = "审核未通过";
                break;
            }
            case 8: {
                name = "撤单";
                break;
            }
        }
        return name;
    }

    /**
     * 获取订单信息
     *
     * @param sourceList
     * @return
     */
    public List<Integer> getBizTypes(List<String> sourceList) {
        List<Integer> bizTypes = new ArrayList<>(0);
        String source = sourceList.get(0);
        switch (source) {
            case "97": {
                bizTypes.add(97);
                break;
            }
            case "98": {
                bizTypes.add(98);
                break;
            }
            default:
                bizTypes.add(1);
                bizTypes.add(6);
                bizTypes.add(97);
                bizTypes.add(98);
                break;
        }
        return bizTypes;
    }

    public CouponLockRequest convert2CouponLockRequest(OrderBeanV1 orderBean, List<CreateOrderAccountRequest> accounts) {
        if (CollectionUtils.isEmpty(accounts)) {
            return null;
        }
        // fisherman 支持 批量锁券逻辑, 配送券+other券
        List<CreateOrderAccountRequest> couponList = accounts.stream().filter(account ->
                account.getAccountType().equals(QueryOrderAccountType.COUPON)
                        || account.getAccountType().equals(QueryOrderAccountType.PRODUCT_COUPON)
                        || account.getAccountType().equals(QueryOrderAccountType.DISCOUNT_COUPON)
                        || account.getAccountType().equals(QueryOrderAccountType.FREIGHT_COUPON)
        ).collect(Collectors.toList());
        AssortOrderLogUtil.info("优惠券转换,用于锁券操作 orderbean : accounts", orderBean, accounts);
        if (CollectionUtils.isEmpty(couponList)) {
            return null;
        }
        List<String> couponCodes = couponList.stream().map(CreateOrderAccountRequest::getAccountId).collect(Collectors.toList());
        CouponLockRequest couponLockRequest = new CouponLockRequest();

        // 订单号 替换成唯一序号
        couponLockRequest.setPartnerId(orderBean.getCompanyId());
        couponLockRequest.setOrderId(orderBean.getOid());
        //couponLockRequest.setCouponCode(accountBean.getAccountId());
        List<CouponLockRequest.CouponLockInfo> infos = new ArrayList<>();
        couponCodes.forEach(s -> {
            CouponLockRequest.CouponLockInfo info = new CouponLockRequest.CouponLockInfo();
            info.setCouponCode(s);
            infos.add(info);
        });
        couponLockRequest.setCouponLockInfos(infos);
        return couponLockRequest;

    }

    public QueryLineUpResponse convent2QueryLineUpResponse(OrderBaseResp baseResponse) {
        QueryLineUpResponse response = new QueryLineUpResponse();
        response.setErrcode(Integer.parseInt(baseResponse.getCode()));
        response.setErrmsg(baseResponse.getMessage());
        if (baseResponse.getResult() == null) {
            return response;
        }
        response.setOrderCodes((List<String>) baseResponse.getResult());
        return response;
    }

    public BaseQueryOrderRequest convert2wmDeliveryTimeOut(BaseQueryOrderRequest orderConfirmRequest, Integer timeOut) {
        orderConfirmRequest.setTimeout(timeOut);
        return orderConfirmRequest;
    }

    public OrderStateInfoResp convent2OrderStateInfoResp(QueryByCodeResponse orderInfo) {
        if (Objects.isNull(orderInfo)) {
            return null;
        }
        OrderStateInfoResp orderStateInfoResp = new OrderStateInfoResp();
        orderStateInfoResp.setErrcode(Integer.parseInt(orderInfo.getCode()));
        orderStateInfoResp.setErrmsg(orderInfo.getMessage());
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, orderInfo.getCode()) || Objects.isNull(orderInfo.getResult()) || StringUtils.isBlank(orderInfo.getResult().getOrderCode())) {
            return orderStateInfoResp;
        }
        OrderInfoReqs orderInfoReqs = orderInfo.getResult();
        OrderStateInfoResp.OrderStateInfo info = new OrderStateInfoResp.OrderStateInfo();
        info.setOrderCode(orderInfoReqs.getOrderCode());
        info.setOrderState(orderInfoReqs.getOrderState());
        info.setAfterSalesState(orderInfoReqs.getAfterSalesState());
        info.setPayState(orderInfoReqs.getPayState());
        info.setOrderOperationHistoryList(orderInfoReqs.getOrderOperationHistoryList());
        // 获取当前状态最后一条匹配的操作时间
        if (CollectionUtils.isNotEmpty(orderInfoReqs.getOrderOperationHistoryList())) {
            List<OrderOperationHistoryResp> historyList = orderInfoReqs.getOrderOperationHistoryList();
            for (int i = historyList.size() - 1; i >= 0; i--) {
                OrderOperationHistoryResp historyResp = historyList.get(i);
                if (Objects.equals(historyResp.getTargetOrderState(), orderInfoReqs.getOrderState())) {
                    info.setStateUpdateTimestamp(historyResp.getUpdateTimestamp());
                    info.setStateTimeout(historyResp.getTimeout());
                    break;
                }
            }
        }
        orderStateInfoResp.setData(info);
        return orderStateInfoResp;
    }

    public CouponRequest convert2PreCheckRequest(OrderBeanV1 orderBean, List<CreateOrderAccountRequest> accounts, String openId) {
        if (CollectionUtils.isEmpty(accounts)) {
            return null;
        }
        // fisherman  begin
        List<CreateOrderAccountRequest> couponList = accounts.stream().filter(account ->
                account.getAccountType().equals(QueryOrderAccountType.COUPON)
                        || account.getAccountType().equals(QueryOrderAccountType.PRODUCT_COUPON)
                        || account.getAccountType().equals(QueryOrderAccountType.DISCOUNT_COUPON)
                        || account.getAccountType().equals(QueryOrderAccountType.FREIGHT_COUPON)
        ).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(couponList)) {
            return null;
        }

        //fisherman 【01测16灰18全，【华莱士】【疑难专项】一个订单多张优惠券使用场景】 https://www.tapd.cn/43862731/prong/stories/view/1143862731001037477
        return this.commonMethodVerificationNew(couponList, orderBean, openId);

//        // fisherman  end
//        if (couponList.size() > 1) {
//            // 找出 配送券
//            CreateOrderAccountRequest freightCouponAccountBean = couponList.stream().filter(account -> account.getAccountType().equals(QueryOrderAccountType.FREIGHT_COUPON)).findFirst().orElse(null);
//            TransactionVO couponCodeVerificationTransDto = null;
//            if (!Objects.isNull(freightCouponAccountBean)) {
//                couponCodeVerificationTransDto = new TransactionVO();
//                couponCodeVerificationTransDto.setCode(freightCouponAccountBean.getAccountId());
//                couponCodeVerificationTransDto.setTotalAmount(freightCouponAccountBean.getPrice());
//            }
//            // 过滤出 配送券
//            List<CreateOrderAccountRequest> collect = couponList.stream().filter(account -> !account.getAccountType().equals(QueryOrderAccountType.FREIGHT_COUPON)).collect(Collectors.toList());
//            return commonMethodVerification(couponCodeVerificationTransDto, collect, orderBean, openId);
//        } else {
//            return commonMethodVerification(null, couponList, orderBean, openId);
//        }
    }

//    private CouponRequest commonMethodVerification(TransactionVO freightCouponAccountBean,
//                                                   List<CreateOrderAccountRequest> collect,
//                                                   OrderBeanV1 orderBean,
//                                                   String openId) {
//        CreateOrderAccountRequest accountBean = collect.get(0);
//        CouponRequest couponRequest = new CouponRequest();
//        couponRequest.setReqtype(71);
//        couponRequest.setVer(Integer.valueOf(Version.VERSION_1));
//        couponRequest.setPartnerId(Integer.parseInt(orderBean.getCompanyId()));
//        ActivityChannelEnum activityChannelEnum = orderTypeEnumConvert2ActivityChannel(orderBean.getOrderType());
//        if (activityChannelEnum == null) {
//            activityChannelEnum = ActivityChannelEnum.pickup;
//        }
//        couponRequest.setChannel(activityChannelEnum.getCode());
//        couponRequest.setStation_id("-1");
//        couponRequest.setOperator_id("-1");
//        couponRequest.setStore_id(orderBean.getShopId());
////        couponRequest.setMemberId(orderBean.getUserId());
//        couponRequest.setOpenid(openId);
//        // 订单号 替换成唯一序号
//        couponRequest.setTrans_id(orderBean.getOid());
//        couponRequest.setBusiness_date(DateUtil.convert2String(new Date(), DateUtil.FORMAT_yyyyMMdd));
//        List<TransactionVO> transactions = new ArrayList<>();
//        TransactionVO couponCodeVerificationTransDto = new TransactionVO();
//        couponCodeVerificationTransDto.setCode(accountBean.getAccountId());
//        couponCodeVerificationTransDto.setOpenId(openId);
//        Integer discountPrice = accountBean.getPrice().intValue();
//        couponCodeVerificationTransDto.setTotalAmount(Math.abs(discountPrice.longValue()));
//        //商品券预教研
//        List<ProductRedeemVO> products = new ArrayList<>();
//        if (QueryOrderAccountType.PRODUCT_COUPON.getCode().equals(accountBean.getAccountType().getCode())) {
//            for (int i = 0; i < orderBean.getProductList().size(); i++) {
//                ProductBeanV1 productBean = orderBean.getProductList().get(i);
//                String pid = StringUtils.isNotBlank(productBean.getSpecification()) ? productBean.getSpecification() : productBean.getProductId();
//                if (!org.springframework.util.CollectionUtils.isEmpty(orderBean.getProductList().get(i).getDiscountList())) {
//                    List<ProductDiscountV1> discounts = orderBean.getProductList().get(i).getDiscountList().stream().
//                            filter(productDiscount -> productDiscount.getDiscountId().equals(accountBean.getAccountId())).collect(Collectors.toList());
//                    for (ProductDiscountV1 productDiscount : discounts) {
//                        if (productDiscount.getDiscountType() == null || productDiscount.getDiscountType() == 0) {
//                            continue;
//                        }
//                        ProductRedeemVO couponCodeVerificationProductDto = new ProductRedeemVO();
//                        couponCodeVerificationProductDto.setPid(pid);
//                        couponCodeVerificationProductDto.setConsume_num(productDiscount.getDiscountQty());
//                        couponCodeVerificationProductDto.setSeq(i + 1);
//                        couponCodeVerificationProductDto.setRedeem_price(new BigDecimal(productBean.getPrice()));
//                        products.add(couponCodeVerificationProductDto);
//                    }
//                }
//            }
//        }
//        if (CollectionUtils.isNotEmpty(products)) {
//            couponCodeVerificationTransDto.setProducts(products);
//        }
//        transactions.add(couponCodeVerificationTransDto);
//        // 配送券逻辑加入
//        if (freightCouponAccountBean != null) {
//            transactions.add(freightCouponAccountBean);
//        }
//        // 配送券逻辑 end
//        couponRequest.setTransactions(transactions);
//        return couponRequest;
//    }

    private CouponRequest commonMethodVerificationNew(List<CreateOrderAccountRequest> collect,
                                                      OrderBeanV1 orderBean,
                                                      String openId) {
        CouponRequest couponRequest = new CouponRequest();
        couponRequest.setReqtype(71);
        couponRequest.setVer(Integer.valueOf(Version.VERSION_1));
        couponRequest.setPartnerId(Integer.parseInt(orderBean.getCompanyId()));
        ActivityChannelEnum activityChannelEnum = orderTypeEnumConvert2ActivityChannel(orderBean.getOrderType(), orderBean.getBizType());
        if (activityChannelEnum == null) {
            activityChannelEnum = ActivityChannelEnum.pickup;
        }
        couponRequest.setChannel(activityChannelEnum.getCode());
        couponRequest.setStation_id("-1");
        couponRequest.setOperator_id("-1");
        couponRequest.setStore_id(orderBean.getShopId());
//        couponRequest.setMemberId(orderBean.getUserId());
        couponRequest.setOpenid(openId);
        // 订单号 替换成唯一序号
        couponRequest.setTrans_id(orderBean.getOid());
        couponRequest.setBusiness_date(DateUtil.convert2String(new Date(), DateUtil.FORMAT_yyyyMMdd));
        List<TransactionVO> transactions = this.getTransactionList(collect, orderBean, openId);
        // 配送券逻辑 end
        couponRequest.setTransactions(transactions);
        return couponRequest;
    }

    private List<TransactionVO> getTransactionList(List<CreateOrderAccountRequest> collect,
                                                   OrderBeanV1 orderBean,
                                                   String openId) {
        List<TransactionVO> transactions = new ArrayList<>();
        collect.forEach(accountBean -> {
            TransactionVO couponCodeVerificationTransDto = new TransactionVO();
            couponCodeVerificationTransDto.setCode(accountBean.getAccountId());
            couponCodeVerificationTransDto.setOpenId(openId);
            Integer discountPrice = accountBean.getPrice().intValue();
            couponCodeVerificationTransDto.setTotalAmount(Math.abs(discountPrice.longValue()));
            //商品券预教研
            List<ProductRedeemVO> products = new ArrayList<>();
            if (QueryOrderAccountType.PRODUCT_COUPON.getCode().equals(accountBean.getAccountType().getCode())) {
                for (int i = 0; i < orderBean.getProductList().size(); i++) {
                    ProductBeanV1 productBean = orderBean.getProductList().get(i);
                    String pid = StringUtils.isNotBlank(productBean.getSpecification()) ? productBean.getSpecification() : productBean.getProductId();
                    if (!org.springframework.util.CollectionUtils.isEmpty(orderBean.getProductList().get(i).getDiscountList())) {
                        List<ProductDiscountV1> discounts = orderBean.getProductList().get(i).getDiscountList().stream().
                                filter(productDiscount -> productDiscount.getDiscountId().equals(accountBean.getAccountId())).collect(Collectors.toList());
                        for (ProductDiscountV1 productDiscount : discounts) {
                            if (productDiscount.getDiscountType() == null || productDiscount.getDiscountType() == 0) {
                                continue;
                            }
                            ProductRedeemVO couponCodeVerificationProductDto = new ProductRedeemVO();
                            couponCodeVerificationProductDto.setPid(pid);
                            couponCodeVerificationProductDto.setConsume_num(productDiscount.getDiscountQty());
                            couponCodeVerificationProductDto.setSeq(i + 1);
                            couponCodeVerificationProductDto.setRedeem_price(new BigDecimal(productBean.getPrice()));
                            products.add(couponCodeVerificationProductDto);
                        }
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(products)) {
                couponCodeVerificationTransDto.setProducts(products);
            }
            transactions.add(couponCodeVerificationTransDto);
        });
        return transactions;
    }

    private ActivityChannelEnum orderTypeEnumConvert2ActivityChannel(Integer orderType, Integer bizType) {
        if (Objects.equals(BizTypeEnum.MALL.getBizType(), bizType)) {
            return ActivityChannelEnum.saasmall;
        }
        if (Objects.equals(OrderTypeV1.TAKE_OUT.getCode(), orderType)) {
            return ActivityChannelEnum.delivery;
        } else if (Objects.equals(OrderTypeV1.COLLECT_GOODS.getCode(), orderType) || Objects.equals(OrderTypeV1.EAT_IN.getCode(), orderType)) {
            return ActivityChannelEnum.pickup;
        } else {
            return ActivityChannelEnum.pickup;
        }
    }

    public BaseQueryOrderRequest getOrderConfirmRequest(String operator, OrderBeanV1 orderBean) {
        return this.getOrderConfirmRequest(operator, orderBean, null);
    }
}
