
package com.tmerclub.cloud.order.controller.app;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.auth.bo.UidInfoBO;
import com.tmerclub.cloud.api.coupon.dto.PlatformChooseCouponDTO;
import com.tmerclub.cloud.api.coupon.feign.CouponOrderFeignClient;
import com.tmerclub.cloud.api.delivery.dto.CalculateAndGetDeliverInfoDTO;
import com.tmerclub.cloud.api.product.feign.WarehouseFeignClient;
import com.tmerclub.cloud.api.feign.MarketingFeignClient;
import com.tmerclub.cloud.api.order.manager.ConfirmOrderManager;
import com.tmerclub.cloud.api.order.manager.SubmitOrderManager;
import com.tmerclub.cloud.api.product.manager.ShopCartAdapter;
import com.tmerclub.cloud.api.product.manager.ShopCartItemAdapter;
import com.tmerclub.cloud.api.seckill.feign.SeckillFeignClient;
import com.tmerclub.cloud.api.user.dto.ShopCustomerReqDTO;
import com.tmerclub.cloud.api.user.feign.ShopCustomerFeignClient;
import com.tmerclub.cloud.api.user.feign.UserLevelAndScoreOrderFeignClient;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.leaf.manager.SegmentManager;
import com.tmerclub.cloud.common.order.constant.DeliveryType;
import com.tmerclub.cloud.common.order.constant.OrderType;
import com.tmerclub.cloud.common.order.dto.OrderDTO;
import com.tmerclub.cloud.common.order.dto.SubmitOrderDTO;
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.SpuMold;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.constant.DistributedIdKey;
import com.tmerclub.cloud.delivery.manager.DeliveryManager;
import com.tmerclub.cloud.order.bo.SubmitOrderPayAmountInfoBO;
import com.tmerclub.cloud.order.model.OrderAddr;
import com.tmerclub.cloud.order.service.OrderAddrService;
import com.tmerclub.cloud.order.service.OrderItemService;
import com.tmerclub.cloud.order.service.OrderService;
import com.tmerclub.cloud.order.vo.SubmitOrderPayInfoVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * 订单信息
 *
 * @author tmerclub
 * @date 2020-12-05 14:13:50
 */
@RestController("appOrderController")
@RequestMapping("/order")
@Tag(name = "app-订单信息")
public class OrderController {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShopCartAdapter shopCartAdapter;
    @Autowired
    private ConfirmOrderManager confirmOrderManager;
    @Autowired
    private ShopCartItemAdapter shopCartItemAdapter;
    @Autowired
    private ThreadPoolExecutor orderThreadPoolExecutor;
    @Autowired
    private DeliveryManager deliveryManager;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private OrderAddrService orderAddrService;
    @Autowired
    private SubmitOrderManager submitOrderManager;
    @Autowired
    private RocketMQTemplate orderCancelTemplate;
    @Autowired
    private SegmentManager segmentManager;
    @DubboReference
    private WarehouseFeignClient warehouseFeignClient;
    @DubboReference
    private MarketingFeignClient marketingFeignClient;
    @DubboReference
    private SeckillFeignClient seckillFeignClient;
    @DubboReference
    private CouponOrderFeignClient couponOrderFeignClient;
    @DubboReference
    private UserLevelAndScoreOrderFeignClient userLevelAndScoreOrderFeignClient;
    @DubboReference
    private ShopCustomerFeignClient shopCustomerFeignClient;


    /**
     * 生成订单
     */
    @PostMapping("/confirm")
    @Operation(summary = "结算，生成订单信息", description = "传入下单所需要的参数进行下单")
    public ServerResponseEntity<ShopCartOrderMergerVO> confirm(@Valid @RequestBody OrderDTO orderParam) throws ExecutionException, InterruptedException {
        UidInfoBO uidInfoBO = AuthUserContext.get();
        Long userId = uidInfoBO.getUserId();
        // 将要返回给前端的完整的订单信息
        ShopCartOrderMergerVO shopCartOrderMerger = getShopCartOrderMergerVO(orderParam);
        shopCartOrderMerger.setUserId(userId);
        List<ShopCartItemVO> shopCartItemsDb = shopCartItemAdapter.getShopCartItems(orderParam.getShopCartItem(), userId, orderParam.getAddrId(), orderParam.getDvyTypes());
        // 获取用户地址信息
        UserDeliveryInfoVO userDeliveryInfoVO = deliveryManager.getUserDeliveryInfoVO(shopCartItemsDb, userId, orderParam);
        // 筛选过滤掉不同配送的商品
        List<ShopCartItemVO> shopCartItems = confirmOrderManager.filterShopItemsByType(shopCartOrderMerger, userDeliveryInfoVO, shopCartItemsDb);
        // 自提订单处理
        deliveryManager.handleStationOrder(shopCartOrderMerger, shopCartItems, userDeliveryInfoVO);

        setMold(shopCartOrderMerger, shopCartItemsDb);

        setPreSaleType(shopCartOrderMerger, shopCartItems);

        OrderLangUtil.shopCartItemList(shopCartItems);

        // 购物车
        List<ShopCartVO> shopCarts = shopCartAdapter.conversionShopCart(shopCartItems);

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 异步计算运费，运费暂时和优惠券没啥关联，可以与优惠券异步计算，获取用户地址，自提信息
        CompletableFuture<ServerResponseEntity<UserDeliveryInfoVO>> deliveryFuture = CompletableFuture.supplyAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 多线程手动设置下用户信息
            AuthUserContext.set(uidInfoBO);
            return deliveryManager.calculateAndGetDeliverInfo(new CalculateAndGetDeliverInfoDTO(shopCartItemsDb, userDeliveryInfoVO));
        }, orderThreadPoolExecutor);

        // 计算满减、套餐、优惠券，重新组合购物车，并返回优惠券信息 (满减是从购物车的时候就已经计算好了，提交订单理所当然应该用相同的方法)
        shopCarts = marketingFeignClient.calculateMarketingAndMakeUpShopCart(shopCarts, orderParam.getCouponIds(), orderParam.getUserChangeCoupon());

        // 运费用异步计算，最后要等运费出结果
        ServerResponseEntity<UserDeliveryInfoVO> userDeliveryInfoResponseEntity = deliveryFuture.get();
        if (!userDeliveryInfoResponseEntity.isSuccess()) {
            LOGGER.info("运费计算失败，失败原因：{}", userDeliveryInfoResponseEntity.getMsg());
            return ServerResponseEntity.transform(userDeliveryInfoResponseEntity);
        }
        // 等活动处理完之后，再插入sku的库存区域id -- 赠品、套餐和组合商品需要在marketing模块中处理
        confirmOrderManager.handleShopCartStockPoint(userDeliveryInfoVO, shopCarts, shopCartItemsDb, shopCartOrderMerger.getSpuMold());

        // 当算完一遍店铺的各种满减活动时，重算一遍订单金额
        confirmOrderManager.recalculateAmountWhenFinishingCalculateShop(shopCartOrderMerger, shopCarts, userDeliveryInfoResponseEntity.getData());
        long orderShopReduce = shopCartOrderMerger.getOrderReduce();

        // ===============================================开始平台优惠的计算==================================================
        // 计算平台优惠券，并返回平台优惠券信息
        ServerResponseEntity<ShopCartOrderMergerVO> couponOrderMergerResponseEntity = couponOrderFeignClient.choosePlatformCoupon(new PlatformChooseCouponDTO(orderParam.getUserChangeCoupon(), orderParam.getCouponIds(), shopCartOrderMerger));

        if (!couponOrderMergerResponseEntity.isSuccess()) {
            return ServerResponseEntity.transform(couponOrderMergerResponseEntity);
        }

        shopCartOrderMerger = couponOrderMergerResponseEntity.getData();
        ServerResponseEntity<ShopCartOrderMergerVO> calculateLevelDiscountResponseEntity = userLevelAndScoreOrderFeignClient.calculateLevelAndScoreDiscount(shopCartOrderMerger);
        if (!calculateLevelDiscountResponseEntity.isSuccess()) {
            LOGGER.info("计算会员等级优惠失败，失败原因：{}", calculateLevelDiscountResponseEntity.getMsg());
            return ServerResponseEntity.transform(calculateLevelDiscountResponseEntity);
        }
        shopCartOrderMerger = calculateLevelDiscountResponseEntity.getData();


        // ===============================================结束平台优惠的计算==================================================

        // 结束平台优惠的计算之后，还要重算一遍金额
        confirmOrderManager.recalculateAmountWhenFinishingCalculatePlatform(shopCartOrderMerger, userDeliveryInfoResponseEntity.getData());

        // 重新插入spu、sku
        resetSpu(shopCartOrderMerger, shopCartItems);
        shopCartOrderMerger.setOrderShopReduce(orderShopReduce);
        // 计算平台佣金-跟订单其他金额是独立的，可以单独计算
        confirmOrderManager.confirmPlatformCommission(shopCartOrderMerger);
//        // 如果下单项有组合商品,在组合一下返回给前端
//        confirmOrderManager.assembleComboShopCart(shopCartOrderMerger, shopCartItemsDb);
        // 缓存计算新
        confirmOrderManager.cacheCalculatedInfo(userId, shopCartOrderMerger);

        // 无法配送的商品添加商品详细和店铺详细
        shopCartAdapter.setFilterShopItemsLong(shopCartOrderMerger);
        return ServerResponseEntity.success(shopCartOrderMerger);
    }


    /**
     * 购物车/立即购买  提交订单,根据店铺拆单
     */
    @PostMapping("/submit")
    @Operation(summary = "提交订单，返回支付流水号", description = "根据传入的参数判断是否为购物车提交订单，同时对购物车进行删除，用户开始进行支付")
    public ServerResponseEntity<List<Long>> submitOrders(@Valid @RequestBody SubmitOrderDTO submitOrderParam) {
        Long userId = AuthUserContext.get().getUserId();

        // 在这里面已经生成了订单id了
        ServerResponseEntity<ShopCartOrderMergerVO> checkResult = submitOrderManager.checkSubmitInfo(submitOrderParam, userId);
        if (!checkResult.isSuccess()) {
            LOGGER.info("提交订单失败，失败原因:{}", checkResult.getMsg());
            return ServerResponseEntity.transform(checkResult);
        }
        ShopCartOrderMergerVO mergerOrder = checkResult.getData();
        mergerOrder.setUserId(userId);

        List<ShopCartOrderVO> shopCartOrders = mergerOrder.getShopCartOrders();
        List<Long> orderIds = new ArrayList<>(mergerOrder.getShopCartOrders().size());
        Map<Long,Long> mainOrderIdMap = new HashMap<>(Constant.INITIAL_CAPACITY);

        // 优惠券列表
        Map<Long, CouponOrderVO> shopCouponMap = new HashMap<>();
        if (CollUtil.isNotEmpty(mergerOrder.getShopCoupons())) {
            for (CouponOrderVO shopCoupon : mergerOrder.getShopCoupons()) {
                shopCoupon.setOrderIds(new ArrayList<>());
                shopCouponMap.put(shopCoupon.getShopId(), shopCoupon);
            }
        }
        // 需要主单号的ids
        if(CollUtil.isNotEmpty(mergerOrder.getNeedMainOrderIds())){
            for (Long skuIds : mergerOrder.getNeedMainOrderIds()) {
                Long orderId = segmentManager.getSegmentIdWithDateTime(DistributedIdKey.tmerclub_ORDER, mergerOrder.getUserId());
                mainOrderIdMap.put(skuIds,orderId);
            }
        }
        // 判断套餐是否失效
        for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
            if(mainOrderIdMap.containsKey(shopCartOrder.getMainOrderId())){
                shopCartOrder.setMainOrderId(mainOrderIdMap.get(shopCartOrder.getMainOrderId()));
            }else{
                shopCartOrder.setMainOrderId(0L);
            }
            Long orderId = segmentManager.getSegmentIdWithDateTime(DistributedIdKey.tmerclub_ORDER, mergerOrder.getUserId());
            shopCartOrder.setOrderId(orderId);
            orderIds.add(orderId);
            // 使用了店铺优惠券，且优惠金额大于0，将订单id加入优惠券订单id列表中
            if (shopCouponMap.containsKey(shopCartOrder.getShopId()) && shopCartOrder.getCouponReduce() > 0) {
                CouponOrderVO couponOrderVO = shopCouponMap.get(shopCartOrder.getShopId());
                couponOrderVO.getOrderIds().add(orderId);
            }
            List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
            // TODO 套餐缓存更改
            this.checkComboActivity(shopCartItemDiscounts);
        }

        // 锁定库存
        submitOrderManager.tryLockStock(mergerOrder);

        // 锁定优惠券
        submitOrderManager.tryLockCoupon(mergerOrder);

        // 锁积分
        submitOrderManager.tryLockScore(mergerOrder);

        // 发送消息，如果三十分钟后没有支付，则取消订单
        SendStatus sendStatus = orderCancelTemplate.syncSend(RocketMqConstant.ORDER_CANCEL_TOPIC, new GenericMessage<>(orderIds), RocketMqConstant.TIMEOUT, RocketMqConstant.CANCEL_ORDER_DELAY_LEVEL).getSendStatus();
        if (!Objects.equals(sendStatus, SendStatus.SEND_OK)) {
            // 消息发不出去就抛异常
            throw new LuckException(ResponseEnum.EXCEPTION);
        }

        // 提交订单
        orderService.submit(mergerOrder);

        // 店铺客户
        this.saveShopCustomer(mergerOrder);
        return ServerResponseEntity.success(orderIds);
    }

    @GetMapping("/order_pay_info")
    @Operation(summary = "获取订单支付信息", description = "获取订单支付的商品/地址信息")
    @Parameter(name = "orderIds", description = "订单流水号", required = true)
    public ServerResponseEntity<SubmitOrderPayInfoVO> getOrderPayInfo(@RequestParam("orderIds") String orderIds) {
        long[] orderIdList = StrUtil.splitToLong(orderIds, ",");
        Long userId = AuthUserContext.get().getUserId();
        SubmitOrderPayInfoVO orderPayInfoParam = new SubmitOrderPayInfoVO();
        List<String> spuNameList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        //获取订单信息
        ServerResponseEntity<ShopCartOrderMergerVO> shopCartOrderMergerResp = seckillFeignClient.getSeckillOrderByRedis(orderIdList[0], userId);
        SubmitOrderPayAmountInfoBO submitOrderPayAmountInfo;
        if(Objects.nonNull(shopCartOrderMergerResp.getData())){
            if (!shopCartOrderMergerResp.isSuccess()) {
                throw new LuckException(shopCartOrderMergerResp.getMsg());
            }
            if (Objects.isNull(shopCartOrderMergerResp.getData())){
                LOGGER.error("订单不存在，订单号:{}", orderIds);
                return ServerResponseEntity.fail(ResponseEnum.ORDER_NOT_EXIST);
            }
            ShopCartOrderMergerVO shopCartOrderMerger = shopCartOrderMergerResp.getData();
            submitOrderPayAmountInfo = new SubmitOrderPayAmountInfoBO();
            submitOrderPayAmountInfo.setTotalScore(0L);
            submitOrderPayAmountInfo.setPreSaleType(shopCartOrderMerger.getPreSaleType());
            submitOrderPayAmountInfo.setTotalFee(shopCartOrderMerger.getActualTotal());
            submitOrderPayAmountInfo.setOrderType(shopCartOrderMerger.getOrderType().value());
            submitOrderPayAmountInfo.setCreateTime(shopCartOrderMerger.getCreateTime());
            submitOrderPayAmountInfo.setUserId(shopCartOrderMerger.getUserId());
            // 地址
            if (Objects.nonNull(shopCartOrderMerger.getUserAddr())) {
                UserAddrVO orderAddr = shopCartOrderMerger.getUserAddr();
                //写入商品名、收货地址/电话
                String address = orderAddr.getProvince() + orderAddr.getCity() + orderAddr.getArea() + orderAddr.getAddr();
                orderPayInfoParam.setUserAddr(address);
                orderPayInfoParam.setConsignee(orderAddr.getConsignee());
                orderPayInfoParam.setMobile(orderAddr.getMobile());
            }
            // 获取商品名称
            String spuName = shopCartOrderMerger.getShopCartOrders().get(0).getShopCartItemDiscounts().get(0).getShopCartItems().get(0).getSpuName();
            spuNameList.add(spuName);
        }else{
            submitOrderPayAmountInfo = orderService.getSubmitOrderPayAmountInfo(orderIdList);
            spuNameList = orderItemService.getSpuNameListByOrderIds(orderIdList);
        }
        if(Objects.isNull(submitOrderPayAmountInfo.getCreateTime()) || !Objects.equals(userId, submitOrderPayAmountInfo.getUserId())) {
            LOGGER.error("订单不存在，订单号:{}", orderIds);
            return ServerResponseEntity.fail(ResponseEnum.ORDER_NOT_EXIST);
        }

        Date endTime = DateUtil.offsetMillisecond(submitOrderPayAmountInfo.getCreateTime(), RocketMqConstant.CANCEL_TIME_INTERVAL);

        orderPayInfoParam.setSpuNameList(spuNameList);
        orderPayInfoParam.setEndTime(endTime);
        orderPayInfoParam.setTotalFee(submitOrderPayAmountInfo.getTotalFee());
        orderPayInfoParam.setTotalScore(submitOrderPayAmountInfo.getTotalScore());
        orderPayInfoParam.setOrderScore(submitOrderPayAmountInfo.getOrderScore());
        orderPayInfoParam.setOrderType(submitOrderPayAmountInfo.getOrderType());
        // 如果是定金预售，判断下是支付尾款还是定金
        if (Objects.equals(submitOrderPayAmountInfo.getPreSaleType(), PreSaleType.DEPOSIT.value())) {
            if (Objects.equals(submitOrderPayAmountInfo.getPreSalePayStatus(), 0)) {
                orderPayInfoParam.setTotalFee(submitOrderPayAmountInfo.getDepositAmount());
            } else {
                orderPayInfoParam.setTotalFee(submitOrderPayAmountInfo.getBalanceAmount() + submitOrderPayAmountInfo.getFreightAmount() - submitOrderPayAmountInfo.getPlatformFreeFreightAmount());
                // 支付尾款的话，修改下剩余支付时间
                endTime = DateUtil.offsetMillisecond(submitOrderPayAmountInfo.getBalanceEndTime(), RocketMqConstant.CANCEL_TIME_INTERVAL);
                orderPayInfoParam.setEndTime(endTime);
                orderPayInfoParam.setPreSalePayStatus(submitOrderPayAmountInfo.getPreSalePayStatus());
                orderPayInfoParam.setBalanceStartTime(submitOrderPayAmountInfo.getBalanceStartTime());
            }
        }
        // 地址
        if (Objects.nonNull(submitOrderPayAmountInfo.getOrderAddrId())) {
            OrderAddr orderAddr = orderAddrService.getById(submitOrderPayAmountInfo.getOrderAddrId());
            LOGGER.info("订单地址信息:{}", orderAddr);
            if (Objects.nonNull(orderAddr)) {
                //写入商品名、收货地址/电话
                String addr = orderAddr.getProvince() + orderAddr.getCity() + orderAddr.getArea() + orderAddr.getAddr();
                orderPayInfoParam.setUserAddr(addr);
                orderPayInfoParam.setConsignee(orderAddr.getConsignee());
                orderPayInfoParam.setMobile(orderAddr.getMobile());
            }
        }
        return ServerResponseEntity.success(orderPayInfoParam);
    }

    private void saveShopCustomer(ShopCartOrderMergerVO mergerOrder) {
        mergerOrder.getShopCartOrders().get(0).setUserId(mergerOrder.getUserId());
        Set<Long> shopIdList = mergerOrder.getShopCartOrders().stream().map(ShopCartOrderVO::getShopId).collect(Collectors.toSet());
        List<ShopCustomerReqDTO> shopCustomerReqList = new ArrayList<>(shopIdList.size());
        for (Long shopId : shopIdList) {
            ShopCustomerReqDTO shopCustomerReqDTO = new ShopCustomerReqDTO();
            shopCustomerReqDTO.setUserId(mergerOrder.getUserId());
            shopCustomerReqDTO.setShopId(shopId);
            shopCustomerReqList.add(shopCustomerReqDTO);
        }
        shopCustomerFeignClient.saveBatchByOrders(shopCustomerReqList);
    }


    private static void setPreSaleType(ShopCartOrderMergerVO shopCartOrderMerger, List<ShopCartItemVO> shopCartItems) {
        // 该商品不满足任何的配送方式
        if (CollectionUtil.isEmpty(shopCartItems)) {
            LOGGER.info("该商品不满足任何的配送方式,并设置配送方式为-1");
            shopCartOrderMerger.setPreSaleType(-1);
        } else {
            // 判断下预售
            ShopCartItemVO firstShopCartItem = shopCartItems.get(0);
            // 是否为预售订单
            shopCartOrderMerger.setPreSaleType(firstShopCartItem.getPreSaleType());
            LOGGER.info("是否为预售订单:{}", shopCartOrderMerger.getPreSaleType());
        }
    }

    private static void resetSpu(ShopCartOrderMergerVO shopCartOrderMerger, List<ShopCartItemVO> shopCartItemsDb) {
        Map<Long, ShopCartItemVO> shopCartItemMap = shopCartItemsDb.stream().collect(Collectors.toMap(ShopCartItemVO::getSkuId, s -> s, (s1, s2) -> s1));
        for (ShopCartOrderVO shopCartOrder : shopCartOrderMerger.getShopCartOrders()) {
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartOrder.getShopCartItemDiscounts()) {
                for (ShopCartItemVO shopCartItem : shopCartItemDiscount.getShopCartItems()) {
                    ShopCartItemVO shopCartItemVO = shopCartItemMap.get(shopCartItem.getSkuId());
                    shopCartItem.setSkuLangList(shopCartItemVO.getSkuLangList());
                    shopCartItem.setSpuLangList(shopCartItemVO.getSpuLangList());
                }
            }
        }
    }

    private static void setMold(ShopCartOrderMergerVO shopCartOrderMerger, List<ShopCartItemVO> shopCartItemsDb) {
        // 商品类别 0.实物商品 1. 虚拟商品 2.组合商品
        int mold = 0;
        if (shopCartItemsDb.stream().filter(shopCartItemDto -> Objects.nonNull(shopCartItemDto.getMold()) && shopCartItemDto.getMold() == 1).count() == shopCartItemsDb.size()) {
            LOGGER.info("订单项中的所有商品都为虚拟商品时，才是虚拟订单,并设置配送方式为不配送");
            // 订单项中的所有商品都为虚拟商品时，才是虚拟订单
            mold = 1;
            shopCartOrderMerger.getDvyTypes().forEach(s -> s.setDvyType(DeliveryType.NOT_DELIVERY.value()));
        }
        shopCartOrderMerger.setSpuMold(mold);
        List<ShopCartItemVO> comboShopCartItems = shopCartItemsDb.stream().filter(shopCartItemDto -> Objects.nonNull(shopCartItemDto.getMold()) && Objects.equals(shopCartItemDto.getMold(), SpuMold.COMBO.value())).toList();
        if(mold == 1 || CollectionUtil.isEmpty(comboShopCartItems)){
            return;
        }
        // 如果有组合商品且为全虚拟的组合商品就为虚拟商品订单
        mold = 1;
        for (ShopCartItemVO comboShopCartItem : comboShopCartItems) {
            if(comboShopCartItem.getComboShopCartItems().stream().filter(shopCartItemDto -> Objects.nonNull(shopCartItemDto.getMold()) && shopCartItemDto.getMold() == 0).count() > 0){
                mold = 0;
                break;
            }
        }
        if(mold == 1){
            shopCartOrderMerger.getDvyTypes().forEach(s -> s.setDvyType(DeliveryType.NOT_DELIVERY.value()));
        }
        shopCartOrderMerger.setSpuMold(mold);
    }

    private static ShopCartOrderMergerVO getShopCartOrderMergerVO(OrderDTO orderParam) {
        ShopCartOrderMergerVO shopCartOrderMerger = new ShopCartOrderMergerVO();
        shopCartOrderMerger.setIsScorePay(orderParam.getIsScorePay());
        shopCartOrderMerger.setDvyTypes(orderParam.getDvyTypes());
        shopCartOrderMerger.setUsableScore(orderParam.getUserUseScore());
        shopCartOrderMerger.setOrderType(OrderType.ORDINARY);
        return shopCartOrderMerger;
    }


    private void checkComboActivity(List<ShopCartItemDiscountVO> shopCartItemDiscounts) {
        List<ShopCartItemDiscountVO> shopCartItemDiscountVOList = shopCartItemDiscounts.stream()
                .filter(shopCartItemDiscountVO -> Objects.nonNull(shopCartItemDiscountVO.getChooseComboItemVo())).toList();
        if (CollUtil.isEmpty(shopCartItemDiscountVOList)) {
            // 没有套餐活动
            return;
        }
        ServerResponseEntity serverResponseEntity = marketingFeignClient.checkComboActivity(shopCartItemDiscountVOList);
        if (!serverResponseEntity.isSuccess()) {
            throw new LuckException(serverResponseEntity.getMsg());
        }
    }

}
