package cn.freemud.adapter;

import cn.freemud.base.util.DateUtil;
import cn.freemud.constant.CustomerScoreConstant;
import cn.freemud.entities.bo.CreateOrderBo;
import cn.freemud.entities.dto.StoreResponseDto;
import cn.freemud.entities.dto.UserDeliveryInfoDto;
import cn.freemud.entities.dto.order.CreatePrepayRequestDto;
import cn.freemud.entities.dto.pay.CombPayResponse;
import cn.freemud.entities.dto.pay.OrderPayResponse;
import cn.freemud.entities.dto.product.AttributeValue;
import cn.freemud.entities.dto.product.GroupDetail;
import cn.freemud.entities.dto.product.ProductAttributeGroup;
import cn.freemud.entities.dto.product.ProductGroup;
import cn.freemud.entities.dto.shoppingCart.ActivityDiscountsDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.ttpay.OrderInfo;
import cn.freemud.entities.vo.CreateOrderBaseVo;
import cn.freemud.entities.vo.CreateOrderResponseVo;
import cn.freemud.entities.vo.CreateOrderVo;
import cn.freemud.entities.vo.GetProductsVo;
import cn.freemud.entities.vo.order.CreateOrderUnionPayCardVo;
import cn.freemud.enums.*;
import cn.freemud.interceptor.ServiceException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.application.sdk.api.couponcenter.offline.request.CouponLockRequest;
import com.freemud.application.sdk.api.membercenter.request.UserScoreRequest;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.entities.v1.ProductBeanV1;
import com.freemud.application.sdk.api.ordercenter.enums.AfterSalesType;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.enums.PayChannelType;
import com.freemud.application.sdk.api.ordercenter.enums.ProductTypeEnum;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtendedReq;
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.orderInfo.OrderPayItemResp;
import com.freemud.application.sdk.api.stockapi.domain.ProductStocksVO;
import com.freemud.application.sdk.api.stockapi.request.UpdateStocksRequest;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.sdk.api.assortment.order.enums.OldOrderAccountType;
import com.freemud.sdk.api.assortment.order.enums.QueryDeliveryType;
import com.freemud.sdk.api.assortment.order.enums.QueryOrderAccountType;
import com.freemud.sdk.api.assortment.order.enums.StockChangeType;
import com.freemud.sdk.api.assortment.order.request.order.*;
import com.freemud.sdk.api.assortment.order.request.payment.CombPayRequest;
import com.freemud.sdk.api.assortment.order.request.payment.PayPlatformVO;
import com.freemud.sdk.api.assortment.order.request.payment.ProductVO;
//import com.freemud.sdk.api.assortment.order.response.payment.OrderPayResponse;
import com.freemud.sdk.api.assortment.order.util.ClassUtils;
import com.freemud.sdk.api.assortment.order.util.WeightUtils;
import com.freemud.sdk.api.assortment.order.vo.ProductGroupVo;
import com.freemud.sdk.api.assortment.payment.request.UnifiedOrderRequest;
import com.freemud.sdk.api.assortment.payment.response.UnifiedOrderResponse;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

@Component
public class CreateOrderAdapter {

    @Value("${mccafe.partner.id}")
    private String mcCafePartnerId;

    public CreatePrepayRequestDto convertToCreatePrepayRequestDto(CreateOrderBo createOrderBo) {
        switch (createOrderBo.getCreateOrderScene()) {
            case SAAS:
                return convertToUniversalCreatePrepayRequestDto(createOrderBo);
            default:
                return convertToUniversalCreatePrepayRequestDto(createOrderBo);
        }
    }

    public CreatePrepayRequestDto convertToUniversalCreatePrepayRequestDto(CreateOrderBo createOrderBo) {
        CreatePrepayRequestDto requestDto = new CreatePrepayRequestDto();
        requestDto.setPartnerId(createOrderBo.getCreateOrderBaseVo().getPartnerId());
        requestDto.setWxAppId(createOrderBo.getUserLoginInfoDto().getWxAppId());
        requestDto.setOpenId(createOrderBo.getUserLoginInfoDto().getOpenId());
        requestDto.setFaceCode(createOrderBo.getCreateOrderBaseVo().getFaceCode());
        requestDto.setCardCode(createOrderBo.getCreateOrderBaseVo().getCardCode());
        requestDto.setPayCode(null);
        requestDto.setFatherOrderBean(createOrderBo.getCreateOrderOperateDto().getFatherOrderBean());
        requestDto.setProductOrderBean(createOrderBo.getCreateOrderOperateDto().getProductOrderBean());
        requestDto.setTotalAmount(createOrderBo.getCreateOrderOperateDto().getTotalAmount()== null ? 0 : createOrderBo.getCreateOrderOperateDto().getTotalAmount());
        requestDto.setCardAmount(createOrderBo.getCreateOrderOperateDto().getCardAmount()== null ? 0 : createOrderBo.getCreateOrderOperateDto().getCardAmount());
        requestDto.setOrderExtInfoDTO(createOrderBo.getExtInfo());
        requestDto.setTransId(createOrderBo.getCreateOrderOperateDto().getFatherOrderBean().getOid());
        requestDto.setOrderClient(null);
        // 转换 fisherman begin
        CreateOrderBaseVo.UnionPayCard unionPayCard = createOrderBo.getCreateOrderBaseVo().getUnionPayCard();
        if (unionPayCard != null) {
            CreateOrderUnionPayCardVo u = new CreateOrderUnionPayCardVo();
            u.setCode(unionPayCard.getCode());
            u.setPassword(unionPayCard.getPassword());
            requestDto.setUnionPayCard(u);
        }
        // 转换 fisherman end
        requestDto.setStoreId(createOrderBo.getCreateOrderBaseVo().getShopId());
        requestDto.setChannel(createOrderBo.getCreateOrderBaseVo().getChannel());
        return requestDto;
    }

    /**
     * 支付信息转换
     */
    public UnifiedOrderRequest convent2UnifiedOrderRequest(OrderBeanV1 orderBean, PaymentRequest paymentRequest, Long amount, Integer cardAmount, String transId, String partnerPayOvertime) {
        UnifiedOrderRequest orderPayDto = new UnifiedOrderRequest();
        orderPayDto.setPartnerId(orderBean.getCompanyId());
        orderPayDto.setBody(paymentRequest.getPrincipalName());
        orderPayDto.setNotifyUrl(paymentRequest.getReverseNotifyiDcUrl());
        orderPayDto.setStoreId(orderBean.getShopId());
        orderPayDto.setTransId(transId);
        orderPayDto.setOpenId(paymentRequest.getOpenId());
        String businessDate = com.freemud.application.sdk.api.util.DateUtil.convert2String(new Date(), "yyyyMMdd");
        orderPayDto.setBusinessDate(businessDate);
        orderPayDto.setAmount(amount);
        orderPayDto.setUndisAmount(1L);
        orderPayDto.setVipAmount(Long.valueOf(cardAmount));
        orderPayDto.setAppId(paymentRequest.getWxAppId());
        orderPayDto.setPayTimeOutTime(StringUtils.defaultIfBlank(partnerPayOvertime, "30"));
        List<UnifiedOrderRequest.ProductBean> productBeans = new ArrayList<UnifiedOrderRequest.ProductBean>();
        if (CollectionUtils.isNotEmpty(orderBean.getProductList())) {
            orderBean.getProductList().forEach(orderProductBean -> {
                UnifiedOrderRequest.ProductBean productBean = new UnifiedOrderRequest.ProductBean();
                productBean.setPid(orderProductBean.getProductId());
                productBean.setConsumeNum(orderProductBean.getNumber());
                productBean.setSeq(orderProductBean.getSequence());
                productBean.setSalesType("NORMAL");
                productBean.setPrice(orderProductBean.getPrice());
                productBean.setName(orderProductBean.getProductName());
                productBeans.add(productBean);
            });
        }
        orderPayDto.setProducts(productBeans);
        orderPayDto.setPayCode(paymentRequest.getPayCode());
        //抖音支付的payCode = 10066
        if (OrderClientType.TIKTOKPAY.getIndex().toString().equalsIgnoreCase(orderBean.getOrderClient())) {
            orderPayDto.setPayCode(PayChannelType.TIKTOKPAY.getEbcode());
        }
        orderPayDto.setFoodOrderType(getFoodOrderType(orderBean.getOrderType()));
        return orderPayDto;
    }

    /**
     * 预支付接口获取类型
     *
     * @return
     */
    private String getFoodOrderType(Integer orderType) {
        //1=外卖 4=自提，5=堂食
        //qr_order（店内扫码点餐）,pre_order（预点到店自提）,home_delivery （外送到家）
        String foodOrderType;
        switch (orderType) {
            case 1:
                foodOrderType = "home_delivery";
                break;
            case 4:
                foodOrderType = "pre_order";
                break;
            case 5:
            default:
                foodOrderType = "qr_order";
                break;
        }
        return foodOrderType;
    }

    public OrderPayResponse convent2OrderPayResponse(UnifiedOrderResponse unifiedOrderResponse) {
        OrderPayResponse responseDto = new OrderPayResponse();
        responseDto.setFmId(unifiedOrderResponse.getFmId());
        responseDto.setMsg(unifiedOrderResponse.getMsg());
        responseDto.setPayEbcode(unifiedOrderResponse.getPayEbcode());
        responseDto.setPayId(unifiedOrderResponse.getPayId());
        UnifiedOrderResponse.PayOrderBean payOrderBean = unifiedOrderResponse.getPayOrder();
        if (null != payOrderBean) {
            OrderPayResponse.PayOrderBean payBean = new OrderPayResponse.PayOrderBean();
            payBean.setAppid(payOrderBean.getAppid());
            payBean.setNonceStr(payOrderBean.getNonceStr());
            payBean.setPackageX(payOrderBean.getPackageX());
            payBean.setSign(payOrderBean.getSign());
            payBean.setSignType(payOrderBean.getSignType());
            payBean.setTimestamp(payOrderBean.getTimestamp());
            payBean.setAliPayOrder(payOrderBean.getAliPayOrder());
            responseDto.setPayOrder(payBean);
            // coco 机场支付
            try {
                JSONObject jsonObject = JSONObject.parseObject(payOrderBean.getAliPayOrder());
                responseDto.setSellerId(jsonObject.getString("sellerId"));
                responseDto.setPayNotifyUrl(jsonObject.getString("payNotifyUrl"));
                responseDto.setEbCode(jsonObject.getString("ebCode"));
            } catch (Exception e) {

            }
        }
        responseDto.setStatusCode(unifiedOrderResponse.getStatusCode());
        responseDto.setPayTransId(unifiedOrderResponse.getPayTransId());
        responseDto.setThirdOrderToken(unifiedOrderResponse.getOrderToken());
        responseDto.setThirdOrderId(unifiedOrderResponse.getOrderId());
        return responseDto;
    }

    public OrderPayResponse getOrderPayResponse(String partnerId, PaymentRequest paymentRequest, String orderId, String fmId) {
        OrderPayResponse orderPayResponse = new OrderPayResponse();
        orderPayResponse.setWxAppid(paymentRequest.getWxAppId());
        orderPayResponse.setOpenId(paymentRequest.getOpenId());
        orderPayResponse.setPartnerId(partnerId);
        orderPayResponse.setOrderId(orderId);
        orderPayResponse.setFmId(fmId);
        orderPayResponse.setPayChannelType(PayChannelType.ZERO);
        return orderPayResponse;
    }

    public CancelOrderRequest convent2CancelOrderRequest(String orderId, String partnerId, AfterSalesType afterSalesType,
                                                         String reason, String trackingNo, String refundId) {
        CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
        cancelOrderRequest.setOrderId(orderId);
        cancelOrderRequest.setPartnerId(partnerId);
        cancelOrderRequest.setAfterSalesType(afterSalesType);
        cancelOrderRequest.setReason(reason);
        cancelOrderRequest.setTrackingNo(trackingNo);
        cancelOrderRequest.setRefundSerialNo(refundId);
        if (AfterSalesType.SYSTEM_CANCEL.getIndex().equals(afterSalesType.getIndex())) {
            cancelOrderRequest.setOperator("admin");
        }
        //若为4，默认做【创建】+【同意并退款完成】，售后单状态为【完成】
        cancelOrderRequest.setCreateEvent(4);
        return cancelOrderRequest;
    }

    /**
     * 父子订单转换前端支付需要的信息
     *
     * @param orderPayResponse
     * @param
     * @return
     */
    public CreateOrderResponseVo convent2CreateFatherSonOrderResponseVo(OrderPayResponse orderPayResponse, OrderBeanV1 orderBean) {
        CreateOrderResponseVo createOrderResponseVo = new CreateOrderResponseVo();
        createOrderResponseVo.setOid(orderBean.getOid());
        createOrderResponseVo.setWxappId(orderPayResponse.getWxAppid());
        createOrderResponseVo.setFmId(orderPayResponse.getFmId());
        OrderPayResponse.PayOrderBean payOrderBean = orderPayResponse.getPayOrder();
        createOrderResponseVo.setTimestamp(payOrderBean == null ? "" : payOrderBean.getTimestamp());
        createOrderResponseVo.setNonceStr(payOrderBean == null ? "" : payOrderBean.getNonceStr());
        createOrderResponseVo.setPackageX(payOrderBean == null ? "" : payOrderBean.getPackageX());
        createOrderResponseVo.setSignType(payOrderBean == null ? "" : payOrderBean.getSignType());
        createOrderResponseVo.setSign(payOrderBean == null ? "" : payOrderBean.getSign());
        //微信新版订阅消息判断新加字段
        if (orderBean != null && orderBean.getType() != null) {
            createOrderResponseVo.setOrderType(getNewOrderType(orderBean.getType(), orderBean.getGmtExpect()));
        }
        createOrderResponseVo.setOrderStr(payOrderBean == null ? "" : payOrderBean.getAliPayOrder());
        //抖音支付添加返回OrderInfo
        if (String.valueOf(PayChannelType.TIKTOKPAY.getIndex()).equals(orderBean.getPayChannelType())) {
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrder_id(orderPayResponse.getThirdOrderId());
            orderInfo.setOrder_token(orderPayResponse.getThirdOrderToken());
            createOrderResponseVo.setOrderInfo(orderInfo);
        }

        return createOrderResponseVo;
    }


    public Integer getOldOrderType(Integer orderType, Integer reachStoreType) {
        if (orderType == 1) {
            if (null == reachStoreType) {
                return 4;
            } else {
                return reachStoreType;
            }
        } else if (orderType == 2) {
            return 1;
        } else {
            throw new ServiceException(ResponseResult.PARAMETER_MISSING, "非法的订单类型");
        }
    }

    /**
     * 新老订单类型转换
     *
     * @return
     */
    public Integer getNewOrderType(Integer orderType, Long gmtExpect) {
        //老订单服务订单类型 1=外卖 4=自提，5=堂食
        //新订单服务订单类型 1=常规堂食，2=预约堂食，3=常规外送，4=预约外送，5=常规自取，6=预约自取
        Integer type = 0;
        switch (orderType) {
            case 1:
                if (gmtExpect == null || gmtExpect == 0L) {
                    type = 3;
                } else {
                    type = 4;
                }
                break;
            case 4:
                if (gmtExpect == null || gmtExpect == 0L) {
                    type = 5;
                } else {
                    type = 6;
                }
                break;
            case 5:
                if (gmtExpect == null || gmtExpect == 0L) {
                    type = 1;
                } else {
                    type = 2;
                }
                break;
            default:
                break;
        }

        return type;
    }

    public CombPayRequest convent2CombPayOrderRequest(String cardNo
            , OrderBeanV1 orderBean
            , PaymentRequest paymentRequest
            , String partnerPayOvertime
            , String orderClient
            , String channel
            , Integer totalAmount) {
        CombPayRequest orderPayDto = new CombPayRequest();
        orderPayDto.setEbCode(paymentRequest.getPayCode());
        orderPayDto.setPartner_id(orderBean.getCompanyId());
        orderPayDto.setBody(paymentRequest.getPrincipalName());
        orderPayDto.setNotify_url(paymentRequest.getReverseNotifyiDcUrl());
        orderPayDto.setStore_id(orderBean.getShopId());
        orderPayDto.setOpen_id(paymentRequest.getOpenId());
        String businessDate = com.freemud.application.sdk.api.util.DateUtil.convert2String(new Date(), "yyyyMMdd");
        orderPayDto.setBusiness_date(businessDate);
        orderPayDto.setAmount(totalAmount.longValue());
        orderPayDto.setVip_amount(0L);
        orderPayDto.setAppId(paymentRequest.getWxAppId());
        orderPayDto.setPayCode(paymentRequest.getPayCode());
        orderPayDto.setVer("V1");
        orderPayDto.setStoreName(orderBean.getShopName());
        orderPayDto.setPayTimeOutTime(StringUtils.defaultIfBlank(partnerPayOvertime, "30"));
        List<ProductVO> productVOS = new ArrayList<ProductVO>();
        if (CollectionUtils.isNotEmpty(orderBean.getProductList())) {
            for (ProductBeanV1 product : orderBean.getProductList()) {
                ProductVO productBean = new ProductVO();
                productBean.setId(product.getProductId());
                productBean.setQuantity(product.getNumber());
                productBean.setSeq(product.getSequence());
                productBean.setSalesType("NORMAL");
                productBean.setPrice(product.getPrice());
                productBean.setName(product.getProductName());
                productVOS.add(productBean);
            }
        }
        orderPayDto.setProducts(productVOS);
        List<PayPlatformVO> platforms = new ArrayList<>();
        PayPlatformVO payPlatformVO = new PayPlatformVO();
        payPlatformVO.setClientCode(PayChannelType.SVC.getEbcode());
        payPlatformVO.setEbcode(PayChannelType.SVC.getEbcode());
        payPlatformVO.setAmount(0L);
        platforms.add(payPlatformVO);

        String ebcode = PayChannelType.getByIndex(Byte.parseByte(channel)).getEbcode();
        payPlatformVO = new PayPlatformVO();
        payPlatformVO.setAmount(0L);
        payPlatformVO.setClientCode(orderClient);
        payPlatformVO.setEbcode(ebcode);
        platforms.add(payPlatformVO);

        orderPayDto.setPlatforms(platforms);
        orderPayDto.setOut_order_no(orderBean.getOid());
        orderPayDto.setCardCode(cardNo);
        return orderPayDto;

    }

    /**
     * 混合支付返回的支付参数
     *
     * @param payPlatforms
     * @return
     */
    public OrderPayResponse convent2OrderCombPayResponse(List<CombPayResponse.PayPlatform> payPlatforms
            , String partnerId
            , String storeId) {
        CombPayResponse.PayPlatform payPlatform = payPlatforms
                .stream()
                .filter(f -> !PayChannelType.SVC.getEbcode().equals(f.getEbCode())).findFirst()
                .orElse(null);
        OrderPayResponse responseDto = new OrderPayResponse();
        responseDto.setMsg("succ");
        responseDto.setPayEbcode(payPlatform.getEbCode());
        responseDto.setPayId("");

        OrderPayResponse.PayOrderBean payBean = new OrderPayResponse.PayOrderBean();
        responseDto.setPayTransId(payPlatform.getTransId());
        responseDto.setFmId(payPlatform.getFmTradeNo());
        CombPayResponse.PayPlatform.PayOrderBean payOrderBean = payPlatform.getPayOrder();
        if (null != payOrderBean) {
            payBean.setAppid(payOrderBean.getAppId());
            payBean.setNonceStr(payOrderBean.getNonceStr());
            payBean.setPackageX(payOrderBean.getPackageX());
            payBean.setSign(payOrderBean.getPaySign());
            payBean.setSignType(payOrderBean.getSignType());
            payBean.setTimestamp(payOrderBean.getTimeStamp());
            payBean.setAliPayOrder(payOrderBean.getAliPayOrder());
            responseDto.setPayOrder(payBean);
        }
        //供修改订单
        for (CombPayResponse.PayPlatform pt : payPlatforms) {
            OrderPayItemResp payItem = new OrderPayItemResp();
            payItem.setFmTradeNo(pt.getFmTradeNo());
            payItem.setStoreId(storeId);
            payItem.setPayChannelType(PayChannelType.getByEbcode(pt.getEbCode()).getIndex().intValue());
            payItem.setPayChannelName(PayChannelType.getByEbcode(pt.getEbCode()).getName());
            payItem.setTransId(pt.getTransId());
            payItem.setPartnerId(partnerId);
            if (PayChannelType.SVC.getEbcode().equals(pt.getEbCode())) {
                payItem.setPayAmount(new BigDecimal(pt.getPayAmount()));
                responseDto.setPayChannelType(PayChannelType.SVC);
            } else if (PayChannelType.WECHAT.getEbcode().equals(pt.getEbCode()) || PayChannelType.ALIPAY.getEbcode().equals(pt.getEbCode())) {
                payItem.setPayAmount(new BigDecimal(pt.getPayAmount()));
                responseDto.setPayChannelType(PayChannelType.getByEbcode(pt.getEbCode()));
            }
            responseDto.getPayItem().add(payItem);
        }
        if (responseDto.getPayItem().size() == 2) {
            responseDto.setPayChannelType(PayChannelType.COMB);
        }
        return responseDto;
    }

    public CreateOrderRequest convent2CreateOrderRequest(CreateOrderBo createOrderBo) {

        CreateOrderBaseVo createOrderVo = createOrderBo.getCreateOrderBaseVo();
        ShoppingCartGoodsDto shoppingCartGoodsDto = createOrderBo.getShoppingCartGoodsDto();
        AssortmentCustomerInfoVo userLoginInfoDto = createOrderBo.getUserLoginInfoDto();
        StoreResponseDto storeResponseDto = createOrderBo.getStoreResponseDto();

        CreateOrderRequest request = new CreateOrderRequest();
        request.setPartnerId(createOrderVo.getPartnerId());
        request.setStoreId(createOrderVo.getShopId());
        //1:线上支付 2:线下支付
        request.setPayType(1);
        request.setUserId(createOrderVo.getUserId());
        request.setUserName(createOrderVo.getUserName());
        //  request.setStoreName(createOrderVo.getStoreName());  fisherman 原来代码
        request.setStoreName(storeResponseDto.getStoreName());
        request.setPayTime(null);
        request.setThirdStoreId(createOrderVo.getThirdShopId());
        request.setThirdOrderCode(null);
        request.setPayChannelType(createOrderVo.getPayChannelType());

        if (Objects.nonNull(createOrderVo.getUnionPayCard())) {
            request.setPayChannel(PayChannelType.USVCP.getEbcode());
            request.setPayChannelName(PayChannelType.USVCP.getName());
            request.setPayChannelType(PayChannelType.USVCP.getIndex());
        }
        if (StringUtils.isNotBlank(createOrderVo.getChannel())) {
            PayChannelType channelType = PayChannelType.getByIndex(Byte.parseByte(createOrderVo.getChannel()));
            if (channelType != null) {
                request.setPayChannel(channelType.getEbcode());
                request.setPayChannelName(channelType.getName());
                request.setPayChannelType(channelType.getIndex());
            }
        }

        //用户在界面上看到的支付金额
        request.setSettlementAmount(shoppingCartGoodsDto.getTotalAmount() + shoppingCartGoodsDto.getDiscountDeliveryAmount() + shoppingCartGoodsDto.getPackageAmount());
        //实际支付现金金额，扣除支付自生优惠，单位分
        request.setActualPayAmount(request.getSettlementAmount());

        //订单原始金额，单位分
        Long originalAmount = 0L;

        // 获取下单渠道 fisherman
        setOrderClient(createOrderVo, userLoginInfoDto, request);

        //订单业务类型 1:普通订单 2:虚拟订单
        request.setBizType(1);
        request.setNote(createOrderVo.getOrderRemark());
        Long gmtExpect = StringUtils.isNotBlank(createOrderVo.getExpectTime()) ? DateUtil.convert2Date(createOrderVo.getExpectTime(), "yyyy-MM-dd HH:mm:ss").getTime() : null;
        request.setOrderType(getNewOrderType(getOldOrderType(createOrderVo.getOrderType(), createOrderVo.getReachStoreType()), gmtExpect));
        request.setBarCounter(createOrderVo.getTableNumber());

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

        //商品信息转换
        List<OrderItemCreateReq> orderItemList = new ArrayList<>();
        //优惠信息转换
        List<OrderSettlementCreateReq> orderSettlementCreateReqList = new ArrayList<>();
        //结算信息转换
        List<OrderCostCreateReq> orderCostCreateReqs = new ArrayList<>();
        // 更新订单商品详情信息 fisherman 2021年04月12日11:55:34  ************************
        originalAmount = updateOrderItemsAndSettlements(orderItemList, orderSettlementCreateReqList, orderCostCreateReqs,
                createOrderVo, shoppingCartGoodsDto, storeResponseDto, createOrderBo.getProducts());
        //商品信息赋值
        request.setOrderItemList(orderItemList);
        //订单原始金额，单位分
        request.setOriginalAmount(originalAmount);
        //结算信息赋值
        request.setOrderCostDetailList(orderCostCreateReqs);
        //商品优惠信息赋值
        request.setOrderSettlementDetailList(orderSettlementCreateReqList);

        //收货人信息转换
        List<DeliveryContactInfoCreateReq> deliveryContactInfoList = new ArrayList<>();
        DeliveryContactInfoCreateReq deliveryContactInfoCreateReq = new DeliveryContactInfoCreateReq();
        //地址类型 1:订单地址 2:售后单地址 3:配送员信息
        deliveryContactInfoCreateReq.setRelateObjectType(1);
        //联系方式类型 1:取件 2:收件
        deliveryContactInfoCreateReq.setInfoType(1);
        deliveryContactInfoCreateReq.setContactsName(createOrderVo.getUserName());
        deliveryContactInfoCreateReq.setMobile(createOrderVo.getMobile());
        UserDeliveryInfoDto userDeliveryInfoDto = createOrderVo.getUserDeliveryInfoDto();
        if (null != userDeliveryInfoDto) {
            deliveryContactInfoCreateReq.setLatitude(new BigDecimal(userDeliveryInfoDto.getUserLatitude()));
            deliveryContactInfoCreateReq.setLongitude(new BigDecimal(userDeliveryInfoDto.getUserLongitude()));
            deliveryContactInfoCreateReq.setProvince(userDeliveryInfoDto.getReceiveProvince());
            deliveryContactInfoCreateReq.setCity(userDeliveryInfoDto.getReceiveCity());
            deliveryContactInfoCreateReq.setRegion(userDeliveryInfoDto.getReceiveRegion());
        }
        String receiveAddress = createOrderVo.getStoreAddress();
        if (Objects.equals(createOrderVo.getOrderType(), CreateOrderType.TAKE_OUT.getCode())) {
            receiveAddress = (userDeliveryInfoDto != null ? userDeliveryInfoDto.getReceiveOfficeName() + "," + userDeliveryInfoDto.getReceiveAddress() : "");
        }
        deliveryContactInfoCreateReq.setAddressDetail(receiveAddress);
        JSONObject deliveryExtInfo = new JSONObject();
        deliveryExtInfo.put("receiveId", createOrderVo.getReceiveId());
        deliveryContactInfoCreateReq.setExtInfo(deliveryExtInfo.toJSONString());
        deliveryContactInfoList.add(deliveryContactInfoCreateReq);
        //第三方配送信息
        BaseCreateOrderRequest.DeliveryTypeInfo deliveryTypeInfo = new BaseCreateOrderRequest.DeliveryTypeInfo();
        String deliveryType = userDeliveryInfoDto != null && userDeliveryInfoDto.getStoreDeliveryInfoDto() != null
                ? userDeliveryInfoDto.getStoreDeliveryInfoDto().getDeliveryType() : "";
        deliveryTypeInfo.setDeliveryType(QueryDeliveryType.getByCode(deliveryType));
        // fisherman 方法调用
        getThirdDeliveryInfo(deliveryContactInfoList, deliveryTypeInfo);
        request.setDeliveryContactInfoList(deliveryContactInfoList);
        //保存门店渠道信息
        OrderExtendedReq orderExtended = new OrderExtendedReq();
        orderExtended.setOrderClientGroupCode(storeResponseDto.getParentCode());
        orderExtended.setOrderClientGroup(storeResponseDto.getParentName());
        request.setOrderExtended(orderExtended);
        request.setOperator(createOrderVo.getUserName());
        request.setAppId(userLoginInfoDto.getWxAppId());

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

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

        // 买一赠一寄件信息
        if (createOrderVo.getChooseGoods() != null && !createOrderVo.getChooseGoods().isEmpty()) {
            request.setOrderSendCouponRespList(JSONArray.parseArray(JSONObject.toJSONString(createOrderVo.getChooseGoods()), CreateOrderRequest.ChooseGood.class));
        }

        return request;
    }

    /**
     * 下单渠道 必填项  根据此字段的值判断是自营或第三方，来走不同的状态机 详细见 orderClientType枚举
     *
     * @param createOrderVo
     * @param userLoginInfoDto
     * @param request
     */
    private void setOrderClient(CreateOrderBaseVo createOrderVo, AssortmentCustomerInfoVo userLoginInfoDto, CreateOrderRequest request) {
        OrderClientType orderClient;
        String channel = userLoginInfoDto.getChannel();
        if (UserLoginChannelEnum.ALIPAY.getCode().equals(channel)) {
            orderClient = OrderClientType.ALIPAY;
        } else if (UserLoginChannelEnum.APP.getCode().equals(channel)) {
            orderClient = OrderClientType.APP;
        } else if (UserLoginChannelEnum.TIKTOKPAY.getCode().equals(channel)) {
            //抖音小程序
            createOrderVo.setPayChannelType(PayChannelType.TIKTOKPAY.getIndex());
            orderClient = OrderClientType.TIKTOKPAY;
        } else {
            // 美业
            if (OrderChannelType.BEAUTIFUL.getCode().equals(createOrderVo.getChannelType())) {
                orderClient = OrderClientType.BEAUTIFUL;
            } else {
                orderClient = OrderClientType.SAAS;
            }
        }
        // fisherman 有个订单来源的字段判断
        request.setOrderClient(orderClient.getIndex());
    }

    /**
     * 计算所有商品的重量 单位g
     */
    private Double sumOrderWeight(List<ShoppingCartGoodsDto.CartGoodsDetailDto> products) {
        Double totalWeight = 0D;
        if (CollectionUtils.isEmpty(products)) {
            return totalWeight;
        }
        for (ShoppingCartGoodsDto.CartGoodsDetailDto productRequest : products) {
            Integer qty = productRequest.getQty() == null ? 0 : productRequest.getQty();
            if (ObjectUtils.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), productRequest.getProductType())
                    || ObjectUtils.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), productRequest.getProductType())) {
                if (CollectionUtils.isNotEmpty(productRequest.getComboProducts())) {
                    Double comboProductTotalWeight = productRequest.getComboProducts().stream().map(t -> {
                        Integer comboQty = t.getQty() == null ? 0 : t.getQty();
                        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 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);
        }
    }

    /**
     * 使用购物车商品信息  更新订单商品明细和优惠明细
     *
     * @param orderItemList                订单商品明细（返回）
     * @param orderSettlementCreateReqList 优惠明细（返回）
     * @param orderCostCreateReqs          费用明细（返回）
     * @param createOrderVo                创单信息（入参）
     * @param shoppingCartGoodsDto         购物车商品信息（入参）
     * @return 订单金额
     */
    private Long updateOrderItemsAndSettlements(List<OrderItemCreateReq> orderItemList, List<OrderSettlementCreateReq> orderSettlementCreateReqList, List<OrderCostCreateReq> orderCostCreateReqs,
                                                CreateOrderBaseVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto, StoreResponseDto storeResponseDto, Map<String, GetProductsVo> productsMap) {
        Long originalAmount = 0L;
        // 更新订单费用信息
        originalAmount = convertCreateOrderCost(originalAmount, orderSettlementCreateReqList, orderCostCreateReqs, createOrderVo, shoppingCartGoodsDto, storeResponseDto);
        // 更新商品属性信息
        if (CollectionUtils.isEmpty(shoppingCartGoodsDto.getProducts())) {
            return originalAmount;
        }
        Integer index = 1;
        for (ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto : shoppingCartGoodsDto.getProducts()) {

            // 改造 begin
            CreateOrderProductRequest createOrderProductDto;
            if (mcCafePartnerId.equals(createOrderVo.getPartnerId())) {
                createOrderProductDto = convent2MCCafeOrderProduct(cartGoodsDetailDto);
            } else {
                createOrderProductDto = convent2OrderProduct(cartGoodsDetailDto);
            }
            createOrderProductDto.setIgnoreProductPrice(1);
            // 改造 end

            originalAmount += updateOrderItemAndSettlement(createOrderProductDto,
                    orderItemList,
                    orderSettlementCreateReqList,
                    cartGoodsDetailDto,
                    createOrderVo.getPartnerId(),
                    "",
                    false,
                    index,
                    productsMap);
//            originalAmount += updateOrderItemAndSettlement(cartGoodsDetailDto,
//                    orderItemList,
//                    orderSettlementCreateReqList,
//                    cartGoodsDetailDto,
//                    createOrderVo.getPartnerId(),
//                    "",
//                    false,
//                    index,
//                    productsMap);
            if (ProductTypeEnum.MATERIAL_PRODUCT.getCode().equals(cartGoodsDetailDto.getProductType())) {
                if (CollectionUtils.isNotEmpty(cartGoodsDetailDto.getMaterialList())) {
                    // 父类商品productId=productId+seq
                    String partnerProductId = cartGoodsDetailDto.getSkuId() + "_" + index;
                    for (ShoppingCartGoodsDto.CartGoodsDetailDto material : cartGoodsDetailDto.getMaterialList()) {
                        index++;
                        material.setSkuId(material.getSpuId());
                        material.setSkuName(material.getSpuName());
                        updateOrderItemAndSettlement(createOrderProductDto, orderItemList, orderSettlementCreateReqList, material, createOrderVo.getPartnerId(), partnerProductId, true, index, productsMap);
                    }
                }
            }
            // 如果是套餐商品，需要转换当前商品行子集ComboProduct&GroupProduct（固定商品、可选商品）
            if (ObjectUtils.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), cartGoodsDetailDto.getProductType())
                    || ObjectUtils.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), cartGoodsDetailDto.getProductType())) {
                // 父类商品productId=productId+seq
                String partnerProductId = cartGoodsDetailDto.getSpuId() + "_" + index;
                if (CollectionUtils.isNotEmpty(cartGoodsDetailDto.getComboProducts())) {
                    final int finalIndex = index;
                    cartGoodsDetailDto.getComboProducts().forEach(combo -> updateOrderItemAndSettlement(createOrderProductDto, orderItemList, orderSettlementCreateReqList, combo, createOrderVo.getPartnerId(), partnerProductId, false, finalIndex, productsMap));
                }
            }
            index++;
        }
        return originalAmount;
    }

    public CreateOrderProductRequest convent2MCCafeOrderProductDemo(ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto, Integer productType) {
        CreateOrderProductRequest createOrderProductDemoDto = new CreateOrderProductRequest();
        createOrderProductDemoDto.setProductId(cartGoodsDetailDto.getSpuId());
        createOrderProductDemoDto.setProductName(cartGoodsDetailDto.getSpuName());
        createOrderProductDemoDto.setSpecification(cartGoodsDetailDto.getSkuId());
        createOrderProductDemoDto.setSpecificationName(cartGoodsDetailDto.getSkuName());
        createOrderProductDemoDto.setPrice(cartGoodsDetailDto.getOriginalPrice());
        createOrderProductDemoDto.setSalePrice(cartGoodsDetailDto.getOriginalPrice());
        createOrderProductDemoDto.setTotalDiscountAmount(cartGoodsDetailDto.getTotalDiscountAmount() == null ? 0 : cartGoodsDetailDto.getTotalDiscountAmount().longValue());
        createOrderProductDemoDto.setNumber(cartGoodsDetailDto.getQty());
        createOrderProductDemoDto.setPicture(cartGoodsDetailDto.getPicture());
        createOrderProductDemoDto.setAddInfo(cartGoodsDetailDto.getAttributeNames());
        createOrderProductDemoDto.setDiscountId(cartGoodsDetailDto.getCouponCode());
        if (cartGoodsDetailDto.getIsTableware() == 0) {
            createOrderProductDemoDto.setProductType(productType);
        } else {
            createOrderProductDemoDto.setProductType(ProductTypeEnum.TABLEWARE_PRODUCT.getCode());
        }
        createOrderProductDemoDto.setParentProductId(cartGoodsDetailDto.getParentProductId());
        createOrderProductDemoDto.setIsFixedProduct(cartGoodsDetailDto.getIsFixedProduct());
        createOrderProductDemoDto.setCustomerCode(cartGoodsDetailDto.getCustomerCode());
        createOrderProductDemoDto.setProductCode(cartGoodsDetailDto.getProductCode());
        createOrderProductDemoDto.setHasStockProudct(cartGoodsDetailDto.isStockLimit());
        createOrderProductDemoDto.setWeight(cartGoodsDetailDto.getWeight());
        createOrderProductDemoDto.setUnit(cartGoodsDetailDto.getUnit());
        createOrderProductDemoDto.setStapleFood(0);
        createOrderProductDemoDto.setCategory(cartGoodsDetailDto.getClassificationId());
        createOrderProductDemoDto.setTax(cartGoodsDetailDto.getTax());
        createOrderProductDemoDto.setTaxId(cartGoodsDetailDto.getTaxId());
        createOrderProductDemoDto.setClassificationId(cartGoodsDetailDto.getClassificationId());
        createOrderProductDemoDto.setClassificationName(cartGoodsDetailDto.getClassificationName());
        createOrderProductDemoDto.setSplitIndex(cartGoodsDetailDto.getSplitIndex());
        if (CollectionUtils.isNotEmpty(cartGoodsDetailDto.getSpecialExtra())) {
            createOrderProductDemoDto.setSpecialAttrs(new ArrayList<>());
            cartGoodsDetailDto.getSpecialExtra().stream().forEach(o -> {
                createOrderProductDemoDto.getSpecialAttrs().add(new OrderSpecialExtraAttrRequest(o.getAttributeId(), o.getAttributeName(), o.getAttributeForeignName(), o.getSpecialCode()));
            });
        }
        return createOrderProductDemoDto;
    }

    public CreateOrderProductRequest convent2MCCafeOrderProduct(ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto) {
        CreateOrderProductRequest createOrderProductDemoDto = convent2MCCafeOrderProductDemo(cartGoodsDetailDto, cartGoodsDetailDto.getProductType());
        if (cartGoodsDetailDto.getProductType() != null) {
            if (cartGoodsDetailDto.getProductType() == ProductType.SETMEALPRODUCT.getCode()
                    || cartGoodsDetailDto.getProductType() == ProductType.SETMEALPRODUCT_UPPRICE.getCode()) {
//                createOrderProductDemoDto.setPrice(0l);
                //套餐
                List<CreateOrderProductRequest> comboProducts = new ArrayList<>();
                cartGoodsDetailDto.getComboProducts().forEach(product -> {
                    CreateOrderProductRequest createOrderComboProduct = convent2MCCafeOrderProductDemo(product, product.getProductType());
                    if (!product.getIsFixedProduct()) {
                        createOrderProductDemoDto.setPrice(createOrderProductDemoDto.getPrice() + product.getOriginalPrice());
                    }
                    comboProducts.add(createOrderComboProduct);
                    if (CollectionUtils.isNotEmpty(product.getMaterialList())) {
                        //加料商品
                        createOrderComboProduct.setProductType(ProductType.MATERIALPRODUCT_UPPRICE.getCode());
                        List<CreateOrderProductRequest> materialProducts = new ArrayList<>();
                        product.getMaterialList().forEach(cartMaterial -> {
                            materialProducts.add(convent2MCCafeOrderProductDemo(cartMaterial, ProductType.LITTLE_MATERIAL_PRODUCT.getCode()));
                        });
                        createOrderComboProduct.setMaterialProduct(materialProducts);
                    }
                });
                createOrderProductDemoDto.setComboProduct(comboProducts);
            } else if (ProductTypeEnum.VIRTUAL_PRODUCT.getCode().equals(cartGoodsDetailDto.getProductType())) {
                if(cartGoodsDetailDto.getIsMonthCard() == 1) {
                    createOrderProductDemoDto.setCardId(cartGoodsDetailDto.getMonthCardInfo().getCardNo());
                    createOrderProductDemoDto.setCardCode(cartGoodsDetailDto.getMonthCardInfo().getCardCode());
                } else if(cartGoodsDetailDto.getIsB3S1Coupon() == 1) {
                    createOrderProductDemoDto.setCardId(cartGoodsDetailDto.getB3S1CouponGoodsInfo().getCardNo());
                    createOrderProductDemoDto.setCardCode(cartGoodsDetailDto.getB3S1CouponGoodsInfo().getCardCode());
                }
            }
        }
        if (CollectionUtils.isNotEmpty(cartGoodsDetailDto.getMaterialList())) {
            //加料商品
            createOrderProductDemoDto.setProductType(ProductType.MATERIALPRODUCT_UPPRICE.getCode());
            List<CreateOrderProductRequest> materialProducts = new ArrayList<>();
            cartGoodsDetailDto.getMaterialList().forEach(product -> {
                materialProducts.add(convent2MCCafeOrderProductDemo(product, ProductType.LITTLE_MATERIAL_PRODUCT.getCode()));
            });
            createOrderProductDemoDto.setMaterialProduct(materialProducts);
        }
        return createOrderProductDemoDto;
    }

    public CreateOrderProductRequest convent2OrderProductDemo(ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto) {
        CreateOrderProductRequest createOrderProductDemoDto = new CreateOrderProductRequest();
        createOrderProductDemoDto.setProductId(StringUtils.isNotBlank(cartGoodsDetailDto.getSpuId()) ? cartGoodsDetailDto.getSpuId() : cartGoodsDetailDto.getSkuId());
        createOrderProductDemoDto.setProductName(cartGoodsDetailDto.getSpuName());
        createOrderProductDemoDto.setProductForeignName(cartGoodsDetailDto.getSpuForeignName());
        createOrderProductDemoDto.setSpecification(cartGoodsDetailDto.getSkuId());
        createOrderProductDemoDto.setSpecificationName(cartGoodsDetailDto.getSkuName());
        createOrderProductDemoDto.setSpecificationForeignName(cartGoodsDetailDto.getSkuForeignName());
        createOrderProductDemoDto.setPrice(cartGoodsDetailDto.getOriginalPrice());
        createOrderProductDemoDto.setSalePrice(cartGoodsDetailDto.getOriginalPrice());
        createOrderProductDemoDto.setTotalDiscountAmount(cartGoodsDetailDto.getTotalDiscountAmount() == null ? 0 : cartGoodsDetailDto.getTotalDiscountAmount().longValue());
        createOrderProductDemoDto.setNumber(cartGoodsDetailDto.getQty());
        createOrderProductDemoDto.setPicture(cartGoodsDetailDto.getPicture());
        createOrderProductDemoDto.setAddInfo(cartGoodsDetailDto.getAttributeNames());
        createOrderProductDemoDto.setDiscountId(cartGoodsDetailDto.getCouponCode());
        createOrderProductDemoDto.setProductType(cartGoodsDetailDto.getProductType());
        createOrderProductDemoDto.setParentProductId(cartGoodsDetailDto.getParentProductId());
        createOrderProductDemoDto.setIsFixedProduct(cartGoodsDetailDto.getIsFixedProduct());
        createOrderProductDemoDto.setCustomerCode(cartGoodsDetailDto.getCustomerCode());
        createOrderProductDemoDto.setProductCode(cartGoodsDetailDto.getProductCode());
        createOrderProductDemoDto.setHasStockProudct(cartGoodsDetailDto.isStockLimit());
        createOrderProductDemoDto.setWeight(cartGoodsDetailDto.getWeight());
        createOrderProductDemoDto.setUnit(cartGoodsDetailDto.getUnit());
        createOrderProductDemoDto.setStapleFood(0);
        createOrderProductDemoDto.setCategory(cartGoodsDetailDto.getClassificationId());
        createOrderProductDemoDto.setTax(cartGoodsDetailDto.getTax());
        createOrderProductDemoDto.setTaxId(cartGoodsDetailDto.getTaxId());
        createOrderProductDemoDto.setClassificationId(cartGoodsDetailDto.getClassificationId());
        createOrderProductDemoDto.setClassificationName(cartGoodsDetailDto.getClassificationName());
        createOrderProductDemoDto.setUserId(cartGoodsDetailDto.getUserId());
        createOrderProductDemoDto.setOpenId(cartGoodsDetailDto.getOpenId());
        createOrderProductDemoDto.setNickName(cartGoodsDetailDto.getUserName());
        createOrderProductDemoDto.setPhotoUrl(cartGoodsDetailDto.getPhotoUrl());
        createOrderProductDemoDto.setPackPrice(cartGoodsDetailDto.getPackPrice());
        createOrderProductDemoDto.setIsSendGoods(cartGoodsDetailDto.getIsSendGoods());

        createOrderProductDemoDto.setCartGoodsUid(cartGoodsDetailDto.getCartGoodsUid());
        createOrderProductDemoDto.setOriginalGoodsUid(cartGoodsDetailDto.getOriginalGoodsUid());
        return createOrderProductDemoDto;
    }

    public CreateOrderProductRequest convent2OrderProduct(ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto) {
        CreateOrderProductRequest createOrderProductDemoDto = convent2OrderProductDemo(cartGoodsDetailDto);
        //套餐
        if (cartGoodsDetailDto.getProductType() != null && (cartGoodsDetailDto.getProductType() == ProductType.SETMEALPRODUCT.getCode() || cartGoodsDetailDto.getProductType() == ProductType.SETMEALPRODUCT_UPPRICE.getCode())) {
            List<CreateOrderProductRequest> comboProducts = new ArrayList<>();
            cartGoodsDetailDto.getComboProducts().forEach(product -> {
                product.setUserId(cartGoodsDetailDto.getUserId());
                product.setUserName(cartGoodsDetailDto.getUserName());
                product.setOpenId(cartGoodsDetailDto.getOpenId());
                product.setPhotoUrl(cartGoodsDetailDto.getPhotoUrl());
                comboProducts.add(convent2OrderProductDemo(product));
            });
            createOrderProductDemoDto.setComboProduct(comboProducts);
        }
        //加料商品
        if (cartGoodsDetailDto.getProductType() != null && (cartGoodsDetailDto.getProductType() == ProductType.MATERIALPRODUCT_UPPRICE.getCode())) {
            List<CreateOrderProductRequest> materialProducts = new ArrayList<>();
            cartGoodsDetailDto.getMaterialList().forEach(product -> {
                product.setUserId(cartGoodsDetailDto.getUserId());
                product.setUserName(cartGoodsDetailDto.getUserName());
                product.setOpenId(cartGoodsDetailDto.getOpenId());
                product.setPhotoUrl(cartGoodsDetailDto.getPhotoUrl());
                materialProducts.add(convent2OrderProductMaterial(product));
            });
            createOrderProductDemoDto.setMaterialProduct(materialProducts);
        }
        createOrderProductDemoDto.setProductType(cartGoodsDetailDto.getProductType());
        return createOrderProductDemoDto;
    }

    private CreateOrderProductRequest convent2OrderProductMaterial(ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto) {
        CreateOrderProductRequest createOrderProductDemoDto = new CreateOrderProductRequest();
        createOrderProductDemoDto.setProductId(cartGoodsDetailDto.getSpuId());
        createOrderProductDemoDto.setProductName(cartGoodsDetailDto.getSpuName());
        createOrderProductDemoDto.setSpecification(cartGoodsDetailDto.getSkuId());
        createOrderProductDemoDto.setSpecificationName(cartGoodsDetailDto.getSkuName());
        createOrderProductDemoDto.setPrice(cartGoodsDetailDto.getOriginalPrice());
        createOrderProductDemoDto.setSalePrice(cartGoodsDetailDto.getOriginalPrice());
        createOrderProductDemoDto.setTotalDiscountAmount(cartGoodsDetailDto.getTotalDiscountAmount() == null ? 0 : cartGoodsDetailDto.getTotalDiscountAmount().longValue());
        createOrderProductDemoDto.setNumber(cartGoodsDetailDto.getQty());
        createOrderProductDemoDto.setPicture(cartGoodsDetailDto.getPicture());
        createOrderProductDemoDto.setAddInfo(cartGoodsDetailDto.getAttributeNames());
        createOrderProductDemoDto.setDiscountId(cartGoodsDetailDto.getCouponCode());
        createOrderProductDemoDto.setProductType(cartGoodsDetailDto.getProductType());
        createOrderProductDemoDto.setParentProductId(cartGoodsDetailDto.getParentProductId());
        createOrderProductDemoDto.setIsFixedProduct(cartGoodsDetailDto.getIsFixedProduct());
        createOrderProductDemoDto.setCustomerCode(cartGoodsDetailDto.getCustomerCode());
        //createOrderProductDemoDto.setProductCode(cartGoodsDetailDto.getProductCode());
        createOrderProductDemoDto.setHasStockProudct(cartGoodsDetailDto.isStockLimit());
        createOrderProductDemoDto.setWeight(cartGoodsDetailDto.getWeight());
        createOrderProductDemoDto.setUnit(cartGoodsDetailDto.getUnit());
        createOrderProductDemoDto.setStapleFood(0);
        createOrderProductDemoDto.setClassificationId(cartGoodsDetailDto.getClassificationId());
        createOrderProductDemoDto.setClassificationName(cartGoodsDetailDto.getClassificationName());
        if (CollectionUtils.isNotEmpty(cartGoodsDetailDto.getActivityDiscountsDtos())) {
            createOrderProductDemoDto.setAccounts(getMaterialAccounts(createOrderProductDemoDto, cartGoodsDetailDto));
        }
        return createOrderProductDemoDto;
    }

    private List<CreateOrderAccountRequest> getMaterialAccounts(CreateOrderProductRequest createOrderProductDto, ShoppingCartGoodsDto.CartGoodsDetailDto material) {
        List<CreateOrderAccountRequest> orderAccountDtos = createOrderProductDto.getAccounts();
        if (CollectionUtils.isEmpty(orderAccountDtos)) {
            orderAccountDtos = new ArrayList<>();
        }
        List<ActivityDiscountsDto> activityDiscountsDtos = material.getActivityDiscountsDtos();
        for (ActivityDiscountsDto activityDiscountsDto : activityDiscountsDtos) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId(activityDiscountsDto.getActivityCode())
                    .name(activityDiscountsDto.getActivityName())
                    .price(activityDiscountsDto.getDiscountAmount().longValue())
                    .accountType(getQueryOrderAccountType(getOrderAccountType(activityDiscountsDto.getActivityType())))
                    .sequence(createOrderProductDto.getSequence())
                    .productId(material.getSpuId())
                    .discountQty((activityDiscountsDto.getActualActivityGoodsNumber() == null || activityDiscountsDto.getActualActivityGoodsNumber() == 0)
                            ? createOrderProductDto.getNumber() : activityDiscountsDto.getActualActivityGoodsNumber())
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        return orderAccountDtos;

    }

    /**
     * 将促销的枚举 ActivityTypeEnum 和orderAccountType 关联映射
     */
    public OldOrderAccountType getOrderAccountType(Integer activityType) {
        if (ActivityTypeEnum.TYPE_1.getCode().equals(activityType) || ActivityTypeEnum.TYPE_11.getCode().equals(activityType) || ActivityTypeEnum.TYPE_12.getCode().equals(activityType) || ActivityTypeEnum.TYPE_13.getCode().equals(activityType)) {
            return OldOrderAccountType.BUY_DISCOUNT;
        }
        if (ActivityTypeEnum.TYPE_3.getCode().equals(activityType)) {
            return OldOrderAccountType.COUPON;
        }
        if (ActivityTypeEnum.TYPE_2.getCode().equals(activityType) || ActivityTypeEnum.TYPE_21.getCode().equals(activityType)) {
            return OldOrderAccountType.DISCOUNT_AMOUNT;
        }
        if (ActivityTypeEnum.TYPE_81.getCode().equals(activityType)) {
            return OldOrderAccountType.PREMIUM_EXCHANGE;
        }
        if (ActivityTypeEnum.TYPE_32.getCode().equals(activityType)) {
            return OldOrderAccountType.PRODUCT_COUPON;
        }
        if (ActivityTypeEnum.TYPE_37.getCode().equals(activityType)) {
            return OldOrderAccountType.SEED_PRODUCT_COUPON;
        }
        if (ActivityTypeEnum.TYPE_34.getCode().equals(activityType)) {
            return OldOrderAccountType.FREIGHT_COUPON;
        }
        if (ActivityTypeEnum.TYPE_31.getCode().equals(activityType)) {
            return OldOrderAccountType.DISCOUNT_COUPON;
        }
        if (ActivityTypeEnum.TYPE_PACKAGE.getCode().equals(activityType)) {
            return OldOrderAccountType.PACK_AMOUNT;
        }
        if (ActivityTypeEnum.TYPE_DELIVERY.getCode().equals(activityType)) {
            return OldOrderAccountType.DELIVERY_AMOUNT;
        }
        if (ActivityTypeEnum.TYPE_61.getCode().equals(activityType)) {
            return OldOrderAccountType.BUYM_SENDN;
        }
        if (ActivityTypeEnum.TYPE_53.getCode().equals(activityType)) {
            return OldOrderAccountType.SECOND_DISCOUNT;
        }
        if (ActivityTypeEnum.TYPE_211.getCode().equals(activityType)) {
            return OldOrderAccountType.SET_MEAL;
        }
        if (ActivityTypeEnum.TYPE_104.getCode().equals(activityType)) {
            return OldOrderAccountType.XY_DISCOUNT;
        }
        if (ActivityTypeEnum.TYPE_14.getCode().equals(activityType)) {
            return OldOrderAccountType.FULL_DISTRIBUTION_FEE;
        }
        if (ActivityTypeEnum.TYPE_320.getCode().equals(activityType)) {
            return OldOrderAccountType.MEMBER_PRICE_DISCOUNT;
        }
        if (ActivityTypeEnum.TYPE_23.getCode().equals(activityType)) {
            return OldOrderAccountType.SUPER_PURCHASE;
        }
        if (ActivityTypeEnum.TYPE_221.getCode().equals(activityType)) {
            return OldOrderAccountType.GATHER_SPOT;
        }
        if (ActivityTypeEnum.TYPE_221.getCode().equals(activityType)) {
            return OldOrderAccountType.GATHER_SPOT;
        }
        if (ActivityTypeEnum.TYPE_22.getCode().equals(activityType)) {
            return OldOrderAccountType.SINGLE_PRODUCT_REDUCTION;
        }

        // coco商品代金券
        if (ActivityTypeEnum.TYPE_36.getCode().equals(activityType)) {
            return OldOrderAccountType.COCO_PRODUCT_CASH_COUPON;
        }
        if (ActivityTypeEnum.TYPE_230.getCode().equals(activityType)) {
            return OldOrderAccountType.FULL_BUYM_SENDN;
        }
        return OldOrderAccountType.BUYM_SENDN;
    }

    /**
     * 获取聚合订单活动类型
     */
    public QueryOrderAccountType getQueryOrderAccountType(OldOrderAccountType oldOrderAccountType) {
        return QueryOrderAccountType.getByCode(oldOrderAccountType.getMessage());
    }


    private Long updateOrderItemAndSettlement(CreateOrderProductRequest productOld,
                                              List<OrderItemCreateReq> orderItemList,
                                              List<OrderSettlementCreateReq> orderSettlementCreateReqList,
                                              ShoppingCartGoodsDto.CartGoodsDetailDto product,
                                              String partnerId,
                                              String parentProductId,
                                              Boolean isMaterial,
                                              int index,
                                              Map<String, GetProductsVo> productsMap) {
        OrderItemCreateReq orderItemCreateReq = new OrderItemCreateReq();
        orderItemCreateReq.setPartnerId(partnerId);
        orderItemCreateReq.setProductName(product.getSpuName());
        orderItemCreateReq.setProductId(StringUtils.isNotBlank(product.getSpuId()) ? product.getSpuId() : product.getSkuId());
        orderItemCreateReq.setProductSpec(product.getSkuId());
        orderItemCreateReq.setProductSpecName(product.getSkuName());
        orderItemCreateReq.setProductSeq(index);
        orderItemCreateReq.setProductQuantity(product.getQty());
        orderItemCreateReq.setProductPrice(product.getOriginalPrice());
        orderItemCreateReq.setIsDeleted(false);
        Integer totalDiscountAmount = product.getTotalDiscountAmount() == null ? 0 : product.getTotalDiscountAmount();
        product.setTotalDiscountAmount(totalDiscountAmount);
        //总原价
        Long totalOriginalProductAmount = product.getOriginalPrice() * product.getQty();
        /**
         * 称重菜
         * 如果没有称重重量视为0
         */
        if (ProductTypeEnum.WEIGHT_PRODUCT.getCode().equals(product.getProductType())) {
            Double weight = (product.getWeight() == null || product.getWeight() <= 0) ? 0 : product.getWeight();
            Double weightPrice = product.getOriginalPrice() * weight;
            Long settlementPrice = weightPrice == 0 ? 0 : weightPrice.longValue() - totalDiscountAmount;
            orderItemCreateReq.setSalePrice(settlementPrice);
            orderItemCreateReq.setSettlementPrice(settlementPrice);
            totalOriginalProductAmount = weightPrice.longValue();
        } else {
            Long settlementPrice = product.getOriginalPrice() * product.getQty() - totalDiscountAmount;
            orderItemCreateReq.setSalePrice(settlementPrice / product.getQty());
            orderItemCreateReq.setSettlementPrice(settlementPrice);
            /**
             * 套餐商品
             * 套餐原价 = 子商品总原价（称重菜原价*重量+普通商品原价*数量+可选商品原价*数量）
             * 套餐结算价 = (套餐价设置为0) ？所有子商品结算价和 * 套餐数量 : 套餐原价*套餐数量-优惠价
             * 套餐售价 = 套餐结算价 / 套餐数量
             */
            if (ProductTypeEnum.SETMEAL_PRODUCT.getCode().equals(product.getProductType()) || ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode().equals(product.getProductType())) {
                if (CollectionUtils.isNotEmpty(product.getComboProducts())) {
                    // 套餐原价
                    Long setmealProductTotalOriginalAmount = 0L;
                    // 套餐结算价
                    Long setmealTotalSettlementPrice = 0L;
                    for (ShoppingCartGoodsDto.CartGoodsDetailDto combo : product.getComboProducts()) {
                        Long comboProductTotalDiscountAmount = combo.getTotalDiscountAmount() == null ? 0L : combo.getTotalDiscountAmount();
                        if (ProductTypeEnum.WEIGHT_PRODUCT.getCode().equals(combo.getProductType())) {
                            Double weight = (combo.getWeight() == null || combo.getWeight() <= 0) ? 0 : combo.getWeight();
                            Double weightPrice = combo.getOriginalPrice() * weight;
                            Long comboSettlementPrice = weightPrice == 0 ? 0 : weightPrice.longValue() - comboProductTotalDiscountAmount;
                            setmealTotalSettlementPrice += comboSettlementPrice;
                            setmealProductTotalOriginalAmount += weightPrice.longValue();
                        } else {
                            Long numberPrice = combo.getOriginalPrice() * combo.getQty();
                            Long comboSettlementPrice = numberPrice - comboProductTotalDiscountAmount;
                            setmealTotalSettlementPrice += comboSettlementPrice;
                            setmealProductTotalOriginalAmount += numberPrice;
                        }
                    }
                    // 套餐原价
                    orderItemCreateReq.setProductPrice(setmealProductTotalOriginalAmount / product.getQty());
                    // 如果套餐没有设置价格取子商品结算价和，否则取套餐自身的结算价
                    setmealTotalSettlementPrice = product.getOriginalPrice() == 0 ? setmealTotalSettlementPrice : settlementPrice;
                    orderItemCreateReq.setSettlementPrice(setmealTotalSettlementPrice);
                    orderItemCreateReq.setSalePrice(setmealTotalSettlementPrice / product.getQty());
                    totalOriginalProductAmount = setmealProductTotalOriginalAmount;
                }
            }
        }
        orderItemCreateReq.setProductSharePrice((long) (totalDiscountAmount / product.getQty()));
        orderItemCreateReq.setProductUnit(product.getUnit());
        //获取商品属性
        OrderProductAddInfoDto addInfo = JSONObject.parseObject(product.getAttributeNames(), OrderProductAddInfoDto.class);
        if (addInfo != null) {
            orderItemCreateReq.setProductProperty(addInfo.getAttributeNames());
            orderItemCreateReq.setProductForeignProperty(addInfo.getAttributeForeignNames());
        }
        orderItemCreateReq.setProductPicUrl(product.getPicture());
        orderItemCreateReq.setThirdProductId(product.getCustomerCode());
        orderItemCreateReq.setProductCode(product.getProductCode());
//        orderItemCreateReq.setCategoryId(product.getCategoryId());
        orderItemCreateReq.setCategoryName(product.getCategoryName());
        //套餐商品
        if (StringUtils.isNotEmpty(parentProductId)) {
            orderItemCreateReq.setParentProductId(parentProductId); //套餐类商品父级商品id
        }
        orderItemCreateReq.setProductType(product.getProductType()); //套餐 type-6
        orderItemCreateReq.setWeight(product.getWeight()); //重量
        OrderProductAddInfoDto extInfo = new OrderProductAddInfoDto();
        //设置是否为套餐商品
        if (product.getIsFixedProduct() != null) {
            extInfo.setIsFixedProduct(product.getIsFixedProduct());
        }
        GetProductsVo getProductsVo = productsMap.get(product.getSkuId());
        if (null != getProductsVo) {
            orderItemCreateReq.setThirdProductId(getProductsVo.getCustomerCode());
            orderItemCreateReq.setProductCode(getProductsVo.getProductCode());

            //第三方商品规格id
            if (StringUtils.isNotBlank(getProductsVo.getThirdProductSpecId())) {
                extInfo.setThirdProductSpecId(getProductsVo.getThirdProductSpecId());
            }
            //第三方商品属性id
            String productPropertyId = getThirdPropertyId(getProductsVo.getProductAttributeGroupList(), product.getAttributeNames());
            if (StringUtils.isNotBlank(productPropertyId)) {
                extInfo.setThirdProductPropertyId(productPropertyId);
            }
            // todo 订单行扩展字段商品组
            List<ProductGroupVo> targetGroupList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(getProductsVo.getProductGroupList())) {
                for (ProductGroup productGroup : getProductsVo.getProductGroupList()) {
                    for (GroupDetail groupDetail : productGroup.getGroupDetail()) {
                        ProductGroupVo productGroupVo = ProductGroupVo.builder()
                                .groupId(groupDetail.getGroupId()).groupName(productGroup.getName())
                                .thirdGroupId(productGroup.getGroupCode()).build();
                        if (!targetGroupList.contains(productGroupVo)) {
                            targetGroupList.add(productGroupVo);
                        }
                    }
                }
            }
            extInfo.setProductGroupList(targetGroupList);
            extInfo.setStapleFood(getProductsVo.getStapleFood());
        } else {
            orderItemCreateReq.setThirdProductId("");
            orderItemCreateReq.setProductCode("");
        }

        if (StringUtils.isNotBlank(productOld.getThirdCategoryId())) {
            extInfo.setThirdCategoryId(productOld.getThirdCategoryId());
        }
        if (CollectionUtils.isNotEmpty(productOld.getSpecialAttrs())) {
            extInfo.setSpecialAttrs(productOld.getSpecialAttrs());
        }
        if (StringUtils.isNotBlank(productOld.getCardId())) {
            extInfo.setCardId(productOld.getCardId());
        }
        if (StringUtils.isNotBlank(productOld.getCardCode())) {
            extInfo.setCardCode(productOld.getCardCode());
        }
        if (StringUtils.isNotBlank(product.getClassificationId())) {
            extInfo.setThirdCensusCategoryId(product.getClassificationId());
            extInfo.setThirdCensusCategoryName(product.getClassificationName());
        }
        if (StringUtils.isNotBlank(product.getSplitIndex())) {
            extInfo.setSplitIndex(product.getSplitIndex());
        }

        if (CollectionUtils.isNotEmpty(product.getSpecialExtra())) {
            List<OrderSpecialExtraAttrRequest> list = new ArrayList();
            product.getSpecialExtra().stream().forEach(o -> {
                list.add(new OrderSpecialExtraAttrRequest(o.getAttributeId(),
                        o.getAttributeName(),
                        o.getAttributeForeignName(),
                        o.getSpecialCode()));
            });
            if (CollectionUtils.isNotEmpty(list)) {
                extInfo.setSpecialAttrs(list);
            }
        }
        if (0 != product.getTax()) {
            extInfo.setTax(product.getTax());
        }
        if (StringUtils.isNotEmpty(product.getTaxId())) {
            extInfo.setTaxId(product.getTaxId());
        }


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

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

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

        orderItemList.add(orderItemCreateReq);
        if (product.getTotalDiscountAmount() != null && product.getTotalDiscountAmount() > 0L && !isMaterial) {
            //优惠信息转换
            OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
            orderSettlementCreateReq.setProductId(StringUtils.isBlank(product.getSkuId()) ? product.getSkuId() : product.getSpuId());
            orderSettlementCreateReq.setNumber(product.getQty());
            orderSettlementCreateReq.setProductSeq(index);
            orderSettlementCreateReq.setExternalObjectId(product.getCouponCode());
            //商家优惠
            orderSettlementCreateReq.setShopDiscountAmount(product.getTotalDiscountAmount().longValue());
            //结算金额
            orderSettlementCreateReq.setSettlementAmount(product.getTotalDiscountAmount().longValue());
            //是否线上 false:不是 true:是
            orderSettlementCreateReq.setIsOnline(true);
            orderSettlementCreateReq.setSettlementType(0);
            orderSettlementCreateReqList.add(orderSettlementCreateReq);
        }
        // 设置商品行优惠明细
        if (CollectionUtils.isNotEmpty(product.getActivityDiscountsDtos())) {
            for (ActivityDiscountsDto activityDiscountsDto : product.getActivityDiscountsDtos()) {
                //优惠信息转换
                OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
                orderSettlementCreateReq.setProductId(product.getSkuId());
                orderSettlementCreateReq.setNumber(product.getQty());
                orderSettlementCreateReq.setProductSeq(index);
                orderSettlementCreateReq.setExternalObjectId(activityDiscountsDto.getActivityCode());
                //商家优惠
                orderSettlementCreateReq.setShopDiscountAmount(activityDiscountsDto.getDiscountAmount().longValue());
                //结算金额
                orderSettlementCreateReq.setSettlementAmount(activityDiscountsDto.getDiscountAmount().longValue());
                //是否线上 false:不是 true:是
                orderSettlementCreateReq.setIsOnline(true);
                orderSettlementCreateReq.setSettlementType(getOrderSettlementType(activityDiscountsDto.getActivityType()));
                orderSettlementCreateReq.setNote(activityDiscountsDto.getActivityName());
                JSONObject jsonObject = new JSONObject();
                if (ActivityTypeEnum.TYPE_32.getCode().equals(activityDiscountsDto.getActivityType())) {
                    jsonObject.put("tenderId", activityDiscountsDto.getTenderId());
                }
                if (null != activityDiscountsDto.getExtendType()) {
                    jsonObject.put("extendType", activityDiscountsDto.getExtendType());
                }
                orderSettlementCreateReq.setExtInfo(jsonObject.toJSONString());
                orderSettlementCreateReqList.add(orderSettlementCreateReq);
            }

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

    private String getThirdPropertyId(List<ProductAttributeGroup> productAttributeGroups, String addInfo) {
        String thirdProductPropertyId = "";
        if (StringUtils.isBlank(addInfo) || CollectionUtils.isEmpty(productAttributeGroups)) {
            return thirdProductPropertyId;
        }
        JSONObject jsonObject = JSONObject.parseObject(addInfo);
        String attributeNames = (String) jsonObject.get("attributeNames");
        List<String> list = new ArrayList<>();
        String[] split = attributeNames.split("/");

        List<AttributeValue> attributeValues = new ArrayList<>();
        for (ProductAttributeGroup attributeGroup : productAttributeGroups) {
            attributeValues.addAll(attributeGroup.getAttributeValues());
        }

        for (int i = 0; i < split.length; i++) {
            for (AttributeValue attributeValue : attributeValues) {
                if (attributeValue.getAttributeValue().equals(split[i])) {
                    list.add(attributeValue.getCustomerCode());
                    break;
                }
            }
        }
        if (CollectionUtils.isNotEmpty(list)) {
            thirdProductPropertyId = StringUtils.join(list, ",");
        }
        return thirdProductPropertyId;
    }

    private Long convertCreateOrderCost(Long originalAmount, List<OrderSettlementCreateReq> orderSettlementCreateReqList, List<OrderCostCreateReq> orderCostCreateReqs,
                                        CreateOrderBaseVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto, StoreResponseDto storeResponseDto) {

        boolean hasDeliveryMonthCard = false;
        for (ActivityDiscountsDto activityDiscountsDto : shoppingCartGoodsDto.getActivityDiscountsDtos()) {
            OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
            orderSettlementCreateReq.setSettlementType(getOrderSettlementType(activityDiscountsDto.getActivityType()));
            orderSettlementCreateReq.setExternalObjectId(activityDiscountsDto.getActivityCode());
            orderSettlementCreateReq.setNote(activityDiscountsDto.getActivityName());
            orderSettlementCreateReq.setNumber(1);
            //商家优惠
            orderSettlementCreateReq.setShopDiscountAmount(activityDiscountsDto.getDiscountAmount().longValue());
            //结算金额
            orderSettlementCreateReq.setSettlementAmount(activityDiscountsDto.getDiscountAmount().longValue());
            //是否线上 false:不是 true:是
            orderSettlementCreateReq.setIsOnline(true);
            orderSettlementCreateReqList.add(orderSettlementCreateReq);
        }

        int index = 1;
        if (shoppingCartGoodsDto.getDeliveryAmount() > 0) {
            OrderCostCreateReq orderCostCreateReq = new OrderCostCreateReq();
            orderCostCreateReq.setCostName("配送费");
            //新订单服务  1=包装费,2=运费,3=餐盒单价,4=餐盒数量
            orderCostCreateReq.setCostType(CostTypeEnum.DELIVERY_AMOUNT.getCode());
            orderCostCreateReq.setActualCostAmount(shoppingCartGoodsDto.getDiscountDeliveryAmount());
            orderCostCreateReq.setCostAmount(shoppingCartGoodsDto.getDeliveryAmount());
            originalAmount += shoppingCartGoodsDto.getDeliveryAmount();
            orderCostCreateReq.setProductSeq(index++);
            //1=订单,2=订单商品,3=售后单
            orderCostCreateReq.setBillType(1);
            if (hasDeliveryMonthCard && StringUtils.isNotBlank(storeResponseDto.getBenefitCardDiscountAmount())) {
                orderCostCreateReq.setNote(Double.valueOf(Double.valueOf(storeResponseDto.getBenefitCardDiscountAmount()) * 100).intValue() + "");
            }
            orderCostCreateReqs.add(orderCostCreateReq);
        }
        if (shoppingCartGoodsDto.getPackageAmount() > 0) {
            OrderCostCreateReq orderCostCreateReq = new OrderCostCreateReq();
            orderCostCreateReq.setCostName("包装费");
            //新订单服务  1=包装费,2=运费,3=餐盒单价,4=餐盒数量
            orderCostCreateReq.setCostType(CostTypeEnum.PACK_AMOUNT.getCode());
            orderCostCreateReq.setActualCostAmount(shoppingCartGoodsDto.getPackageAmount());
            orderCostCreateReq.setCostAmount(shoppingCartGoodsDto.getPackageAmount());
            originalAmount += shoppingCartGoodsDto.getDeliveryAmount();
            orderCostCreateReq.setProductSeq(index++);
            //1=订单,2=订单商品,3=售后单
            orderCostCreateReq.setBillType(1);
            orderCostCreateReqs.add(orderCostCreateReq);
        }
        // 会员卡
        Long cardOriginalAmount = shoppingCartGoodsDto.getCardOriginalAmount() != null ? shoppingCartGoodsDto.getCardOriginalAmount() : 0L;
        if (cardOriginalAmount > 0) {
            OrderCostCreateReq orderCostCreateReq = new OrderCostCreateReq();
            orderCostCreateReq.setCostName("会员卡原价");
            //新订单服务  1=包装费,2=运费,3=餐盒单价,4=餐盒数量
            orderCostCreateReq.setCostType(CostTypeEnum.CARD_ORIGINAL_AMOUNT.getCode());
            orderCostCreateReq.setActualCostAmount(cardOriginalAmount);
            orderCostCreateReq.setCostAmount(cardOriginalAmount);
            originalAmount += cardOriginalAmount;
            orderCostCreateReq.setProductSeq(index++);
            //1=订单,2=订单商品,3=售后单
            orderCostCreateReq.setBillType(1);
            orderCostCreateReqs.add(orderCostCreateReq);
        }

        // fisherman  这里缺少 积分扣减 会员卡优惠  cn.freemud.adapter.OrderAdapter.convent2CreateOrderDto
        return originalAmount;
    }

    /**
     * 将促销的枚举 ActivityTypeEnum 和orderAccountType 关联映射
     */
    public Integer getOrderSettlementType(Integer activityType) {
        if (ActivityTypeEnum.TYPE_1.getCode().equals(activityType) || ActivityTypeEnum.TYPE_11.getCode().equals(activityType) || ActivityTypeEnum.TYPE_12.getCode().equals(activityType) || ActivityTypeEnum.TYPE_13.getCode().equals(activityType)) {
            return 2;
        }
        if (ActivityTypeEnum.TYPE_3.getCode().equals(activityType)) {
            return 10;
        }
        if (ActivityTypeEnum.TYPE_2.getCode().equals(activityType) || ActivityTypeEnum.TYPE_21.getCode().equals(activityType)) {
            return 206;
        }
        if (ActivityTypeEnum.TYPE_81.getCode().equals(activityType)) {
            return 46;
        }
        if (ActivityTypeEnum.TYPE_32.getCode().equals(activityType)) {
            return 118;
        }
        if (ActivityTypeEnum.TYPE_34.getCode().equals(activityType)) {
            return 99;
        }
        if (ActivityTypeEnum.TYPE_31.getCode().equals(activityType)) {
            return 208;
        }
        if (ActivityTypeEnum.TYPE_61.getCode().equals(activityType)) {
            return 23;
        }
        if (ActivityTypeEnum.TYPE_53.getCode().equals(activityType)) {
            return 20;
        }
        if (ActivityTypeEnum.TYPE_211.getCode().equals(activityType)) {
            return 211;
        }
        if (ActivityTypeEnum.TYPE_104.getCode().equals(activityType)) {
            return 104;
        }
        if (ActivityTypeEnum.TYPE_14.getCode().equals(activityType)) {
            return 1014;
        }
        if (ActivityTypeEnum.TYPE_320.getCode().equals(activityType)) {
            return 220;
        }
        if (ActivityTypeEnum.TYPE_23.getCode().equals(activityType)) {
            return 47;
        }
        if (ActivityTypeEnum.TYPE_221.getCode().equals(activityType)) {
            return 211;
        }
        // coco商品代金券
        if (ActivityTypeEnum.TYPE_36.getCode().equals(activityType)) {
            return 36;
        }
        return activityType;
    }

    public CreateOrderRequest convent2CustomCreateOrderRequest(CreateOrderBo createOrderBo) {
        switch (createOrderBo.getCreateOrderScene()) {
            case SAAS:
                return convent2SaasCreateOrderRequest(createOrderBo);
            default:
                return convent2SaasCreateOrderRequest(createOrderBo);
        }
    }

    public CreateOrderRequest convent2SaasCreateOrderRequest(CreateOrderBo createOrderBo) {
        return createOrderBo.getCreateOrderRequest();
    }

    /**
     * 获取扣减库存信息
     *
     * @param orderBean       订单信息
     * @param products        订单商品列表
     * @param stockChangeType 库存改变类型
     * @return
     */
    public UpdateStocksRequest getUpdateProductStock(OrderBeanV1 orderBean, List<ShoppingCartGoodsDto.CartGoodsDetailDto> 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(com.freemud.application.sdk.api.util.DateUtil.convert2String(new Date(), com.freemud.application.sdk.api.util.DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        List<ProductStocksVO> productStocks = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(products)) {
            products.forEach(product -> {
                if (product.isStockLimit()) {
                    ProductStocksVO productStocksVO = new ProductStocksVO();
                    productStocksVO.setProductId(StringUtils.isNotBlank(product.getSkuId()) ? product.getSkuId() : product.getSpuId());
                    productStocksVO.setQty(product.getQty());
                    productStocks.add(productStocksVO);

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

    /**
     * 积分扣减或冲正
     *
     * @param orderBean 订单
     * @param isReduce  是否扣减：true扣减；false冲正
     * @return
     */
    public UserScoreRequest convent2UserScoreRequest(OrderBeanV1 orderBean, ShoppingCartGoodsDto shoppingCartGoodsDto, boolean isReduce, Integer useCustomerScore) {
        Long scoreReduceAmount = shoppingCartGoodsDto.getScoreReduceAmount() != null ? shoppingCartGoodsDto.getScoreReduceAmount() : 0;
        if (scoreReduceAmount > 0 && CustomerScoreConstant.SUBSTRACT.getValue().equals(useCustomerScore)) {
            UserScoreRequest userScoreRequest = new UserScoreRequest();
            userScoreRequest.setMemberId(orderBean.getUserId());
            userScoreRequest.setPartnerId(orderBean.getCompanyId());
            userScoreRequest.setReduceAmount(scoreReduceAmount.intValue());
            userScoreRequest.setScoreOrderNo(orderBean.getOid());
            userScoreRequest.setChangeType(isReduce ? 2 : 1);
            userScoreRequest.setOperationType(isReduce ? 14 : 2);
            userScoreRequest.setStoreId(orderBean.getShopId());
            return userScoreRequest;
        } else {
            return null;
        }
    }

    public CouponLockRequest convert2CouponLockRequest(OrderBeanV1 orderBean, ShoppingCartGoodsDto shoppingCartGoodsDto) {
        //fisherman 已经废弃 20210616
        if (CollectionUtils.isEmpty(shoppingCartGoodsDto.getActivityDiscountsDtos())) {
            return null;
        }
        Optional<ActivityDiscountsDto> activityDiscountsDtoOptional = shoppingCartGoodsDto.getActivityDiscountsDtos().stream().filter(activityDiscountsDto ->
                activityDiscountsDto.getActivityType().equals(ActivityTypeEnum.TYPE_3)
                        || activityDiscountsDto.getActivityType().equals(ActivityTypeEnum.TYPE_32)
                        || activityDiscountsDto.getActivityType().equals(ActivityTypeEnum.TYPE_31)).findFirst();
        if (!activityDiscountsDtoOptional.isPresent() || activityDiscountsDtoOptional.get().getDiscountAmount() == 0) {
            return null;
        }
        ActivityDiscountsDto activityDiscountsDto = activityDiscountsDtoOptional.get();
        CouponLockRequest couponLockRequest = new CouponLockRequest();
        // 订单号 替换成唯一序号
        couponLockRequest.setPartnerId(orderBean.getCompanyId());
        couponLockRequest.setOrderId(orderBean.getOid());
        //couponLockRequest.setCouponCode(activityDiscountsDto.getActivityCode());
        return couponLockRequest;

    }

}