/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title:
 * @Package cn.freemud.adapter
 * @Description:
 * @author: liming.guo
 * @date: 2018/5/21 20:34
 * @version V1.0
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
package cn.freemud.adapter;

import cn.freemud.base.constant.Version;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.calculate.CalculationSharingDiscountResponseDto;
import cn.freemud.entities.dto.order.CreateOrderDto;
import cn.freemud.entities.vo.CreateOrderVo;
import cn.freemud.entities.vo.PremiumExchangeResponseVo;
import cn.freemud.entities.vo.coupon.CartProduct;
import cn.freemud.entities.vo.coupon.CouponAvailableCartInfo;
import cn.freemud.enums.*;
import cn.freemud.utils.PropertyConvertUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
public class ActivityAdapter {

    /**
     * 扣减库存数量
      */
    private static final int STACK_SUB = 1;

    public ActivityQueryRequestDto convert2ActivityQueryRequestDto(CreateOrderVo createOrderVo) {
        if (createOrderVo == null || createOrderVo.getPremiumExchangeActivity() == null
                || CollectionUtils.isEmpty(createOrderVo.getPremiumExchangeActivity().getProducts())) {
            return null;
        }
        ActivityQueryRequestDto activityQueryRequestDto = new ActivityQueryRequestDto();
        activityQueryRequestDto.setVer(Version.VERSION_1);
        activityQueryRequestDto.setPartnerCode(createOrderVo.getPartnerId());
        activityQueryRequestDto.setStoreId(createOrderVo.getShopId());
        activityQueryRequestDto.setActivityType(ActivityTypeEnum.TYPE_81.getCode());
        List<ActivityQueryRequestDto.QueryGoodsBeanDto> goodsBeanDtoList = new ArrayList<>();
        for (CreateOrderVo.PremiumExchangeActivity.Product skuProduct : createOrderVo.getPremiumExchangeActivity().getProducts()) {
            ActivityQueryRequestDto.QueryGoodsBeanDto queryGoodsBeanDto = new ActivityQueryRequestDto.QueryGoodsBeanDto(skuProduct.getSkuId(),
                    skuProduct.getQty(),
                    skuProduct.getOriginalPrice());
            goodsBeanDtoList.add(queryGoodsBeanDto);
        }
        activityQueryRequestDto.setGoods(goodsBeanDtoList);
        return activityQueryRequestDto;
    }

    public ActivityCalculationDiscountRequestDto convert2ActivityCalculationDiscountRequestDto(ShoppingCartInfoDto shoppingCartInfoDto
            , String partnerCode, String storeId, String appid, Integer orderType, CouponListResponseDto.CouponBean couponBean, Long promotionAmount) {
        if (shoppingCartInfoDto == null || CollectionUtils.isEmpty(shoppingCartInfoDto.getData())) {
            return null;
        }
        ActivityCalculationDiscountRequestDto result = new ActivityCalculationDiscountRequestDto();
        result.setVer(Integer.valueOf(Version.VERSION_1));
        result.setPartnerCode(partnerCode);
        result.setStoreId(storeId);
        ActivityChannelEnum activityChannelEnum = PropertyConvertUtil.orderTypeConvert2ActivityChannel(orderType);
        if(!Objects.isNull(activityChannelEnum)) {
            result.setChannel(activityChannelEnum.getCode());
        }
        result.setAppId(appid);
        result.setIsShowActivities(1);
        result.setIsShowGoodsActivity(1);
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountGoods> goods = new ArrayList<>();
        // TODO 暂时指定成一个商品，后期优化
        ActivityCalculationDiscountRequestDto.CalculationDiscountGoods calculationDiscountGoods = new ActivityCalculationDiscountRequestDto.CalculationDiscountGoods();
        calculationDiscountGoods.setGoodsId("1");
        calculationDiscountGoods.setCategory("1");
        calculationDiscountGoods.setGoodsQuantity(1);
        Long amount = 0L;
        if (shoppingCartInfoDto.getAmount() != null) {
            amount = shoppingCartInfoDto.getAmount();
        }
        Long packAmount = 0L;
        // 外卖才有打包费
        if (shoppingCartInfoDto.getPackAmount() != null && Objects.equals(CreateOrderType.TAKE_OUT.getCode(), orderType)) {
            packAmount = shoppingCartInfoDto.getPackAmount();
        }
        Long couponAmount = 0L;
        if (couponBean != null && couponBean.getDiscountAmount() != null) {
            couponAmount = Long.valueOf(couponBean.getDiscountAmount());
        }
        if (promotionAmount == null) {
            promotionAmount = 0L;
        }
        calculationDiscountGoods.setOriginalPrice(amount + packAmount - couponAmount - promotionAmount);
        goods.add(calculationDiscountGoods);
        result.setGoods(goods);
        return result;
    }

    public PremiumExchangeResponseVo convert2PremiumExchange(ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult) {
        // 返回构造对象
        PremiumExchangeResponseVo premiumExchangeResponseVo = new PremiumExchangeResponseVo();
        // 组装验证商品对象
        List<PremiumExchangeResponseVo.PremiumExchangeProduct> products = new ArrayList<>();
        premiumExchangeResponseVo.setResultCode(ActivityResultCodeEnum.NON_PARTICIPATE.getCode());
        if (calculationDiscountResult == null) {
            return premiumExchangeResponseVo;
        }
        // 只取最新活动
        if (calculationDiscountResult != null && CollectionUtils.isNotEmpty(calculationDiscountResult.getSendGoods())) {
            if (CollectionUtils.isNotEmpty(calculationDiscountResult.getDiscounts())) {
                List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount> discountList = calculationDiscountResult.getDiscounts();
                for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount discount : discountList) {
                    if (Objects.equals(discount.getType(), ActivityTypeEnum.TYPE_81.getCode())) {
                        Integer showType = discount.getIntegral() == null ? 0 : discount.getIntegral();
                        premiumExchangeResponseVo.setShowType(showType);
                    }
                }
            }
            for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity sendActivity : calculationDiscountResult.getSendGoods()) {
                if (Objects.equals(sendActivity.getActivityType(), ActivityTypeEnum.TYPE_81.getCode())) {
                    // 判断加价购活动商品不存在直接跳出循环
                    if (CollectionUtils.isEmpty(sendActivity.getSendGoods())) {
                        break;
                    }
                    premiumExchangeResponseVo.setResultCode(ActivityResultCodeEnum.PARTICIPATE.getCode());
                    premiumExchangeResponseVo.setActivityCode(sendActivity.getActivityCode());
                    premiumExchangeResponseVo.setActivityName(sendActivity.getActivityName());
                    premiumExchangeResponseVo.setMaxNum(sendActivity.getMaxNum());
                    sendActivity.getSendGoods().forEach(sendGoods -> {
                        PremiumExchangeResponseVo.PremiumExchangeProduct product = new PremiumExchangeResponseVo.PremiumExchangeProduct();
                        product.setSpuId(sendGoods.getCategory());
                        product.setSkuId(sendGoods.getGoodsId());
                        product.setSkuName(sendGoods.getGoodsName());
                        product.setOriginalPrice(sendGoods.getOriginalPrice());
                        product.setNowPrice(sendGoods.getNowPrice());
                        product.setNumber(sendGoods.getSendNumber());
                        products.add(product);
                    });
                    break;
                }
            }
        }
        if(CollectionUtils.isEmpty(products)){
            premiumExchangeResponseVo.setResultCode(ActivityResultCodeEnum.NO_ACTIVITY.getCode());
            premiumExchangeResponseVo.setResultMsg(ActivityResultCodeEnum.NO_ACTIVITY.getDesc());
            return premiumExchangeResponseVo;
        }
        premiumExchangeResponseVo.setProducts(products);
        return premiumExchangeResponseVo;
    }

    public ActivityUpdateStockRequestDto convert2ActivityUpdateStockRequestDto(CreateOrderVo createOrderVo, String orderId, CreateOrderDto createOrderDto) {
        ActivityUpdateStockRequestDto activityUpdateStockRequestDto = new ActivityUpdateStockRequestDto();
        activityUpdateStockRequestDto.setVer(Version.VERSION_1);
        activityUpdateStockRequestDto.setOrderId(orderId);
        activityUpdateStockRequestDto.setPartnerCode(createOrderVo.getPartnerId());
        activityUpdateStockRequestDto.setStoreId(createOrderVo.getShopId());

        List<ActivityUpdateStockRequestDto.StockBeanDto> stock = new ArrayList<>();
        // 加价购
        if (createOrderVo.getPremiumExchangeActivity() != null && CollectionUtils.isNotEmpty(createOrderVo.getPremiumExchangeActivity().getProducts())) {
            ActivityUpdateStockRequestDto.StockBeanDto stockBeanDto = new ActivityUpdateStockRequestDto.StockBeanDto();
            stockBeanDto.setActivityCode(createOrderVo.getPremiumExchangeActivity().getActivityCode());
            stockBeanDto.setActivityStock(STACK_SUB);
            List<ActivityUpdateStockRequestDto.StockBeanDto.GoodsStock> goodsStocks = new ArrayList<>();
            createOrderVo.getPremiumExchangeActivity().getProducts().forEach(product -> {
                ActivityUpdateStockRequestDto.StockBeanDto.GoodsStock goodsStock = new ActivityUpdateStockRequestDto.StockBeanDto.GoodsStock();
                goodsStock.setGoodsId(product.getSkuId());
                goodsStock.setStock(product.getQty());
                goodsStocks.add(goodsStock);
            });
            stockBeanDto.setGoodsStock(goodsStocks);
            stock.add(stockBeanDto);
        }
        // 满减活动和限时特价
        if (createOrderDto != null && CollectionUtils.isNotEmpty(createOrderDto.getAccounts())) {
            createOrderDto.getAccounts().forEach(createOrderAccountDto -> {
                if (Objects.equals(createOrderAccountDto.getType(), OrderAccountType.BUY_DISCOUNT.getCode())
                        || Objects.equals(createOrderAccountDto.getType(), OrderAccountType.DISCOUNT_AMOUNT.getCode())
                        || Objects.equals(createOrderAccountDto.getType(), OrderAccountType.BUYM_SENDN.getCode())) {
                    ActivityUpdateStockRequestDto.StockBeanDto stockBeanDto = new ActivityUpdateStockRequestDto.StockBeanDto();
                    stockBeanDto.setActivityCode(createOrderAccountDto.getAccountId());
                    stockBeanDto.setActivityStock(STACK_SUB);
                    List<ActivityUpdateStockRequestDto.StockBeanDto.GoodsStock> goodsStocks = new ArrayList<>();
                    // 满减活动没有商品库存
                    if (CollectionUtils.isNotEmpty(createOrderAccountDto.getAccountProducts())
                            && !Objects.equals(createOrderAccountDto.getType(), OrderAccountType.BUY_DISCOUNT.getCode())
                            && !Objects.equals(createOrderAccountDto.getType(), OrderAccountType.BUYM_SENDN.getCode())) {
                        createOrderAccountDto.getAccountProducts().forEach(createAccountProductDto -> {
                            ActivityUpdateStockRequestDto.StockBeanDto.GoodsStock goodsStock = new ActivityUpdateStockRequestDto.StockBeanDto.GoodsStock();
                            goodsStock.setGoodsId(createAccountProductDto.getProductId());
                            goodsStock.setStock(createAccountProductDto.getDiscountQty());
                            goodsStocks.add(goodsStock);
                        });
                    }
                    stockBeanDto.setGoodsStock(goodsStocks);
                    stock.add(stockBeanDto);
                }
            });
        }
        activityUpdateStockRequestDto.setStock(stock);
        return activityUpdateStockRequestDto;
    }

    public ActivityCancelStockRequestDto convert2ActivityCancelStockRequestDto(QueryOrdersResponseDto.DataBean.OrderBean orderBean, List<Integer> transType) {
        ActivityCancelStockRequestDto activityCancelStockRequestDto = new ActivityCancelStockRequestDto();
        activityCancelStockRequestDto.setVer(Version.VERSION_1);
        activityCancelStockRequestDto.setPartnerCode(orderBean.getCompanyId());
        activityCancelStockRequestDto.setStoreId(orderBean.getShopId());
        activityCancelStockRequestDto.setOrderId(orderBean.getOid());
        activityCancelStockRequestDto.setTransType(transType);
        activityCancelStockRequestDto.setUserId(orderBean.getUserId());
        List<ActivityCancelStockRequestDto.ProductVo> orderProducts = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(orderBean.getProductList())) {
            orderBean.getProductList().forEach(productBean -> {
                ActivityCancelStockRequestDto.ProductVo productStock = new ActivityCancelStockRequestDto.ProductVo();
                productStock.setSkuId(productBean.getSpecification() );
                productStock.setQty(productBean.getNumber());
                orderProducts.add(productStock);
            });
        }
        activityCancelStockRequestDto.setProducts(orderProducts);
        //优惠券冲正
        List<QueryOrdersResponseDto.DataBean.OrderBean.AccountBean> accountList = orderBean.getAccountList();
        if (!CollectionUtils.isEmpty(accountList) && !CollectionUtils.isEmpty(orderBean.getProductList())) {
            for (QueryOrdersResponseDto.DataBean.OrderBean.AccountBean accountBean : accountList) {
                List<CouponCodeVerificationProductDto> products = new ArrayList<>();
                //订单中存储的6代表商品券
                if (Objects.equals(accountBean.getType(), OrderAccountType.PRODUCT_COUPON.getCode())) {
                    for (int i = 0; i < orderBean.getProductList().size(); i++) {
                        QueryOrdersResponseDto.DataBean.OrderBean.ProductBean productBean = orderBean.getProductList().get(i);
                        String pid = StringUtils.isNotBlank(productBean.getSpecification()) ? productBean.getSpecification() : productBean.getProductId();
                        if (!org.springframework.util.CollectionUtils.isEmpty(orderBean.getProductList().get(i).getDiscountList())) {
                            List<QueryOrdersResponseDto.DataBean.OrderBean.ProductBean.ProductDiscount> discounts = orderBean.getProductList().get(i).getDiscountList().stream().
                                    filter(productDiscount -> productDiscount.getDiscountId().equals(accountBean.getAccountId())).collect(Collectors.toList());
                            for (QueryOrdersResponseDto.DataBean.OrderBean.ProductBean.ProductDiscount productDiscount : discounts) {
                                CouponCodeVerificationProductDto couponCodeVerificationProductDto = new CouponCodeVerificationProductDto();
                                couponCodeVerificationProductDto.setPID(pid);
                                couponCodeVerificationProductDto.setConsume_num(productDiscount.getDiscountQty());
                                couponCodeVerificationProductDto.setSeq(i + 1);
                                products.add(couponCodeVerificationProductDto);
                            }
                        }
                    }
                }
                if (OrderAccountType.COUPON.getCode().equals(accountBean.getType())
                        || OrderAccountType.PRODUCT_COUPON.getCode().equals(accountBean.getType())
                        || OrderAccountType.DISCOUNT_COUPON.getCode().equals(accountBean.getType())) {
                    activityCancelStockRequestDto.setCouponCode(accountBean.getAccountId());
                    activityCancelStockRequestDto.setCouponProducts(products);
                }
            }
        }

        return activityCancelStockRequestDto;
    }

    /**
     * 组装ActivityQueryDto对象
     *
     * @param partnerId
     * @param storeId
     * @param userId
     * @param appId
     * @param orderType
     * @return
     */
    public ActivityQueryDto getActivityQueryDto(String partnerId, String storeId, String userId, String appId, Integer orderType) {
        return ActivityQueryDto.builder()
                .partnerId(partnerId)
                .storeId(storeId)
                .userId(userId)
                .appId(appId)
                .orderType(orderType)
                .build();
    }



    public PremiumExchangeResponseVo convert2PremiumExchangeSharing(CalculationSharingDiscountResponseDto.CalculationDiscountResult discountResult) {
        // 返回构造对象
        PremiumExchangeResponseVo premiumExchangeResponseVo = new PremiumExchangeResponseVo();
        // 组装验证商品对象
        List<PremiumExchangeResponseVo.PremiumExchangeProduct> products = new ArrayList<>();
        premiumExchangeResponseVo.setResultCode(ActivityResultCodeEnum.NON_PARTICIPATE.getCode());
        if (discountResult == null) {
            return premiumExchangeResponseVo;
        }
        // 只取最新活动
        if (discountResult != null && CollectionUtils.isNotEmpty(discountResult.getSendGoods())) {
            if (CollectionUtils.isNotEmpty(discountResult.getDiscounts())) {
                List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.Discount> discountList = discountResult.getDiscounts();
                for (CalculationSharingDiscountResponseDto.CalculationDiscountResult.Discount discount : discountList) {
                    if (Objects.equals(discount.getType(), ActivityTypeEnum.TYPE_81.getCode())) {
                        Integer showType = discount.getIntegral() == null ? 0 : discount.getIntegral();
                        premiumExchangeResponseVo.setShowType(showType);
                    }
                }
            }
            for (CalculationSharingDiscountResponseDto.CalculationDiscountResult.SendActivity sendActivity : discountResult.getSendGoods()) {
                if (Objects.equals(sendActivity.getActivityType(), ActivityTypeEnum.TYPE_81.getCode())) {
                    // 判断加价购活动商品不存在直接跳出循环
                    if (CollectionUtils.isEmpty(sendActivity.getSendGoods())) {
                        break;
                    }
                    premiumExchangeResponseVo.setResultCode(ActivityResultCodeEnum.PARTICIPATE.getCode());
                    premiumExchangeResponseVo.setActivityCode(sendActivity.getActivityCode());
                    premiumExchangeResponseVo.setActivityName(sendActivity.getActivityName());
                    premiumExchangeResponseVo.setMaxNum(sendActivity.getMaxNum());
                    sendActivity.getSendGoods().forEach(sendGoods -> {
                        PremiumExchangeResponseVo.PremiumExchangeProduct product = new PremiumExchangeResponseVo.PremiumExchangeProduct();
                        product.setSpuId(sendGoods.getCategory());
                        product.setSkuId(sendGoods.getGoodsId());
                        product.setSkuName(sendGoods.getGoodsName());
                        product.setOriginalPrice(sendGoods.getOriginalPrice());
                        product.setNowPrice(sendGoods.getNowPrice());
                        product.setNumber(sendGoods.getSendNumber());
                        products.add(product);
                    });
                    break;
                }
            }
        }
        if(CollectionUtils.isEmpty(products)){
            premiumExchangeResponseVo.setResultCode(ActivityResultCodeEnum.NO_ACTIVITY.getCode());
            premiumExchangeResponseVo.setResultMsg(ActivityResultCodeEnum.NO_ACTIVITY.getDesc());
            return premiumExchangeResponseVo;
        }
        premiumExchangeResponseVo.setProducts(products);
        return premiumExchangeResponseVo;
    }

    public CouponAvailableCartInfo convert2CouponAvailableCartInfoSharing(String partnerId,String storeId, CalculationSharingDiscountResponseDto.CalculationDiscountResult discountResult, List<String>  orgCodes) {
        // 返回构造对象
        CouponAvailableCartInfo couponAvailableCartInfo = new CouponAvailableCartInfo();
        couponAvailableCartInfo.setProviderId(partnerId);
        couponAvailableCartInfo.setMerchantId(partnerId);
        couponAvailableCartInfo.setStoreId(storeId);
        couponAvailableCartInfo.setChannelIdList(orgCodes);

        Long totalMealDiscountAmount = 0L;//套餐优惠不算在内
        Long sendDiscountAmount = 0L;//赠送和换购商品优惠不算在内
        Long sendRealAmount = 0L;//赠送和换购商品实付不算在内
        if(discountResult!=null){
            //已使用券
            if(CollectionUtils.isNotEmpty(discountResult.getDiscounts())){
                List<String> couponCodes = discountResult.getDiscounts().stream().filter(discount -> Objects.equals(discount.getType(),ActivityTypeEnum.TYPE_3.getCode())
                        || Objects.equals(discount.getType(),ActivityTypeEnum.TYPE_31.getCode())
                        || Objects.equals(discount.getType(),ActivityTypeEnum.TYPE_32.getCode())
                        || Objects.equals(discount.getType(),ActivityTypeEnum.TYPE_33.getCode())).map(CalculationSharingDiscountResponseDto.CalculationDiscountResult.Discount::getActivityCode).collect(Collectors.toList());
                couponAvailableCartInfo.setCouponCodes(couponCodes);

                totalMealDiscountAmount = discountResult.getDiscounts().stream().filter(goodsDiscount -> Objects.equals(goodsDiscount.getType(),ActivityTypeEnum.TYPE_310.getCode())).mapToLong(CalculationSharingDiscountResponseDto.CalculationDiscountResult.Discount::getDiscount).sum();
            }

            if(CollectionUtils.isNotEmpty(discountResult.getGoods())){
                List<CartProduct> goods = new ArrayList<>();
                for(CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods discountGood : discountResult.getGoods()){
                    //小料和可选搭配金额
                    Pair<Long,Long> pair  = getSmallMaterialAmountSharing(discountGood.getSmallMaterial());//value1=总实付 value2=总优惠
                    if(Objects.equals(CalculationGoodsType.TYPE_1.getType(),discountGood.getCartGoodType()) || Objects.equals(CalculationGoodsType.TYPE_2.getType(),discountGood.getCartGoodType())){
                        sendRealAmount += discountGood.getRealAmount() + pair.getFirst();
                        sendDiscountAmount += discountGood.getDiscountAmount() + pair.getSecond();
                        continue;
                    }
                    CartProduct cartProduct = new CartProduct();
                    cartProduct.setProductId(discountGood.getGoodsId());
                    cartProduct.setQuantity(discountGood.getGoodsQuantity());

                    Long mealDiscountAmount = 0L;//套餐优惠不算在内
                    if(CollectionUtils.isNotEmpty(discountGood.getDiscounts())){
                        Optional<String> goodCoupon = discountGood.getDiscounts().stream().filter(goodsDiscount -> Objects.equals(goodsDiscount.getType(),ActivityTypeEnum.TYPE_32.getCode())
                                || Objects.equals(goodsDiscount.getType(),ActivityTypeEnum.TYPE_33.getCode())).map(CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount::getActivityCode).findFirst();
                        cartProduct.setCouponCode(goodCoupon!=null && goodCoupon.isPresent()?goodCoupon.get():null);

                        mealDiscountAmount = discountGood.getDiscounts().stream().filter(goodsDiscount -> Objects.equals(goodsDiscount.getType(),ActivityTypeEnum.TYPE_310.getCode())).mapToLong(CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount::getDiscount).sum();
                    }
                    cartProduct.setOriginalTotalAmount(discountGood.getRealAmount()+discountGood.getDiscountAmount() + pair.getFirst() + pair.getSecond() - mealDiscountAmount);
                    cartProduct.setRealAmount(discountGood.getRealAmount() + pair.getFirst());
                    cartProduct.setDiscountAmount(discountGood.getDiscountAmount()+pair.getSecond() - mealDiscountAmount);
                    goods.add(cartProduct);
                }
                couponAvailableCartInfo.setProductList(goods);
            }
            couponAvailableCartInfo.setOriginalTotalAmount(discountResult.getOriginalTotalAmount() - totalMealDiscountAmount - sendRealAmount - sendDiscountAmount);
            couponAvailableCartInfo.setRealAmount(discountResult.getTotalAmount() - sendRealAmount);
            couponAvailableCartInfo.setDiscountAmount(discountResult.getTotalDiscountAmount() - totalMealDiscountAmount - sendDiscountAmount);
        }else{
            couponAvailableCartInfo.setProductList(new ArrayList<>());
            couponAvailableCartInfo.setOriginalTotalAmount(0L);
            couponAvailableCartInfo.setRealAmount(0L);
            couponAvailableCartInfo.setDiscountAmount(0L);
        }
        return couponAvailableCartInfo;
    }
    public CouponAvailableCartInfo convert2CouponAvailableCartInfo(String partnerId,String storeId,ActivityCalculationDiscountResponseDto.CalculationDiscountResult discountResult, List<String>  orgCodes) {
        // 返回构造对象
        CouponAvailableCartInfo couponAvailableCartInfo = new CouponAvailableCartInfo();
        couponAvailableCartInfo.setProviderId(partnerId);
        couponAvailableCartInfo.setMerchantId(partnerId);
        couponAvailableCartInfo.setStoreId(storeId);
        couponAvailableCartInfo.setChannelIdList(orgCodes);

        Long totalMealDiscountAmount = 0L;//套餐优惠不算在内
        if(discountResult!=null){
            //已使用券
            if(CollectionUtils.isNotEmpty(discountResult.getCouponDiscounts())){
                List<String> couponCodes = discountResult.getCouponDiscounts().stream().filter(discount -> Objects.equals(discount.getActivityType(),ActivityTypeEnum.TYPE_3.getCode())
                        || Objects.equals(discount.getActivityType(),ActivityTypeEnum.TYPE_31.getCode())
                        || Objects.equals(discount.getActivityType(),ActivityTypeEnum.TYPE_32.getCode())
                        || Objects.equals(discount.getActivityType(),ActivityTypeEnum.TYPE_33.getCode())).map(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.CouponResults::getCouponCode).collect(Collectors.toList());
                couponAvailableCartInfo.setCouponCodes(couponCodes);

                totalMealDiscountAmount = discountResult.getDiscounts().stream().filter(goodsDiscount -> Objects.equals(goodsDiscount.getType(),ActivityTypeEnum.TYPE_310.getCode())).mapToLong(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount::getDiscount).sum();
            }

            if(CollectionUtils.isNotEmpty(discountResult.getGoods())){
                List<CartProduct> goods = new ArrayList<>();
                for(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods discountGood : discountResult.getGoods()){
                    CartProduct cartProduct = new CartProduct();
                    cartProduct.setProductId(discountGood.getGoodsId());
                    cartProduct.setQuantity(discountGood.getGoodsQuantity());
                    //小料和可选搭配金额
                    Pair<Long,Long> pair  = getSmallMaterialAmount(discountGood.getSmallMaterial());//value1=总实付 value2=总优惠
                    Long mealDiscountAmount = 0L;//套餐优惠不算在内
                    if(CollectionUtils.isNotEmpty(discountGood.getDiscounts())){
                        Optional<String> goodCoupon = discountGood.getDiscounts().stream().filter(goodsDiscount -> Objects.equals(goodsDiscount.getType(),ActivityTypeEnum.TYPE_32.getCode())
                                || Objects.equals(goodsDiscount.getType(),ActivityTypeEnum.TYPE_33.getCode())).map(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount::getActivityCode).findFirst();
                        cartProduct.setCouponCode(goodCoupon!=null && goodCoupon.isPresent()?goodCoupon.get():null);

                        mealDiscountAmount = discountGood.getDiscounts().stream().filter(goodsDiscount -> Objects.equals(goodsDiscount.getType(),ActivityTypeEnum.TYPE_310.getCode())).mapToLong(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount::getDiscount).sum();
                    }
                    cartProduct.setOriginalTotalAmount(discountGood.getRealAmount()+discountGood.getDiscountAmount() + pair.getFirst()+pair.getSecond() - mealDiscountAmount);
                    cartProduct.setRealAmount(discountGood.getRealAmount()+pair.getFirst());
                    cartProduct.setDiscountAmount(discountGood.getDiscountAmount()+pair.getSecond() -mealDiscountAmount);
                    goods.add(cartProduct);
                }
                couponAvailableCartInfo.setProductList(goods);
            }
            couponAvailableCartInfo.setOriginalTotalAmount(discountResult.getOriginalTotalAmount() - totalMealDiscountAmount);
            couponAvailableCartInfo.setRealAmount(discountResult.getTotalAmount());
            couponAvailableCartInfo.setDiscountAmount(discountResult.getTotalDiscountAmount() - totalMealDiscountAmount);
        }else{
            couponAvailableCartInfo.setProductList(new ArrayList<>());
            couponAvailableCartInfo.setOriginalTotalAmount(0L);
            couponAvailableCartInfo.setRealAmount(0L);
            couponAvailableCartInfo.setDiscountAmount(0L);
        }
        return couponAvailableCartInfo;
    }
    private Pair<Long,Long> getSmallMaterialAmountSharing(List<CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods.SmallMaterial> smallMaterial){
        long realAmount = 0;
        long discountAmount = 0;
        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(smallMaterial)){
            for(CalculationSharingDiscountResponseDto.CalculationDiscountResult.Goods.SmallMaterial small :smallMaterial){
                realAmount += small.getRealAmount();
                discountAmount += small.getDiscountAmount();
            }
        }
        return Pair.of(realAmount,discountAmount);
    }
    private Pair<Long,Long> getSmallMaterialAmount(List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.GoodsMaterial> smallMaterial){
        long realAmount = 0;
        long discountAmount = 0;
        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(smallMaterial)){
            for(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.GoodsMaterial small :smallMaterial){
                realAmount += small.getRealAmount();
                discountAmount += small.getDiscountAmount();
            }
        }
        return Pair.of(realAmount,discountAmount);
    }
}
