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

import cn.freemud.base.constant.Version;
import com.alibaba.fastjson.JSONObject;
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.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.enums.*;
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.promotioncenter.request.promotion.ActivityUpdateStockRequest;
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.domain.OrderStatesVO;
import com.freemud.sdk.api.assortment.order.domain.ResponseCodeConstant;
import com.freemud.sdk.api.assortment.order.entities.OrderEditInfo;
import com.freemud.sdk.api.assortment.order.enums.*;
import com.freemud.sdk.api.assortment.order.request.order.OrderDownloadRequest;
import com.freemud.sdk.api.assortment.order.request.order.*;
import com.freemud.sdk.api.assortment.order.response.order.*;
import com.freemud.sdk.api.assortment.order.response.payment.OrderPayResponse;
import com.freemud.sdk.api.assortment.order.util.WeightUtils;
import com.google.common.collect.Lists;
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.BeanUtils;
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;
import java.util.stream.LongStream;
import java.util.stream.Stream;

@Component
public class OrderSdkAdapter {

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


    private static final int STACK_SUB = 1;

    /**
     * 接单request
     * @param operator
     * @param orderBean
     * @return
     */
    public BaseQueryOrderRequest getOrderConfirmRequest(String operator, QueryOrdersResponse.DataBean.OrderBean orderBean){
        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());
        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,QueryOrdersResponse.DataBean.OrderBean orderBean){
        CancelOrderRequest var1 = new CancelOrderRequest();
        var1.setPartnerId(orderBean.getCompanyId());
        var1.setOrderId(orderBean.getOid());
        var1.setReason(reason);
        if (orderBean.getStatus() == 1) {
            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) ? AfterSalesOrderCreateEventEnum.REFUND_COMPLETE.getCreateEvent() : AfterSalesOrderCreateEventEnum.RETURN_COMPLETE.getCreateEvent());
        var1.setOperator(operator);
        return var1;
    }
    public CancelOrderRequest getRejectRefundRequest(String operator,String reason,QueryOrdersResponse.DataBean.OrderBean orderBean){
        CancelOrderRequest var1 = new CancelOrderRequest();
        var1.setOrderId(orderBean.getOid());
        var1.setReason(reason);
        var1.setPartnerId(orderBean.getCompanyId());
        if (orderBean.getRefundList() != null && orderBean.getRefundList().size() != 0) {
            //新订单服务需要售后单code
            var1.setAfterSalesCode(orderBean.getRefundList().get(orderBean.getRefundList().size() - 1).getRid());
        }
        var1.setOperator(operator);
        return var1;
    }

    public CancelOrderRequest convent2CancelOrderRequest(String orderId, String partnerId, AfterSalesType afterSalesType,
                                                         String reason, String trackingNo, Long refund_id) {
        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);
        if (refund_id != null) {
            cancelOrderRequest.setRefundSerialNo(refund_id.toString());
        }
        return cancelOrderRequest;
    }

    public BaseQueryOrderRequest getRefundAgreeRequest(String refund_id,String reason,String operator, QueryOrdersResponse.DataBean.OrderBean 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);
        if (orderBean.getRefundList() != null && orderBean.getRefundList().size() != 0) {
            //新订单服务需要售后单code
            var1.setAfterSalesCode(orderBean.getRefundList().get(orderBean.getRefundList().size() - 1).getRid());
        }
        return var1;
    }

    /**
     * 老订单服务创建订单对象 转换成 新订单服务请求对象
     */
    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());
        //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());
        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.setBarCounter(requestVO.getBarCounter());

        //商品信息转换
        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());
        //商品信息赋值
        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());
        deliveryContactInfoList.add(deliveryContactInfoCreateReq);
        //第三方配送信息
        getThirdDeliveryInfo(deliveryContactInfoList, requestVO.getAddInfo());
        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;
    }


    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;
    }

    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.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, orderInfo.getAddInfo());
        createOrderRequest.setDeliveryContactInfoList(deliveryContactInfoList);
        //门店渠道信息
        createOrderRequest.setOrderExtended(orderInfo.getOrderExtended());
        return createOrderRequest;
    }

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

    private Long convertCreateOrderCost(Long originalAmount, List<OrderSettlementCreateReq> orderSettlementCreateReqList, List<OrderCostCreateReq> orderCostCreateReqs, List<CreateOrderAccountRequest> accounts) {
        if (!CollectionUtils.isEmpty(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())) {
                    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);
                    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());

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

    /**
     * 转换订单费用类型
     *
     * @param queryOrderAccountType
     * @return
     */
    private Integer getCostType(QueryOrderAccountType queryOrderAccountType) {
        // 订单费用类型 1=包装费,2=运费,3=餐盒单价,4=餐盒数量,5=会员卡费用
        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;
            default:
                break;
        }

        return type;
    }

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

        orderConditionsReq.setPartnerId(queryOrdersRequest.getCompanyId());
        orderConditionsReq.setUserId(queryOrdersRequest.getUserId());
        orderConditionsReq.setPageSize(queryOrdersRequest.getPageSize());
        orderConditionsReq.setPageNum(queryOrdersRequest.getPageNumber());

        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());
            }
            if ("meals".equals(queryOrdersRequest.getSource()[i])) {
                orderClients.add(OrderClientType.WAI_MEAL.getIndex());
            }
            if ("saasmall".equals(queryOrdersRequest.getSource()[i])) {
                orderClients.add(OrderClientType.SAASMALL.getIndex());
            }
            if ("app".equals(queryOrdersRequest.getSource()[i])) {
                orderClients.add(OrderClientType.APP.getIndex());
            }
        }
        orderClients.add(OrderClientType.ALIPAY.getIndex());
        orderConditionsReq.setOrderClients(orderClients);
        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.setBizTypes(queryOrdersRequest.getBizTypes());

        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(com.freemud.application.sdk.api.ordercenter.response.BaseResponse<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;
        }

        QueryOrdersResponse.DataBean.OrderBean data = convent2NEWOrderInfo(result.getResult());
        response.setData(data);
        return response;
    }

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

        response.setOrderBeanList(orderBeanList);
        return response;
    }

    /**
     * 新订单服务查询父子订单返回对象 转换成 老订单服务创建返回对象
     */
    public QueryRelatedOrderByCodeResp convent2QueryFatherOrderInfo(BaseResponse<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<QueryOrdersResponse.DataBean.OrderBean> orderBeanList = new ArrayList<>();
        result.getResult().forEach(orderInfoReqs -> {
            QueryOrdersResponse.DataBean.OrderBean orderBean = 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;
        }
        QueryOrdersResponse.DataBean.OrderBean data = 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;
        }
        QueryOrdersResponse.DataBean.OrderBean data = convent2NEWOrderInfo(result.getResult());
        response.setData(data);
        return response;
    }


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

        //新订单服务优惠信息集合
        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;
                }
                QueryOrdersResponse.DataBean.OrderBean.AccountBean accountBean = new QueryOrdersResponse.DataBean.OrderBean.AccountBean();
                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("");
                accountBean.setPlatformDiscountAmount(orderSettlementResp.getPlatformDiscountAmount());
                accountBean.setShopDiscountAmount(orderSettlementResp.getShopDiscountAmount());
                accountList.add(accountBean);
            }
        }

        //新订单 订单费用信息集合 餐盒费和包装费
        List<OrderCostResp> orderCostResps1 = orderCostResps == null ? new ArrayList<>() : orderCostResps;
        for (OrderCostResp orderCostResp : orderCostResps1) {
            QueryOrdersResponse.DataBean.OrderBean.AccountBean accountBean = new QueryOrdersResponse.DataBean.OrderBean.AccountBean();
            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());
            }
            accountBean.setAddInfo("");
            accountList.add(accountBean);
        }
        return accountList;
    }

    /**
     * 老订单服务商品信息转化 order_product 和produce_discount 表
     */
    private List<QueryOrdersResponse.DataBean.OrderBean.ProductBean> getOldOrderProductList(List<OrderSettlementResp> orderSettlementResps,
                                                                                            List<OrderItemResp> orderItemList) {
        List<QueryOrdersResponse.DataBean.OrderBean.ProductBean> productList = new ArrayList<QueryOrdersResponse.DataBean.OrderBean.ProductBean>();
        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) {
            QueryOrdersResponse.DataBean.OrderBean.ProductBean 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)));
            }
            productList.add(productBean);
        }
        return productList;
    }

    private QueryOrdersResponse.DataBean.OrderBean.ProductBean getOldOrderProduct(List<OrderSettlementResp> orderSettlementResps, OrderItemResp orderItemResp) {
        QueryOrdersResponse.DataBean.OrderBean.ProductBean productBean = new QueryOrdersResponse.DataBean.OrderBean.ProductBean();
        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.setSpecification(orderItemResp.getProductSpec());
        productBean.setSpecificationName(orderItemResp.getProductSpecName());
        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());
        productBean.setAddInfo(JSONObject.toJSONString(map));
        productBean.setProductProperty(orderItemResp.getProductProperty());
        productBean.setExtInfo(orderItemResp.getExtInfo());

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

        List<QueryOrdersResponse.DataBean.OrderBean.ProductBean.ProductDiscount> discountList = new ArrayList<QueryOrdersResponse.DataBean.OrderBean.ProductBean.ProductDiscount>();
        List<OrderSettlementResp> orderSettlementResps1 = orderSettlementResps == null ? new ArrayList<>() : orderSettlementResps;
        for (OrderSettlementResp orderSettlementResp : orderSettlementResps1) {
            if (ObjectUtils.equals(orderItemResp.getProductSeq(), orderSettlementResp.getProductSeq()) && orderItemResp.getProductSpec().equals(orderSettlementResp.getProductId())) {
                QueryOrdersResponse.DataBean.OrderBean.ProductBean.ProductDiscount productDiscount = new QueryOrdersResponse.DataBean.OrderBean.ProductBean.ProductDiscount();
                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("");
                productDiscount.setProductId(orderSettlementResp.getProductId());
                discountList.add(productDiscount);
            }
        }
        productBean.setDiscountList(discountList);
        return productBean;
    }

    private List<QueryOrdersResponse.DataBean.OrderBean.RefundBean> getOldOrderRefundList(List<AfterSalesOrderResp> afterSalesOrderRespList) {
        List<QueryOrdersResponse.DataBean.OrderBean.RefundBean> refundBeans = new ArrayList<>();
        for (AfterSalesOrderResp afterSalesOrderResp : afterSalesOrderRespList) {
            QueryOrdersResponse.DataBean.OrderBean.RefundBean refundBean = new QueryOrdersResponse.DataBean.OrderBean.RefundBean();
            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());
            refundBeans.add(refundBean);
        }
        return refundBeans;
    }

    private List<QueryOrdersResponse.DataBean.OrderBean.OperationHistory> getOrderOperationHistory(List<OrderOperationHistoryResp> orderOperationHistoryResps) {
        List<QueryOrdersResponse.DataBean.OrderBean.OperationHistory> operationHistories = new ArrayList<>();
        if (orderOperationHistoryResps == null) {
            return operationHistories;
        }
        for (OrderOperationHistoryResp operationHistoryResp : orderOperationHistoryResps) {
            QueryOrdersResponse.DataBean.OrderBean.OperationHistory operationHistory = new QueryOrdersResponse.DataBean.OrderBean.OperationHistory();
            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<QueryOrdersResponse.DataBean.OrderBean> orders = new ArrayList<>();
        for (OrderInfoReqs orderInfoReqs : baseDownLoadResponse.getResult()) {
            QueryOrdersResponse.DataBean.OrderBean data = convent2NEWOrderInfo(orderInfoReqs);
            orders.add(data);
        }
        dataBean.setOrders(orders);
        response.setData(dataBean);
        return response;
    }

    /**
     * 信息订单信息 转化成 老订单信息
     */
    public QueryOrdersResponse.DataBean.OrderBean convent2NEWOrderInfo(OrderInfoReqs orderInfoReqs) {
        QueryOrdersResponse.DataBean.OrderBean data = new QueryOrdersResponse.DataBean.OrderBean();

        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.getIsNeedInvoice());
        data.setOriginalAmount(orderInfoReqs.getOriginalAmount());
        QueryOrdersResponse.DataBean.OrderBean.AddDeliveryInfo addInfo = new QueryOrdersResponse.DataBean.OrderBean.AddDeliveryInfo();
        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());

        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.setAddress(orderInfoReqs.getDeliveryContactInfoList().get(0).getAddressDetail());
                    data.setPhone(orderInfoReqs.getDeliveryContactInfoList().get(0).getMobile());
                    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.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()));
            }

        } 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.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<QueryOrdersResponse.DataBean.OrderBean.ProductBean> productList = getOldOrderProductList(orderInfoReqs.getOrderSettlementDetailList(), orderInfoReqs.getOrderItemList());
        data.setProductList(productList);

        List<QueryOrdersResponse.DataBean.OrderBean.AccountBean> accountList = getOldOrderAccountList(orderInfoReqs.getOrderSettlementDetailList(), orderInfoReqs.getOrderCostDetailList());
        data.setAccountList(accountList);

        if (orderInfoReqs.getAfterSalesOrderList() != null && orderInfoReqs.getAfterSalesOrderList().size() != 0) {
            List<QueryOrdersResponse.DataBean.OrderBean.RefundBean> refundList = getOldOrderRefundList(orderInfoReqs.getAfterSalesOrderList());
            data.setRefundList(refundList);
        }
        data.setOrderOperationHistoryList(getOrderOperationHistory(orderInfoReqs.getOrderOperationHistoryList()));
        data.setApportionDetails(getApportionDetails(orderInfoReqs));
        data.setOrderSettlementDetailList(orderInfoReqs.getOrderSettlementDetailList());
        data.setExpressChannelName(orderInfoReqs.getExpressChannelName());
        //费用信息
        data.setOrderCostDetailList(orderInfoReqs.getOrderCostDetailList());
        data.setExpressChannelName(orderInfoReqs.getExpressChannelName());
        //发票信息
        data.setOrderInvoice(orderInfoReqs.getOrderInvoice());

        return data;
    }

    public QueryOrdersResponse convent2QueryOrdersResponse(BaseResponse<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<QueryOrdersResponse.DataBean.OrderBean> orders = new ArrayList<>();
        for (OrderInfoReqs orderInfoReqs : queryOrderForUserResp.getItemList()) {
            QueryOrdersResponse.DataBean.OrderBean data = convent2NEWOrderInfo(orderInfoReqs);
            orders.add(data);
        }
        dataBean.setOrders(orders);
        response.setData(dataBean);
        return response;
    }

    public PayAccessResponse convent2PayAccessResponse(BaseResponse<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(BaseResponse 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(BaseResponse<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=外卖加价购,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 "PRODUCT_COUPON":
                type = 118;
                break;
            case "DISCOUNT_COUPON":
                type = 208;
                break;
            case "DISCOUNT_AMOUNT":
                type = 206;
                break;
            case "PREMIUM_EXCHANGE":
                type = 46;
                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;
            default:
                break;
        }
        return type;
    }

    /**
     * 老订单类型转换新订单类型
     */
    public Integer getNewOrderType(QueryOrderType orderType, Long gmtExpect) {
        //订单服务订单类型 1=外卖 4=自提，5=堂食
        //外卖平台订单类型 1=常规堂食，2=预约堂食，3=常规外送，4=预约外送，5=常规自取，6=预约自取
        Integer type = 0;
        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;
    }

    public Integer getNewOrderClient(String name) {
        String _name = OrderSourceType.SAAS.getCode();
        Integer orderClientType;
        switch (name) {
            case "saas":
                orderClientType = 2;
                break;
            case "alipay":
                orderClientType=3;
                break;
            case "jdwm":
                orderClientType = 10;
                break;
            case "mtwm":
                orderClientType = 11;
                break;
            case "eleme":
                orderClientType = 8;
                break;
            case "bdwm":
                orderClientType = 9;
                break;
            case "ebwm":
                orderClientType = 9;
                break;
            case "saas_member":
                orderClientType = 13;
                break;
            case "saas_order":
                orderClientType = 14;
                break;
            case "pos":
                orderClientType = 15;
                break;
            case "meal":
                orderClientType = 19;
                break;
            case "saasmall":
                orderClientType = 23;
                break;
            case "app":
                orderClientType = 12;
                break;
            case "fmwd":
                orderClientType = 25;
                break;
            case "parking":
                orderClientType = 99;
                break;
            default:
                orderClientType = OrderClientType.SAAS.getIndex();
                break;
        }
        return orderClientType;
    }

    public String getOldSource(Integer orderClientType) {
        String name = "";
        switch (orderClientType) {
            case 2:
                name = "saas";
                break;
            case 3:
                name="alipay";
                break;
            case 10:
                name = "jdwm";
                break;
            case 11:
                name = "mtwm";
                break;
            case 8:
                name = "eleme";
                break;
            case 9:
                name = "bdwm";
                break;
            case 13:
                name = "saas_member";
                break;
            case 14:
                name = "saas_order";
                break;
            case 15:
                name = "pos";
                break;
            case 19:
                name = "meals";
                break;
            case 23:
                name = "saasmall";
                break;
            case 12:
                name = "app";
                break;
            case 25:
                name = "fmwd";
                break;
            case 99:
                name = "parking";
                break;
            default:
                name = orderClientType.toString();
                break;
        }

        return name;
    }

    public String getOldSourceName(Integer orderClientType) {
        String name = "";
        switch (orderClientType) {
            case 2:
                name = "saas 点餐";
                break;
            case 3:
                name="支付宝";
                break;
            case 10:
                name = "京东";
                break;
            case 11:
                name = "美团外卖";
                break;
            case 8:
                name = "饿了么";
                break;
            case 9:
                name = "饿百";
                break;
            case 13:
                name = "i 会员订单";
                break;
            case 15:
                name = "pos";
                break;
            case 19:
                name = "saas 围餐";
                break;
            case 23:
                name = "saas 商城";
                break;
            case 12:
                name = "APP";
                break;
            case 25:
                name = "非码微店";
                break;
            case 99:
                name = "农工商停车";
                break;
            default:
                break;
        }

        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;
    }

    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(BaseResponse 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<QueryOrdersResponse.DataBean.OrderBean> orders = new ArrayList<>();
        for (OrderInfoReqs orderInfoReqs : queryOrderForUserResp.getOrderPosRespList()) {
            QueryOrdersResponse.DataBean.OrderBean data = 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(QueryOrdersResponse.DataBean.OrderBean 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;
    }

    public ActivityUpdateStockRequest convert2ActivityUpdateStockRequest(QueryOrdersResponse.DataBean.OrderBean 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");
        return activityUpdateStockRequest;
    }

    /**
     * 订单下载转换对象
     */
    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(), OldOrderType.TAKE_OUT.getCode())) {
            orderTypes.add(OrderType.GENERAL_EXPRESS.getIndex());
            orderTypes.add(OrderType.RESERVED_EXPRESS.getIndex());
        }
        //自提
        if (Objects.equals(request.getOrderType(), OldOrderType.COLLECT_GOODS.getCode())) {
            orderTypes.add(OrderType.GENERAL_SELF_PICKUP.getIndex());
            orderTypes.add(OrderType.RESERVED_SELF_PICKUP.getIndex());
        }
        //堂食
        if (Objects.equals(request.getOrderType(), OldOrderType.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(BaseResponse<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(PayStatus.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(), NewOrderType.GENERAL_EXPRESS.getCode()) || ObjectUtils.equals(orderDto.getOrderType(), NewOrderType.RESERVED_EXPRESS.getCode())) {
                    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(BaseResponse<StoreOrderStatisticResp> result) {
        GetStatisticStoreOrderReportResponse response = new GetStatisticStoreOrderReportResponse();
        response.setErrcode(Integer.parseInt(result.getCode()));
        response.setErrmsg(result.getMessage());
        if (result.getResult() == null) {
            return response;
        }
        GetStatisticStoreOrderReportResponse.OrderBean data = new GetStatisticStoreOrderReportResponse.OrderBean();
        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
     */
    private 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 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();
            case 220:
                newOrderAccountType=OldOrderAccountType.MEMBER_PRICE_DISCOUNT.getCode();
            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(BaseResponse<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(BaseResponse<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<QueryOrdersResponse.DataBean.OrderBean> itemList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(result.getItemList())) {
            for (OrderInfoReqs orderInfoReqs : result.getItemList()) {
                QueryOrdersResponse.DataBean.OrderBean orderBean = convent2NEWOrderInfo(orderInfoReqs);
                itemList.add(orderBean);
            }
        }
        response.setItemList(itemList);

        return response;

    }

    /**
     * 积分扣减或冲正
     *
     * @param orderBean 订单
     * @param accounts  订单优惠明细
     * @param isReduce  是否扣减：true扣减；false冲正
     * @return
     */
    public UserScoreRequest convent2UserScoreRequest(QueryOrdersResponse.DataBean.OrderBean 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(QueryOrdersResponse.DataBean.OrderBean 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++) {
                QueryOrdersResponse.DataBean.OrderBean.ProductBean 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<QueryOrdersResponse.DataBean.OrderBean.ProductBean.ProductDiscount> discounts = orderBean.getProductList().get(i).getDiscountList().stream().
                            filter(productDiscount -> productDiscount.getDiscountId().equals(accountBean.getAccountId())).collect(Collectors.toList());
                    for (QueryOrdersResponse.DataBean.OrderBean.ProductBean.ProductDiscount 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(OldOrderType.TAKE_OUT.getCode(), orderBean.getType())?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());
        return queryRelatedOrderByCodeReq;
    }

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

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

    public BaseOrderResponse convent2NewOrderUpdateThirdOrderCode(BaseResponse updateThirdOrderCode) {
        BaseOrderResponse baseOrderResponse = new BaseOrderResponse();
        baseOrderResponse.setErrcode(updateThirdOrderCode.getCode() != null ? Integer.parseInt(updateThirdOrderCode.getCode()) : 500);
        baseOrderResponse.setErrmsg(updateThirdOrderCode.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(requestVO.getOrderType() == null ? 1 : getNewOrderType(requestVO.getOrderType(), null));
        request.setPartnerId(requestVO.getCompanyId());
        request.setStoreId(requestVO.getShopId());
        request.setOrderClient(requestVO.getOrderClient());
        request.setCompanySelfCode(requestVO.getThirdOrderCode());
        request.setStoreName(requestVO.getShopName());
        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.BaseResponse<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.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(settlementAmount);
            request.setSettlementAmount(settlementAmount);
        }
        //商品信息赋值
        request.setOrderItemList(orderItemList);
        request.setOperator(requestVO.getOperator());
        return request;
    }

    /**
     * 使用购物车商品信息  更新订单商品明细和优惠明细
     *
     * @param orderItemList                订单商品明细（返回）
     * @param orderSettlementCreateReqList 优惠明细（返回）
     * @param orderCostCreateReqs          费用明细（返回）
     * @param products                     购物车商品信息（入参）
     * @param partnerId                    商户号（入参）
     * @param accounts                     订单优惠和费用（入参）
     * @return 订单金额
     */
    private 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(orderItemList, orderSettlementCreateReqList, productRequest, partnerId, "");
            // 如果是套餐商品，需要转换当前商品行子集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())) {
                    productRequest.getComboProduct().forEach(combo -> updateOrderItemAndSettlement(orderItemList, orderSettlementCreateReqList, combo, partnerId, partnerProductId));
                }
            }
            index++;
        }
        return originalAmount;
    }

    /**
     * 更新当前商品行，订单商品明细和优惠明细
     *
     * @param orderItemList                订单商品明细
     * @param orderSettlementCreateReqList 优惠明细
     * @param product                      当前商品行
     * @param partnerId                    商户号
     * @param parentProductId              套餐父商品Id
     * @return
     */
    private Long updateOrderItemAndSettlement(List<OrderItemCreateReq> orderItemList, List<OrderSettlementCreateReq> orderSettlementCreateReqList, CreateOrderProductRequest product, String partnerId, String parentProductId) {
        OrderItemCreateReq orderItemCreateReq = new OrderItemCreateReq();
        orderItemCreateReq.setId(product.getId());
        orderItemCreateReq.setPartnerId(partnerId);
        orderItemCreateReq.setProductName(product.getProductName());
        orderItemCreateReq.setProductId(product.getProductId());
        orderItemCreateReq.setProductSpec(product.getSpecification());
        orderItemCreateReq.setProductSpecName(product.getSpecificationName());
        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);
            /**
             * 套餐商品
             * 套餐原价 = 子商品总原价（称重菜原价*重量+普通商品原价*数量+可选商品原价*数量）
             * 套餐结算价 = (套餐价设置为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;
                        }
                    }
                    // 套餐原价
                    orderItemCreateReq.setProductPrice(setmealProductTotalOriginalAmount / product.getNumber());
                    // 如果套餐没有设置价格取子商品结算价和，否则取套餐自身的结算价
                    setmealTotalSettlementPrice = product.getPrice() == 0 ? setmealTotalSettlementPrice : settlementPrice;
                    orderItemCreateReq.setSettlementPrice(setmealTotalSettlementPrice);
                    orderItemCreateReq.setSalePrice(setmealTotalSettlementPrice / product.getNumber());
                    totalOriginalProductAmount = setmealProductTotalOriginalAmount;
                }
            }
        }
        orderItemCreateReq.setProductSharePrice(totalDiscountAmount / product.getNumber());
        orderItemCreateReq.setProductUnit(product.getUnit());
        //获取商品属性
        OrderProductAddInfoDto addInfo = JSONObject.parseObject(product.getAddInfo(), OrderProductAddInfoDto.class);
        orderItemCreateReq.setProductProperty(addInfo.getAttributeNames());
        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.getCategory())){
            extInfo.setThirdCensusCategoryId(product.getCategory());
        }
        extInfo.setStapleFood(product.getStapleFood());
        //if (product.getStapleFood()!=null && product.getStapleFood()>0) {
        //    extInfo.setStapleFood(1);
        //}
        // todo 订单行扩展字段商品组
        extInfo.setProductGroupList(product.getProductGroupList());

        orderItemCreateReq.setExtInfo(JSONObject.toJSONString(extInfo));
        orderItemList.add(orderItemCreateReq);
        if (product.getTotalDiscountAmount() != null && product.getTotalDiscountAmount() > 0L) {
            //优惠信息转换
            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());
                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());
        return assortmentGroupUpdateOrderRequest;
    }

    public CreateOrderProductRequest convertOrderBeanProductBean2CreateOrderProductRequest(QueryOrdersResponse.DataBean.OrderBean.ProductBean productBean, String trackingNo) {
        CreateOrderProductRequest createOrderProductRequest = new CreateOrderProductRequest();
        createOrderProductRequest.setProductCode(productBean.getProductCode());
        createOrderProductRequest.setProductName(productBean.getProductName());
        createOrderProductRequest.setNumber(productBean.getNumber());
        createOrderProductRequest.setParentProductId(productBean.getParentProductId());
        createOrderProductRequest.setTrackingNo(trackingNo);
        createOrderProductRequest.setAddInfo(productBean.getAddInfo());
        createOrderProductRequest.setProductId(productBean.getProductId());
        createOrderProductRequest.setSpecification(productBean.getSpecification());
        createOrderProductRequest.setSpecificationName(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<QueryOrdersResponse.DataBean.OrderBean.OrderSettlement> getApportionDetails(OrderInfoReqs orderInfoReqs) {
        List<QueryOrdersResponse.DataBean.OrderBean.OrderSettlement> 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) {
                QueryOrdersResponse.DataBean.OrderBean.OrderSettlement orderSettlement = new QueryOrdersResponse.DataBean.OrderBean.OrderSettlement();
                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(null);
                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());
                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
     */
    private 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;
    }
}
