
package com.tmerclub.cloud.api.order.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.coupon.dto.LockCouponDTO;
import com.tmerclub.cloud.api.coupon.feign.CouponOrderFeignClient;
import com.tmerclub.cloud.api.feign.SearchSpuFeignClient;
import com.tmerclub.cloud.api.order.constant.ShopCityStatus;
import com.tmerclub.cloud.api.product.dto.StockBillLogItemDTO;
import com.tmerclub.cloud.api.product.feign.SkuStockChangeFeignClient;
import com.tmerclub.cloud.api.product.feign.SpuFeignClient;
import com.tmerclub.cloud.api.user.dto.UserScoreLockDTO;
import com.tmerclub.cloud.api.user.feign.UserScoreLockFeignClient;
import com.tmerclub.cloud.common.cache.constant.CacheNames;
import com.tmerclub.cloud.common.cache.constant.OrderCacheNames;
import com.tmerclub.cloud.common.cache.util.CacheManagerUtil;
import com.tmerclub.cloud.common.cache.util.RedisUtil;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.constant.DeliveryType;
import com.tmerclub.cloud.common.order.constant.OrderType;
import com.tmerclub.cloud.common.order.constant.ShopCartItemDiscountType;
import com.tmerclub.cloud.common.order.dto.*;
import com.tmerclub.cloud.common.order.util.OrderLangUtil;
import com.tmerclub.cloud.common.order.vo.*;
import com.tmerclub.cloud.common.product.constant.PreSaleType;
import com.tmerclub.cloud.common.product.constant.ShopCartSpuActivityType;
import com.tmerclub.cloud.common.product.constant.SpuMold;
import com.tmerclub.cloud.common.product.vo.SpuVO;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.BeanUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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


/**
 * 提交订单适配
 *
 * @author tmerclub
 * @date 2020/12/07
 */
@Component
public class SubmitOrderManager {
    private static final Logger logger = LoggerFactory.getLogger(SubmitOrderManager.class);

    @Autowired
    private CacheManagerUtil cacheManagerUtil;

    @DubboReference
    private SkuStockChangeFeignClient skuStockChangeFeignClient;

    @DubboReference
    private CouponOrderFeignClient couponOrderFeignClient;

    @DubboReference
    private UserScoreLockFeignClient userScoreLockFeignClient;

    @DubboReference
    private SpuFeignClient spuFeignClient;

    @DubboReference
    private SearchSpuFeignClient searchSpuFeignClient;

    public ServerResponseEntity<ShopCartOrderMergerVO> checkSubmitInfo(SubmitOrderDTO submitOrderParam, Long userId) {
        ShopCartOrderMergerVO mergerOrder = cacheManagerUtil.getCache(OrderCacheNames.ORDER_CONFIRM_KEY, String.valueOf(userId), ShopCartOrderMergerVO.class);
        // 看看订单有没有过期
        if (mergerOrder == null) {
            return ServerResponseEntity.showFailMsg("订单已过期，请重新提交");
        }
        // 防止重复提交
        boolean cad = RedisUtil.cad(OrderCacheNames.ORDER_CONFIRM_UUID_KEY + CacheNames.UNION + userId, String.valueOf(userId));
        if (!cad) {
            return ServerResponseEntity.fail(ResponseEnum.REPEAT_ORDER);
        }
        //获取套餐订单项
        List<ShopCartOrderVO> cartOrders = mergerOrder.getShopCartOrders();
        Map<Long, Integer> dvyMap = mergerOrder.getDvyTypes().stream().collect(Collectors.toMap(DvyTypeDTO::getShopId, DvyTypeDTO::getDvyType));
        for (ShopCartOrderVO cartOrder : cartOrders) {
            if (Objects.equals(dvyMap.get(cartOrder.getShopId()), DeliveryType.SAME_CITY.value())) {
                if (Objects.nonNull(cartOrder.getShopCityStatus()) && Objects.equals(cartOrder.getShopCityStatus(), ShopCityStatus.NO_CONFIG.value())) {
                    // 当前店铺未开启同城配送
                    return ServerResponseEntity.showFailMsg("店铺" + cartOrder.getShopName() + "未开启同城配送");
                }
                if (Objects.nonNull(cartOrder.getShopCityStatus()) && cartOrder.getShopCityStatus() < ShopCityStatus.USABLE.value()) {
                    // 超出商家配送距离或起送费不够
                    return ServerResponseEntity.showFailMsg("超出商家" + cartOrder.getShopName() + "的配送距离或起送费不够");
                }
            }
            // 请选择自提点并填写完整的自提信息
            if (Objects.equals(dvyMap.get(cartOrder.getShopId()), DeliveryType.STATION.value())
                    && Objects.isNull(mergerOrder.getStationId()) && Objects.isNull(submitOrderParam.getOrderSelfStationDto())) {
                return ServerResponseEntity.showFailMsg("请选择自提点并填写完整的自提信息");
            }
            List<ShopCartItemDiscountVO> shopCartItemDiscounts = cartOrder.getShopCartItemDiscounts();
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
                // 超出配送距离
                for (ShopCartItemVO shopCartItem : shopCartItemDiscount.getShopCartItems()) {
                    if (!shopCartItem.getIsDelivery() && !Objects.equals(dvyMap.get(cartOrder.getShopId()), DeliveryType.STATION.value())) {
                        logger.info("商品不在配送范围且未选择自提");
                        throw new LuckException(ResponseEnum.DELIVERY_OVER);
                    }
                }
                if (Objects.equals(shopCartItemDiscount.getType(), ShopCartItemDiscountType.COMBO.value())){
                    logger.info("套餐商品");
                    cartOrder.setHasComboOrder(true);
                }
            }
        }
        if (Objects.nonNull(mergerOrder.getUserHasScore()) && Objects.nonNull(mergerOrder.getUsableScore())) {
            if (mergerOrder.getUserHasScore() < mergerOrder.getUsableScore()) {
                throw new LuckException(ResponseEnum.NOT_SCORE);
            }
        }
        // 检查下虚拟商品的所需留言是否填写完成
        if (CollectionUtil.isNotEmpty(submitOrderParam.getVirtualRemarkList())) {
            List<VirtualRemarkDTO> virtualRemarkList = submitOrderParam.getVirtualRemarkList();
            // 如果至少要输入一个备注信息，则不能为空
            if (isRequired(mergerOrder) && CollectionUtil.isEmpty(virtualRemarkList)) {
                // 不能为空
                return ServerResponseEntity.showFailMsg("备注信息不能为空");
            }
            for (VirtualRemarkDTO virtualRemarkVO : virtualRemarkList) {
                if (!Objects.isNull(virtualRemarkVO.getRequired())
                        && virtualRemarkVO.getRequired()
                        && StrUtil.isBlank(virtualRemarkVO.getValue())) {
                    // 不能为空
                    return ServerResponseEntity.showFailMsg("备注信息不能为空");
                }
            }
            mergerOrder.setVirtualRemarkList(BeanUtil.mapAsList(virtualRemarkList, VirtualRemarkVO.class));
        }
        // 处理一下团购订单和秒杀的供应商信息
        handleGroupAndSeckillOrderSupplier(mergerOrder);
        //如果是套餐商品设置订单
        // 设置自提信息
        mergerOrder.setOrderSelfStation(BeanUtil.map(submitOrderParam.getOrderSelfStationDto(), OrderSelfStationVO.class));

        // 订单拆单
        this.handleMergeOrder(submitOrderParam, userId, mergerOrder);

        List<Integer> dvyList = mergerOrder.getDvyTypes().stream().map(DvyTypeDTO::getDvyType).toList();

        // 快递和同城配送的地址信息
        if (dvyList.contains(DeliveryType.DELIVERY.value()) && Objects.isNull(mergerOrder.getUserAddr())) {
            // 请填写收货地址
            throw new LuckException("请填写收货地址");
        }
        return ServerResponseEntity.success(mergerOrder);
    }

    private void handleMergeOrder(SubmitOrderDTO submitOrderParam, Long userId, ShopCartOrderMergerVO mergerOrder) {
        List<OrderShopDTO> orderShopParams = submitOrderParam.getOrderShopParam();

        List<ShopCartOrderVO> shopCartOrders = mergerOrder.getShopCartOrders();
        // 检查商品状态
//        this.checkSpuStatus(shopCartOrders);
        List<CouponOrderVO> shopCoupons = getShopCoupons(submitOrderParam, mergerOrder, orderShopParams, shopCartOrders);
        mergerOrder.setShopCoupons(shopCoupons);
        // 需要拆分订单(订单类型为普通订单才需要拆单)
        if (needSplitShopCartOrder(mergerOrder)) {
            // 虚拟商品拆分订单
            splitShopCartOrderDtoByVirtual(mergerOrder, userId);
            // 套餐商品拆单
            splitComboShopCartOrderDto(mergerOrder, userId);
            // 根据供应商拆分订单
            splitShopCartOrderDto(mergerOrder, userId);
            // 根据预售拆分订单
            splitShopCartOrderDtoByPreSale(mergerOrder, userId);
        }
    }

    private static boolean isRequired(ShopCartOrderMergerVO mergerOrder) {
        boolean isRequired = false;
        for (VirtualRemarkVO virtualRemarkVO : mergerOrder.getVirtualRemarkList()) {
            if (!Objects.isNull(virtualRemarkVO.getIsRequired())
                    && virtualRemarkVO.getIsRequired()) {
                isRequired = true;
                break;
            }
        }
        return isRequired;
    }


    private static List<CouponOrderVO> getShopCoupons(SubmitOrderDTO submitOrderParam, ShopCartOrderMergerVO mergerOrder, List<OrderShopDTO> orderShopParams, List<ShopCartOrderVO> shopCartOrders) {
        List<CouponOrderVO> shopCoupons = new ArrayList<>(Constant.INITIAL_CAPACITY);
        // 设置备注
        for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
            setRemark(orderShopParams, shopCartOrder);
            if (CollUtil.isNotEmpty(shopCartOrder.getCoupons())) {
                for (CouponOrderVO shopCoupon : shopCartOrder.getCoupons()) {
                    if (Objects.equals(Boolean.TRUE, shopCoupon.getChoose())) {
                        shopCoupons.add(shopCoupon);
                    }
                }
            }
        }
        setOrderInvoice(submitOrderParam, mergerOrder);
        return shopCoupons;
    }

    private static void setOrderInvoice(SubmitOrderDTO submitOrderParam, ShopCartOrderMergerVO mergerOrder) {
        //设置发票
        List<OrderInvoiceDTO> orderInvoiceList = submitOrderParam.getOrderInvoiceList();
        if (CollectionUtil.isNotEmpty(orderInvoiceList)) {
            mergerOrder.setOrderInvoiceList(orderInvoiceList);
        }
    }

    private static void setRemark(List<OrderShopDTO> orderShopParams, ShopCartOrderVO shopCartOrder) {
        for (OrderShopDTO orderShopParam : orderShopParams) {
            if (Objects.equals(shopCartOrder.getShopId(), orderShopParam.getShopId())) {
                shopCartOrder.setRemarks(orderShopParam.getRemarks());
            }
        }
    }

    /**
     * 是否需要拆单
     * 1.套餐需要拆单
     * 2.供应商需要拆单
     * 3.不是定金预售商品，需要拆单
     *
     * @param mergerOrder
     * @return
     */
    private boolean needSplitShopCartOrder(ShopCartOrderMergerVO mergerOrder) {
        // 普通订单和团购才需要拆单
        if (Objects.equals(mergerOrder.getOrderType().value(), OrderType.SECKILL.value())) {
            return Boolean.FALSE;
        }
        // 如果不是定金预售商品，需要拆分订单
        if (Objects.equals(mergerOrder.getPreSaleType(), PreSaleType.FULLPAY.value())) {
            return Boolean.TRUE;
        }
        for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartOrder.getShopCartItemDiscounts()) {
                // 套餐需要拆单
                if (Objects.equals(shopCartItemDiscount.getType(), ShopCartSpuActivityType.COMBO.value())) {
                    return Boolean.TRUE;
                }
                // 供应商需要拆单
                for (ShopCartItemVO shopCartItem : shopCartItemDiscount.getShopCartItems()) {
                    // 供应商商品且是供应商发货，需要拆单
                    boolean supplierSplitShopCartOrder = Objects.nonNull(shopCartItem.getSupplierId()) &&
                            !Objects.equals(shopCartItem.getSupplierId(), 0L) &&
                            Objects.equals(shopCartItem.getSupplierDeliveryType(), 1);
                    if (supplierSplitShopCartOrder) {
                        return Boolean.TRUE;
                    }
                    // 判断下是否为预售商品,如果是预售商品就拆单
                    if (Objects.isNull(shopCartItem.getPreSaleType()) || Objects.equals(shopCartItem.getPreSaleType(), -1)) {
                        return Boolean.TRUE;
                    }
                    // 判断下是否组合商品
                    if (Objects.isNull(shopCartItem.getMold()) || Objects.equals(shopCartItem.getMold(), SpuMold.COMBO.value())) {
                        return Boolean.TRUE;
                    }
                }
            }
        }
        return Boolean.FALSE;
    }


    private void splitComboShopCartOrderDto(ShopCartOrderMergerVO mergerOrder, Long userId) {
        List<ShopCartOrderVO> shopCartOrderList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        Set<Long> needMainOrderIds = new HashSet<>(Constant.INITIAL_CAPACITY);
        for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
            Iterator<ShopCartItemDiscountVO> shopCartIterator = shopCartOrder.getShopCartItemDiscounts().iterator();
            boolean recalculate = false;
            int index = 0;
            while (shopCartIterator.hasNext()) {
                ShopCartItemDiscountVO shopCartItemDiscountDto = shopCartIterator.next();
                // 非套餐项不用处理
                if (!Objects.equals(shopCartItemDiscountDto.getType(), ShopCartSpuActivityType.COMBO.value())) {
                    continue;
                }
                shopCartItemDiscountDto.getChooseComboItemVo().setIndex(index);
                index++;
                // 如果套餐中没有虚拟商品，不用处理
                Iterator<ShopCartItemVO> iterator = shopCartItemDiscountDto.getShopCartItems().iterator();
                boolean isSplit = false;
                while (iterator.hasNext()) {
                    int size = shopCartItemDiscountDto.getShopCartItems().size();
                    ShopCartItemVO shopCartItemDto = iterator.next();
                    // 不是虚拟商品，不用处理
                    if (Objects.isNull(shopCartItemDto.getMold()) || shopCartItemDto.getMold() != 1) {
                        continue;
                    }
                    if (mergerOrder.getSpuMold() == 0) {
                        logger.info("订单中有虚拟商品，需要拆单");
                        mergerOrder.setSpuMold(1);
                    }
                    // 套餐中的虚拟商品，但只有一个订单项
                    if (Objects.equals(size, 1)) {
                        continue;
                    }
                    ShopCartOrderVO shopCartOrderDto = new ShopCartOrderVO();
                    shopCartOrderDto.setHasComboOrder(shopCartOrder.getHasComboOrder());
                    // 拆分虚拟商品
                    shopCartOrderDto.setShopId(shopCartOrder.getShopId());
                    shopCartOrderDto.setShopName(shopCartOrder.getShopName());
                    shopCartOrderDto.setRemarks(shopCartOrder.getRemarks());
                    shopCartOrderDto.setShopCityStatus(shopCartOrder.getShopCityStatus());
                    shopCartOrderDto.setStartDeliveryFee(shopCartOrder.getStartDeliveryFee());
                    shopCartOrderDto.setIsRefund(shopCartOrder.getIsRefund());
                    shopCartOrderDto.setOrderType(shopCartOrder.getOrderType());
                    shopCartOrderDto.setShopCartItemDiscounts(new ArrayList<>(0));
                    shopCartOrderDto.setActualTotal(shopCartOrderDto.getTotal());
                    shopCartOrderDto.setSpuMold(1);
                    SpuVO spuVO = spuFeignClient.getDetailById(shopCartItemDto.getSpuId()).getData();
                    shopCartOrderDto.setWriteOffMultipleCount(spuVO.getWriteOffMultipleCount());
                    shopCartOrderDto.setWriteOffNum(spuVO.getWriteOffNum());
                    shopCartOrderDto.setWriteOffStart(spuVO.getWriteOffStart());
                    shopCartOrderDto.setWriteOffEnd(spuVO.getWriteOffEnd());
                    ShopCartItemDiscountVO shopCartItemDiscount = new ShopCartItemDiscountVO();
                    shopCartItemDiscount.setChooseComboItemVo(shopCartItemDiscountDto.getChooseComboItemVo());
                    shopCartItemDiscount.setShopCartItems(Collections.singletonList(shopCartItemDto));
                    shopCartOrderDto.getShopCartItemDiscounts().add(shopCartItemDiscount);
                    loadShopCartOrderDto(shopCartOrderDto);
                    shopCartOrderList.add(shopCartOrderDto);
                    // 移除该订单项
                    iterator.remove();
                    if (!isSplit) {
                        isSplit = true;
                    }
                    if (!recalculate) {
                        recalculate = true;
                    }
                }
            }
            if (!recalculate) {
                continue;
            }

            loadShopCartOrderDto(shopCartOrder);
        }
        if (CollUtil.isNotEmpty(shopCartOrderList)) {
            mergerOrder.getShopCartOrders().addAll(shopCartOrderList);
        }
    }


    private static boolean isStation(ShopCartOrderMergerVO mergerOrder, Map<Long, Integer> dvyTypeMap, ShopCartOrderVO shopCartOrder) {
        int dvyType = dvyTypeMap.get(shopCartOrder.getShopId());
        boolean station = false;
        //判断是否是自提订单
        if (Objects.equals(dvyType, DeliveryType.STATION.value())) {
            //自提订单的地址信息
            if (Objects.isNull(mergerOrder.getOrderSelfStation())) {
                // 请填写自提信息
                throw new LuckException("请填写自提信息");
            }
            Integer mold = shopCartOrder.getShopCartItemDiscounts().get(0).getShopCartItems().get(0).getMold();
            // 非虚拟商品才需要自提
            if (!Objects.equals(mold, SpuMold.VIRTUAL.value())) {
                station = true;
            }
        }
        return station;
    }

    private void splitShopCartOrderDto(ShopCartOrderMergerVO mergerOrder, Long userId) {
        List<ShopCartOrderVO> shopCartOrders = new ArrayList<>(Constant.INITIAL_CAPACITY);
        List<ShopCartOrderVO> normalShopCartOrderList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        Map<Long, Map<Long, ShopTransFeeVO>> supplierIdWithShopTransFeeMap = mergerOrder.getSupplierIdWithShopTransFeeMap();
        for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
            // 注意一下等级免运费金额，因为一个店如果免运费，则肯定所以项都免运费了
            long levelFreeTransfee = Objects.isNull(shopCartOrder.getLevelFreeTransfee()) ? 0L : shopCartOrder.getLevelFreeTransfee();
            Iterator<ShopCartItemDiscountVO> shopCartIterator = shopCartOrder.getShopCartItemDiscounts().iterator();
            long transFee = shopCartOrder.getTransfee();
            List<ShopCartItemVO> normalShopCartItemList = new ArrayList<>(Constant.INITIAL_CAPACITY);
            Map<Long, ShopCartOrderVO> shopCartOrderMap = new HashMap<>(12);
            while (shopCartIterator.hasNext()) {
                ShopCartItemDiscountVO shopCartItemDiscountDto = shopCartIterator.next();
                Iterator<ShopCartItemVO> iterator = shopCartItemDiscountDto.getShopCartItems().iterator();
                while (iterator.hasNext()) {
                    ShopCartItemVO shopCartItemDto = iterator.next();
                    // 判断下是否为供应商商品,如果是商家代销供应商商品且为供应商发货才继续
                    if (Objects.equals(shopCartItemDto.getSupplierId(), 0L) || !Objects.equals(shopCartItemDto.getSupplierDeliveryType(), 1)) {
                        // 普通的商品和商家仓库自己发货的放入同一个list
                        normalShopCartItemList.add(shopCartItemDto);
                        continue;
                    }

                    ShopCartOrderVO shopCartOrderVO = new ShopCartOrderVO();
                    shopCartOrderVO.setHasComboOrder(shopCartOrder.getHasComboOrder());
                    // 拆分供应商商品
                    if (shopCartOrderMap.containsKey(shopCartItemDto.getSupplierId())) {
                        shopCartOrderVO = shopCartOrderMap.get(shopCartItemDto.getSupplierId());
                        ShopCartItemDiscountVO shopCartItemDiscount = new ShopCartItemDiscountVO();
                        shopCartItemDiscount.setShopCartItems(Collections.singletonList(shopCartItemDto));
                        shopCartOrderVO.getShopCartItemDiscounts().add(shopCartItemDiscount);
                    } else {
                        setShopCartOrderInfo(userId, shopCartOrder, shopCartItemDto, shopCartOrderVO);
                        shopCartOrderMap.put(shopCartItemDto.getSupplierId(), shopCartOrderVO);
                    }
                    // 移除该订单项
                    iterator.remove();
                }
            }
            Map<Long, ShopTransFeeVO> shopSupplierIdWithShopTransFeeMap = supplierIdWithShopTransFeeMap.get(shopCartOrder.getShopId());
            // 重新算一下供应商
            if (CollectionUtil.isNotEmpty(shopCartOrderMap)) {
                for (Long supplierId : shopCartOrderMap.keySet()) {
                    // 供应商运费放进去
                    ShopTransFeeVO shopTransFeeVO = shopSupplierIdWithShopTransFeeMap.get(supplierId);
                    // 店铺订单计算
                    ShopCartOrderVO shopCartOrderVO = shopCartOrderMap.get(supplierId);
                    // 如果有等级免运费金额，则所有都免运费
                    shopCartOrderVO.setTransfee(Objects.isNull(shopTransFeeVO) ? 0L : shopTransFeeVO.getTransfee());
                    shopCartOrderVO.setLevelFreeTransfee(Math.min(levelFreeTransfee, shopCartOrderVO.getTransfee()));
                    this.loadShopCartOrderDto(shopCartOrderVO);
                    shopCartOrders.add(shopCartOrderVO);
                    transFee = transFee - shopCartOrderVO.getTransfee();
                }
            }
            // 普通商品和商家仓库发货的供应商商品做一个order
            if (CollectionUtil.isNotEmpty(normalShopCartItemList)) {
                ShopCartItemDiscountVO shopCartItemDiscount = new ShopCartItemDiscountVO();
                shopCartItemDiscount.setShopCartItems(normalShopCartItemList);
                shopCartOrder.setTransfee(transFee);
                shopCartOrder.setLevelFreeTransfee(Math.min(levelFreeTransfee, shopCartOrder.getTransfee()));
                shopCartOrder.setShopCartItemDiscounts(Collections.singletonList(shopCartItemDiscount));
                this.loadShopCartOrderDto(shopCartOrder);
                normalShopCartOrderList.add(shopCartOrder);
            }
        }
        mergerOrder.setShopCartOrders(new ArrayList<>(Constant.INITIAL_CAPACITY));
        if (CollectionUtil.isNotEmpty(normalShopCartOrderList)) {
            mergerOrder.setShopCartOrders(normalShopCartOrderList);
        }
        if (CollUtil.isNotEmpty(shopCartOrders)) {
            mergerOrder.getShopCartOrders().addAll(shopCartOrders);
        }
    }

    private void setShopCartOrderInfo(Long userId, ShopCartOrderVO shopCartOrder, ShopCartItemVO shopCartItemDto, ShopCartOrderVO shopCartOrderVO) {
        shopCartOrderVO.setOrderType(shopCartOrder.getOrderType());
        shopCartOrderVO.setShopId(shopCartOrder.getShopId());
        shopCartOrderVO.setShopName(shopCartOrder.getShopName());
        shopCartOrderVO.setRemarks(shopCartOrder.getRemarks());
        shopCartOrderVO.setSupplierId(shopCartOrder.getSupplierId());
        shopCartOrderVO.setSupplierDeliveryType(shopCartOrder.getSupplierDeliveryType());
        shopCartOrderVO.setShopCartItemDiscounts(new ArrayList<>(Constant.INITIAL_CAPACITY));
        ShopCartItemDiscountVO shopCartItemDiscount = new ShopCartItemDiscountVO();
        shopCartItemDiscount.setShopCartItems(Collections.singletonList(shopCartItemDto));
        shopCartOrderVO.getShopCartItemDiscounts().add(shopCartItemDiscount);
    }

    private void splitShopCartOrderDtoByPreSale(ShopCartOrderMergerVO mergerOrder, Long userId) {
        List<ShopCartOrderVO> shopCartOrders = new ArrayList<>(Constant.INITIAL_CAPACITY);
        List<ShopCartOrderVO> normalShopCartOrderList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        Map<Long, ShopTransFeeVO> preSaleTransFeeMap = mergerOrder.getPreSaleTransFeeMap();
        for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
            // 注意一下等级免运费金额，因为一个店如果免运费，则肯定所以项都免运费了
            long levelFreeTransfee = Objects.isNull(shopCartOrder.getLevelFreeTransfee()) ? 0L : shopCartOrder.getLevelFreeTransfee();
            Iterator<ShopCartItemDiscountVO> shopCartIterator = shopCartOrder.getShopCartItemDiscounts().iterator();
            long transFee = shopCartOrder.getTransfee();
            Map<Long, ShopCartOrderVO> shopCartOrderMap = new HashMap<>(12);
            List<ShopCartItemVO> normalShopCartItemList = new ArrayList<>(Constant.INITIAL_CAPACITY);
            while (shopCartIterator.hasNext()) {
                ShopCartItemDiscountVO shopCartItemDiscountDto = shopCartIterator.next();
                Iterator<ShopCartItemVO> iterator = shopCartItemDiscountDto.getShopCartItems().iterator();
                while (iterator.hasNext()) {
                    ShopCartItemVO shopCartItemDto = iterator.next();
                    // 判断下是否为预售商品,如果是预售商品就拆单
                    if (Objects.isNull(shopCartItemDto.getPreSaleType()) || Objects.equals(shopCartItemDto.getPreSaleType(), -1)) {
                        // 普通的商品放入同一个list
                        normalShopCartItemList.add(shopCartItemDto);
                        continue;
                    }

                    ShopCartOrderVO shopCartOrderVO = getPreSaleShopCartOrder(userId, shopCartOrder, shopCartItemDto);
                    shopCartOrderMap.put(shopCartItemDto.getSkuId(), shopCartOrderVO);
                    // 移除该订单项
                    iterator.remove();
                }
            }
            // 重新算一下预售商品
            if (CollectionUtil.isNotEmpty(shopCartOrderMap)) {
                for (Long skuId : shopCartOrderMap.keySet()) {
                    // 运费放进去
                    ShopTransFeeVO shopTransFeeVO = preSaleTransFeeMap.get(skuId);
                    // 店铺订单计算
                    ShopCartOrderVO shopCartOrderVO = shopCartOrderMap.get(skuId);
                    // 如果有等级免运费金额，则所有都免运费
                    shopCartOrderVO.setTransfee(Objects.isNull(shopTransFeeVO) ? 0L : shopTransFeeVO.getTransfee());
                    shopCartOrderVO.setLevelFreeTransfee(Math.min(levelFreeTransfee, shopCartOrderVO.getTransfee()));
                    shopCartOrderVO.setHasComboOrder(shopCartOrder.getHasComboOrder());
                    loadShopCartOrderDto(shopCartOrderVO);
                    shopCartOrders.add(shopCartOrderVO);
                    transFee = transFee - shopCartOrderVO.getTransfee();
                }
            }
            // 普通商品和商家仓库发货的供应商商品做一个order
            if (CollectionUtil.isNotEmpty(normalShopCartItemList)) {
                ShopCartItemDiscountVO shopCartItemDiscount = new ShopCartItemDiscountVO();
                shopCartItemDiscount.setShopCartItems(normalShopCartItemList);
                shopCartOrder.setShopCartItemDiscounts(Collections.singletonList(shopCartItemDiscount));
                shopCartOrder.setTransfee(transFee);
                shopCartOrder.setLevelFreeTransfee(Math.min(levelFreeTransfee, shopCartOrder.getTransfee()));
                loadShopCartOrderDto(shopCartOrder);
                normalShopCartOrderList.add(shopCartOrder);
            }
        }
        mergerOrder.setShopCartOrders(new ArrayList<>(Constant.INITIAL_CAPACITY));
        if (CollectionUtil.isNotEmpty(normalShopCartOrderList)) {
            mergerOrder.setShopCartOrders(normalShopCartOrderList);
        }
        if (CollUtil.isNotEmpty(shopCartOrders)) {
            mergerOrder.getShopCartOrders().addAll(shopCartOrders);
        }
    }

    private void splitShopCartOrderDtoByVirtual(ShopCartOrderMergerVO mergerOrder, Long userId) {
        List<ShopCartOrderVO> shopCartOrders = new ArrayList<>(Constant.INITIAL_CAPACITY);
        List<ShopCartOrderVO> normalShopCartOrderList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        OrderType orderType = mergerOrder.getOrderType();
        for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
            // 注意一下等级免运费金额，因为一个店如果免运费，则肯定所以项都免运费了
            long levelFreeTransfee = Objects.isNull(shopCartOrder.getLevelFreeTransfee()) ? 0L : shopCartOrder.getLevelFreeTransfee();
            Iterator<ShopCartItemDiscountVO> shopCartIterator = shopCartOrder.getShopCartItemDiscounts().iterator();
            long transFee = shopCartOrder.getTransfee();
            List<ShopCartOrderVO> virtualShopCartOrderList = new ArrayList<>();
            List<ShopCartItemVO> normalShopCartItemList = new ArrayList<>(Constant.INITIAL_CAPACITY);
            Long mainOrderId = null;
            int itemCount = shopCartOrder.getShopCartItemDiscounts().get(0).getShopCartItems().size();
            // 如果当前店铺的商品数量为1,则不需要拆单直接跳过
            if(itemCount == 1 && shopCartOrder.getShopCartItemDiscounts().size() == 1){
                continue;
            }
            while (shopCartIterator.hasNext()) {
                ShopCartItemDiscountVO shopCartItemDiscountDto = shopCartIterator.next();
                Iterator<ShopCartItemVO> iterator = shopCartItemDiscountDto.getShopCartItems().iterator();
                while (iterator.hasNext()) {
                    ShopCartItemVO shopCartItemDto = iterator.next();
                    // 普通虚拟商品直接拆分即可
                    if (Objects.equals(shopCartItemDto.getMold(), SpuMold.VIRTUAL.value())) {
                        ShopCartOrderVO shopCartOrderVO = getPreSaleShopCartOrder(userId, shopCartOrder, shopCartItemDto);
                        shopCartOrderVO.setMainOrderId(0L);
                        shopCartOrderVO.setSpuMold(1);
                        virtualShopCartOrderList.add(shopCartOrderVO);
                        // 移除该订单项
                        iterator.remove();
                    }
                }
            }
            // 重新算一下商品
            if (CollectionUtil.isNotEmpty(virtualShopCartOrderList)) {
                for (ShopCartOrderVO shopCartOrderVO : virtualShopCartOrderList) {
                    // 店铺订单计算
                    // 能被拆分的都是虚拟商品,运费都为0
                    shopCartOrderVO.setTransfee(0L);
                    shopCartOrderVO.setLevelFreeTransfee(0L);
                    shopCartOrderVO.setHasComboOrder(shopCartOrder.getHasComboOrder());
                    shopCartOrderVO.setMainOrderId(Objects.isNull(shopCartOrderVO.getMainOrderId()) ? mainOrderId : shopCartOrder.getMainOrderId());
                    loadShopCartOrderDto(shopCartOrderVO);
                    shopCartOrders.add(shopCartOrderVO);
                }
            }
            shopCartOrder.setSpuMold(0);
            loadShopCartOrderDto(shopCartOrder);
        }
        if (CollUtil.isNotEmpty(shopCartOrders)) {
            mergerOrder.getShopCartOrders().addAll(shopCartOrders);
        }
    }


    private ShopCartOrderVO getPreSaleShopCartOrder(Long userId, ShopCartOrderVO shopCartOrder, ShopCartItemVO shopCartItemDto) {
        ShopCartOrderVO shopCartOrderVO = new ShopCartOrderVO();
        // 拆分预售商品
        shopCartOrderVO.setShopId(shopCartOrder.getShopId());
        shopCartOrderVO.setShopName(shopCartOrder.getShopName());
        shopCartOrderVO.setRemarks(shopCartOrder.getRemarks());
        shopCartOrderVO.setOrderType(shopCartOrder.getOrderType());
        shopCartOrderVO.setShopCartItemDiscounts(new ArrayList<>(Constant.INITIAL_CAPACITY));
        shopCartOrderVO.setSupplierId(shopCartOrder.getSupplierId());
        shopCartOrderVO.setSupplierDeliveryType(shopCartOrder.getSupplierDeliveryType());
        ShopCartItemDiscountVO shopCartItemDiscount = new ShopCartItemDiscountVO();
        shopCartItemDiscount.setShopCartItems(Collections.singletonList(shopCartItemDto));
        shopCartOrderVO.getShopCartItemDiscounts().add(shopCartItemDiscount);
        return shopCartOrderVO;
    }

    private void loadShopCartOrderDto(ShopCartOrderVO shopCartOrderVO) {
        if (Objects.isNull(shopCartOrderVO.getLevelFreeTransfee())) {
            shopCartOrderVO.setLevelFreeTransfee(0L);
        }
        if (Objects.isNull(shopCartOrderVO.getTransfee())) {
            shopCartOrderVO.setTransfee(0L);
        }
        shopCartOrderVO.setUseScore(0L);
        shopCartOrderVO.setActualTotal(shopCartOrderVO.getTransfee() - shopCartOrderVO.getLevelFreeTransfee());
        shopCartOrderVO.setTotal(0L);
        shopCartOrderVO.setTotalCount(0);
        shopCartOrderVO.setDiscountReduce(0L);
        shopCartOrderVO.setCouponReduce(0L);
        shopCartOrderVO.setPlatformCouponReduce(0L);
        shopCartOrderVO.setScoreReduce(0L);
        shopCartOrderVO.setPlatformAmount(shopCartOrderVO.getLevelFreeTransfee());
        shopCartOrderVO.setLevelReduce(0L);
        shopCartOrderVO.setShopReduce(shopCartOrderVO.getPlatformAmount());
        shopCartOrderVO.setPlatformCommission(0L);
        shopCartOrderVO.setTotalPurchasePlatformCommission(0L);
        List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCartOrderVO.getShopCartItemDiscounts();
        for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
            for (ShopCartItemVO cartItemDto : shopCartItemDiscount.getShopCartItems()) {
                // 订单项的金额在生成订单时已经算好了，这里只需要相加即可，不需要别的处理
                shopCartOrderVO.setActualTotal(shopCartOrderVO.getActualTotal() + cartItemDto.getActualTotal());
                shopCartOrderVO.setTotal(shopCartOrderVO.getTotal() + cartItemDto.getTotalAmount());
                shopCartOrderVO.setTotalCount(shopCartOrderVO.getTotalCount() + cartItemDto.getCount());
                shopCartOrderVO.setShopReduce(shopCartOrderVO.getShopReduce() + cartItemDto.getShareReduce());
                /// comboAmount与shareReduce金额一样，导致套餐计算优惠翻倍
//                if (Objects.nonNull(cartItemDto.getComboAmount())) {
//                    //加上套餐优惠金额
//                    shopCartOrderVO.setShopReduce(shopCartOrderVO.getShopReduce() + cartItemDto.getComboAmount());
//                }
                cartItemDto.setPlatformCommission(Objects.isNull(cartItemDto.getPlatformCommission()) ? 0L : cartItemDto.getPlatformCommission());
                shopCartOrderVO.setPlatformCommission(shopCartOrderVO.getPlatformCommission() + cartItemDto.getPlatformCommission());
                shopCartOrderVO.setSupplierId(cartItemDto.getSupplierId());
                shopCartOrderVO.setSupplierDeliveryType(cartItemDto.getSupplierDeliveryType());
                shopCartOrderVO.setPreSaleType(cartItemDto.getPreSaleType());
                if (Objects.nonNull(cartItemDto.getPurchasePlatformCommission())) {
                    shopCartOrderVO.setTotalPurchasePlatformCommission(shopCartOrderVO.getTotalPurchasePlatformCommission() + cartItemDto.getPurchasePlatformCommission());
                }
                if (Objects.nonNull(cartItemDto.getDiscountAmount())) {
                    shopCartOrderVO.setDiscountReduce(shopCartOrderVO.getDiscountReduce() + cartItemDto.getDiscountAmount());
                }
                if (Objects.nonNull(cartItemDto.getShopCouponAmount())) {
                    shopCartOrderVO.setCouponReduce(shopCartOrderVO.getCouponReduce() + cartItemDto.getShopCouponAmount());
                }
                if (Objects.nonNull(cartItemDto.getPlatformCouponAmount())) {
                    shopCartOrderVO.setPlatformCouponReduce(shopCartOrderVO.getPlatformCouponReduce() + cartItemDto.getPlatformCouponAmount());
                }
                if (Objects.nonNull(cartItemDto.getScoreReduce())) {
                    shopCartOrderVO.setScoreReduce(shopCartOrderVO.getScoreReduce() + cartItemDto.getScoreReduce());
                }
                if (Objects.nonNull(cartItemDto.getPlatformShareReduce())) {
                    shopCartOrderVO.setPlatformAmount(shopCartOrderVO.getPlatformAmount() + cartItemDto.getPlatformShareReduce());
                }
                if (Objects.nonNull(cartItemDto.getLevelReduce())) {
                    shopCartOrderVO.setLevelReduce(shopCartOrderVO.getLevelReduce() + cartItemDto.getLevelReduce());
                }
                if (Objects.nonNull(cartItemDto.getScorePrice())) {
                    shopCartOrderVO.setUseScore(shopCartOrderVO.getUseScore() + cartItemDto.getScorePrice());
                }
            }
        }
    }

    public void tryLockStock(ShopCartOrderMergerVO mergerOrder) {

        Map<String, StockBillLogItemDTO> stockBillLogItemMap = new HashMap<>(Constant.INITIAL_CAPACITY);

        for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
            List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
                // 加载库存日志信息
                this.loadStockBillLogItem(stockBillLogItemMap, shopCartOrder, shopCartItemDiscount);
            }
        }

        // 库存日志列表
        List<StockBillLogItemDTO> stockBillLogItems = new ArrayList<>(stockBillLogItemMap.values());

        logger.info("tryLockStock stockBillLogItems:{}", stockBillLogItems);
        // 锁定库存
        ServerResponseEntity<?> lockStockResponse = skuStockChangeFeignClient.lock(stockBillLogItems);
//         提示具体哪个商品库存不足
        if (Objects.equals(ResponseEnum.NOT_STOCK.value(), lockStockResponse.getCode())) {
            for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
                List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
                for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
                    List<ShopCartItemVO> shopCartItems = shopCartItemDiscount.getShopCartItems();
                    for (ShopCartItemVO orderItem : shopCartItems) {
                        boolean flag = Objects.nonNull(orderItem.getSupplierSkuId()) && Objects.equals(orderItem.getSupplierSkuId().toString(),
                                lockStockResponse.getData().toString());
                        if(Objects.equals(orderItem.getMold(),SpuMold.COMBO.value())){
                            for (ShopCartItemVO comboShopCartItem : orderItem.getComboShopCartItems()) {
                                if (Objects.equals(comboShopCartItem.getSkuId().toString(), lockStockResponse.getData().toString()) || flag) {
                                    OrderLangUtil.shopCartItemLang(orderItem);
                                    String skuName = Objects.isNull(orderItem.getSkuName()) ? "" : orderItem.getSkuName();
                                    throw new LuckException(orderItem.getSpuName() + " " + skuName + " 库存不足");
                                }
                            }
                            continue;
                        }
                        if (Objects.equals(orderItem.getSkuId().toString(), lockStockResponse.getData().toString()) || flag) {
                            OrderLangUtil.shopCartItemLang(orderItem);
                            String skuName = Objects.isNull(orderItem.getSkuName()) ? "" : orderItem.getSkuName();
                            throw new LuckException(orderItem.getSpuName() + " " + skuName + " 库存不足");
                        }

                    }
                }
            }
        }
        if (!lockStockResponse.isSuccess()) {
            throw new LuckException(lockStockResponse);
        }
    }

    private void loadStockBillLogItem(Map<String, StockBillLogItemDTO> stockBillLogItemMap, ShopCartOrderVO shopCartOrder, ShopCartItemDiscountVO shopCartItemDiscount) {
        List<ShopCartItemVO> shopCartItems = shopCartItemDiscount.getShopCartItems();
        for (ShopCartItemVO orderItem : shopCartItems) {
            if(Objects.equals(orderItem.getMold(),SpuMold.COMBO.value())){
                for (ShopCartItemVO comboShopCartItem : orderItem.getComboShopCartItems()) {
                    handleSotckBillLog(stockBillLogItemMap, shopCartOrder, comboShopCartItem);
                }
            }else {
                handleSotckBillLog(stockBillLogItemMap, shopCartOrder, orderItem);
            }


            //处理赠品订单项
            if (CollUtil.isEmpty(orderItem.getGiveawayShopCartItemList())) {
                continue;
            }
            // 赠品库存计算
            for (ShopCartItemVO giveawayShopCartItem : orderItem.getGiveawayShopCartItemList()) {

                String giveawaySkuPointKey = giveawayShopCartItem.getSkuId() + Constant.UNDERLINE + giveawayShopCartItem.getStockPointId();
                StockBillLogItemDTO giveawayStockBillLogItem;
                if (!stockBillLogItemMap.containsKey(giveawaySkuPointKey)) {
                    giveawayStockBillLogItem = new StockBillLogItemDTO(
                            giveawayShopCartItem.getSpuId(),
                            giveawayShopCartItem.getSkuId(),
                            giveawayShopCartItem.getShopId(),
                            shopCartOrder.getOrderId(),
                            giveawayShopCartItem.getSpuName(),
                            giveawayShopCartItem.getSkuName(),
                            0,
                            giveawayShopCartItem.getSkuPriceFee(),
                            giveawayShopCartItem.getPartyCode(),
                            giveawayShopCartItem.getImgUrl()
                    );
                    giveawayStockBillLogItem.setStockPointId(giveawayShopCartItem.getStockPointId());
                    stockBillLogItemMap.put(giveawaySkuPointKey, giveawayStockBillLogItem);
                } else {
                    giveawayStockBillLogItem = stockBillLogItemMap.get(giveawaySkuPointKey);
                }
                giveawayStockBillLogItem.setStockCount(giveawayStockBillLogItem.getStockCount() + giveawayShopCartItem.getCount());
            }
        }
    }

    private static void handleSotckBillLog(Map<String, StockBillLogItemDTO> stockBillLogItemMap, ShopCartOrderVO shopCartOrder, ShopCartItemVO orderItem) {
        String skuPointKey = orderItem.getSkuId() + Constant.UNDERLINE + orderItem.getStockPointId();
        StockBillLogItemDTO stockBillLogItem = stockBillLogItemMap.get(skuPointKey);
        if (Objects.isNull(stockBillLogItem)) {
            stockBillLogItem = new StockBillLogItemDTO(
                    orderItem.getSpuId(),
                    orderItem.getSkuId(),
                    shopCartOrder.getShopId(),
                    shopCartOrder.getOrderId(),
                    orderItem.getSpuName(),
                    orderItem.getSkuName(),
                    0,
                    orderItem.getSkuPriceFee(),
                    orderItem.getPartyCode(),
                    orderItem.getImgUrl()
            );
            stockBillLogItemMap.put(skuPointKey, stockBillLogItem);
        }
        stockBillLogItem.setStockPointId(orderItem.getStockPointId());
        stockBillLogItem.setStockPointType(orderItem.getStockPointType());
        stockBillLogItem.setStockCount(stockBillLogItem.getStockCount() + orderItem.getCount());
        stockBillLogItem.setSupplierId(orderItem.getSupplierId());
        stockBillLogItem.setSupplierDeliveryType(orderItem.getSupplierDeliveryType());

        // 如果是供应商商品且发货方式为供应商发货，则将spuId和skuId替换成供应商商品的
        // 只替换id，商品名称图片等信息则保留商家的商品信息，库存记录是商家的库存记录
        if (!Objects.equals(orderItem.getSupplierId(), 0L) && Objects.equals(orderItem.getSupplierDeliveryType(), 1)) {
            stockBillLogItem.setSpuId(orderItem.getSupplierSpuId());
            stockBillLogItem.setSkuId(orderItem.getSupplierSkuId());
        }
    }

    public void tryLockCoupon(ShopCartOrderMergerVO mergerOrder) {
        if (!Objects.equals(mergerOrder.getOrderType(), OrderType.ORDINARY)) {
            logger.info("提交普通订单，锁定优惠券");
            return;
        }
        List<LockCouponDTO> lockCouponParams;
        List<Long> orderIds = new ArrayList<>(Constant.INITIAL_CAPACITY);
        // 如果不为空表示拆分过订单
        if (CollectionUtil.isEmpty(mergerOrder.getShopCoupons())) {
            List<ShopCartOrderVO> shopCartOrders = mergerOrder.getShopCartOrders();
            for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
                Long orderId = shopCartOrder.getOrderId();
                List<CouponOrderVO> coupons = shopCartOrder.getCoupons();
                if (CollectionUtil.isNotEmpty(coupons)) {
                    for (CouponOrderVO coupon : coupons) {
                        if (Objects.equals(Boolean.TRUE, coupon.getChoose())) {
                            coupon.setOrderId(orderId);
                        }
                    }
                }
                orderIds.add(orderId);
            }
            // 锁优惠券
            lockCouponParams = getLockCouponDto(mergerOrder, orderIds);
        } else {
            for (CouponOrderVO shopCoupon : mergerOrder.getShopCoupons()) {
                orderIds.addAll(shopCoupon.getOrderIds());
            }
            // 锁定优惠券
            // 平台优惠券
            lockCouponParams = new ArrayList<>(Constant.INITIAL_CAPACITY);
            LockCouponDTO platformLockCouponParam = getLockCouponWhichSplit(mergerOrder.getCoupons());
            if (platformLockCouponParam != null) {
                // 平台优惠券涉及多个订单，所以设置订单id为多个订单id以逗号分割
                platformLockCouponParam.setOrderIds(StrUtil.join(StrUtil.COMMA, orderIds));
                lockCouponParams.add(platformLockCouponParam);
            }
            // 店铺优惠券
            LockCouponDTO shopLockCouponParam = getLockCouponWhichSplit(mergerOrder.getShopCoupons());
            if (shopLockCouponParam != null) {
                lockCouponParams.add(shopLockCouponParam);
            }
        }
        if (CollectionUtil.isEmpty(lockCouponParams)) {
            return;
        }
        ServerResponseEntity<Void> lockCouponResponse = couponOrderFeignClient.lockCoupon(lockCouponParams);
        if (!lockCouponResponse.isSuccess()) {
            throw new LuckException(lockCouponResponse.getMsg());
        }
    }

    /**
     * 尝试锁定优惠券
     *
     * @param mergerOrder
     * @param orderIds
     */
    private List<LockCouponDTO> getLockCouponDto(ShopCartOrderMergerVO mergerOrder, List<Long> orderIds) {
        // 锁定优惠券
        // 平台优惠券
        List<LockCouponDTO> lockCouponParams = new ArrayList<>(Constant.INITIAL_CAPACITY);
        LockCouponDTO platformLockCouponParam = getLockCouponWhichSplit(mergerOrder.getCoupons());
        if (platformLockCouponParam != null) {
            // 平台优惠券涉及多个订单，所以设置订单id为多个订单id以逗号分割
            platformLockCouponParam.setOrderIds(StrUtil.join(StrUtil.COMMA, orderIds));
            lockCouponParams.add(platformLockCouponParam);
        }
        // 店铺优惠券
        for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
            LockCouponDTO shopLockCouponParam = getLockCouponWhichSplit(shopCartOrder.getCoupons());
            if (shopLockCouponParam != null) {
                lockCouponParams.add(shopLockCouponParam);
            }
        }

        return lockCouponParams;
    }

    private LockCouponDTO getLockCouponWhichSplit(List<CouponOrderVO> couponOrders) {
        if (CollectionUtil.isEmpty(couponOrders)) {
            return null;
        }
        for (CouponOrderVO couponOrder : couponOrders) {
            if ((Objects.equals(Boolean.TRUE, couponOrder.getChoose())) && couponOrder.getCanUse()) {
                LockCouponDTO param = new LockCouponDTO();
                if (Objects.nonNull(couponOrder.getOrderId())) {
                    param.setOrderIds(String.valueOf(couponOrder.getOrderId()));
                } else {
                    param.setOrderIds(StrUtil.join(StrUtil.COMMA, couponOrder.getOrderIds()));
                }
                param.setCouponId(couponOrder.getCouponId());
                param.setCouponUserId(couponOrder.getCouponUserId());
                param.setReduceAmount(couponOrder.getReduceAmount());
                return param;
            }
        }
        return null;
    }

    public void tryLockScore(ShopCartOrderMergerVO mergerOrder) {
        // 如果没有使用积分，就不用锁定积分啦
        if (Objects.isNull(mergerOrder.getUsableScore()) || Objects.equals(mergerOrder.getUsableScore(), 0L)) {
            logger.info("没有使用积分，不用锁定积分");
            return;
        }
        List<ShopCartOrderVO> shopCartOrders = mergerOrder.getShopCartOrders();
        List<UserScoreLockDTO> userScoreLocks = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
            if (Objects.equals(shopCartOrder.getUseScore(), 0L)) {
                continue;
            }
            userScoreLocks.add(new UserScoreLockDTO(shopCartOrder.getOrderId(), shopCartOrder.getUseScore(), mergerOrder.getOrderType().value()));
        }

        // 锁定积分
        ServerResponseEntity<Void> scoreResp = userScoreLockFeignClient.lock(userScoreLocks);
        if (!scoreResp.isSuccess()) {
            logger.info("锁定积分失败，失败原因：{}", scoreResp.getMsg());
            throw new LuckException(scoreResp.getMsg());
        }

    }
//
//    private void checkSpuStatus(List<ShopCartOrderVO> shopCartOrders) {
//        List<Long> spuIds = new ArrayList<>(Constant.INITIAL_CAPACITY);
//        for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
//            List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
//            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
//                List<ShopCartItemVO> shopCartItems = shopCartItemDiscount.getShopCartItems();
//                for (ShopCartItemVO orderItem : shopCartItems) {
//                    spuIds.add(orderItem.getSpuId());
//                }
//            }
//        }
//        if (CollUtil.isNotEmpty(spuIds)) {
//            ServerResponseEntity<?> skuStatusResponseEntity = searchSpuFeignClient.checkSpuStatus(spuIds);
//            if (Objects.equals(skuStatusResponseEntity.getCode(), ResponseEnum.SPU_STATUS_ERROR.value())) {
//                for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
//                    List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
//                    for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
//                        List<ShopCartItemVO> shopCartItems = shopCartItemDiscount.getShopCartItems();
//                        for (ShopCartItemVO orderItem : shopCartItems) {
//                            if (Objects.equals(orderItem.getSpuId().toString(), skuStatusResponseEntity.getData().toString())) {
//                                OrderLangUtil.shopCartItemLang(orderItem);
//                                String skuName = Objects.isNull(orderItem.getSkuName()) ? "" : orderItem.getSkuName();
//                                throw new LuckException(orderItem.getSpuName() + " " + skuName + " 不在正常状态");
//                            }
//                        }
//                    }
//                }
//            }
//            if (!skuStatusResponseEntity.isSuccess()) {
//                throw new LuckException(skuStatusResponseEntity);
//            }
//        }
//    }

    private void handleGroupAndSeckillOrderSupplier(ShopCartOrderMergerVO mergerOrder){
        if (Objects.equals(mergerOrder.getOrderType().value(), OrderType.GROUP.value()) ||
                Objects.equals(mergerOrder.getOrderType().value(), OrderType.SECKILL.value())) {
            logger.info("团购订单或秒杀订单，处理供应商信息");
            mergerOrder.getShopCartOrders().forEach(shopCartOrderVO -> {
                shopCartOrderVO.getShopCartItemDiscounts().forEach(shopCartItemDiscountVO -> {
                    shopCartItemDiscountVO.getShopCartItems().forEach(shopCartItemVO -> {
                        shopCartOrderVO.setSupplierDeliveryType(shopCartItemVO.getSupplierDeliveryType());
                        shopCartOrderVO.setSupplierId(shopCartItemVO.getSupplierId());
                    });
                });
            });
        }
    }
}
