/**
 * 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.ActivityCalculationDiscountRequestDto;
import cn.freemud.entities.dto.calculate.ActivityCalculationDiscountResponseDto;
import cn.freemud.entities.dto.calculate.ActivityTypeSharedExclusive;
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 com.freemud.application.sdk.api.ordercenter.entities.v1.AccountBeanV1;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.entities.v1.ProductBeanV1;
import com.freemud.application.sdk.api.ordercenter.entities.v1.ProductDiscountV1;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.BeanUtils;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Component;

import java.util.*;
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(OrderBeanV1 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<AccountBeanV1> accountList = orderBean.getAccountList();
        if (!CollectionUtils.isEmpty(accountList) && !CollectionUtils.isEmpty(orderBean.getProductList())) {
            for (AccountBeanV1 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++) {
                        ProductBeanV1 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<ProductDiscountV1> discounts = orderBean.getProductList().get(i).getDiscountList().stream().
                                    filter(productDiscount -> productDiscount.getDiscountId().equals(accountBean.getAccountId())).collect(Collectors.toList());
                            for (ProductDiscountV1 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(ActivityCalculationDiscountResponseDto.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<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount> discountList = discountResult.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 : 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, 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;//套餐优惠不算在内
//        Long sendDiscountAmount = 0L;//赠送和换购商品优惠不算在内
//        Long sendRealAmount = 0L;//赠送和换购商品实付不算在内
        if(discountResult!=null){
            boolean newCalculation = CollectionUtils.isNotEmpty(discountResult.getCouponSharedExclusive());
            if(newCalculation){
                couponAvailableCartInfo.setNewCalculation(newCalculation);
                buildOrderDiscount(couponAvailableCartInfo,discountResult.getDiscounts(),discountResult.getCouponSharedExclusive());
            }
            //已使用券
            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())
                        || Objects.equals(discount.getType(),ActivityTypeEnum.TYPE_330.getCode())).map(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount::getActivityCode).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()){
                    //小料和可选搭配金额
                    Triple<Long,Long,Long> triple  = getSmallMaterialAmountSharing(discountGood.getSmallMaterial());//value1=总实付 value2=总优惠 value3=单个主商品下总原价
                    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());
                    cartProduct.setOriginalPrice(discountGood.getOriginalPrice()+triple.getRight());

                    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())
                                        || Objects.equals(goodsDiscount.getType(),ActivityTypeEnum.TYPE_330.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() + triple.getLeft() + triple.getMiddle() - mealDiscountAmount);
                    cartProduct.setRealAmount(discountGood.getRealAmount() + triple.getLeft());
                    cartProduct.setDiscountAmount(discountGood.getDiscountAmount()+triple.getMiddle() - mealDiscountAmount);
                    if(newCalculation){
                        buildGoodDiscount(cartProduct,discountGood,discountResult.getCouponSharedExclusive());
                    }
                    goods.add(cartProduct);
                }
                couponAvailableCartInfo.setProductList(goods);
            }
//            couponAvailableCartInfo.setOriginalTotalAmount(discountResult.getOriginalTotalAmount() - totalMealDiscountAmount - sendRealAmount - sendDiscountAmount);
//            couponAvailableCartInfo.setRealAmount(discountResult.getTotalAmount() - sendRealAmount);
//            couponAvailableCartInfo.setDiscountAmount(discountResult.getTotalDiscountAmount() - totalMealDiscountAmount - sendDiscountAmount);
            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);
        }
        couponAvailableCartInfo.setDeliveryAmount(discountResult!=null?discountResult.getDeliveryAmount():0);
        couponAvailableCartInfo.setDistributionFee(discountResult!=null?discountResult.getDistributionFee():0);
        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.setExclusion(true);

        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())
                        || Objects.equals(discount.getActivityType(),ActivityTypeEnum.TYPE_330.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())
                                        || Objects.equals(goodsDiscount.getType(),ActivityTypeEnum.TYPE_330.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);
            couponAvailableCartInfo.setDeliveryAmount(discountResult.getDeliveryAmount());
            couponAvailableCartInfo.setDistributionFee(discountResult.getDistributionFee());
        }else{
            couponAvailableCartInfo.setProductList(new ArrayList<>());
            couponAvailableCartInfo.setOriginalTotalAmount(0L);
            couponAvailableCartInfo.setRealAmount(0L);
            couponAvailableCartInfo.setDiscountAmount(0L);
            couponAvailableCartInfo.setDeliveryAmount(0L);
            couponAvailableCartInfo.setDistributionFee(0L);
        }

        return couponAvailableCartInfo;
    }
    private Triple<Long,Long,Long> getSmallMaterialAmountSharing(List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.SmallMaterial> smallMaterial){
        long realAmount = 0;
        long discountAmount = 0;
        long originalPrice = 0;
        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(smallMaterial)){
            for(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.SmallMaterial small :smallMaterial){
                realAmount += small.getRealAmount();
                discountAmount += small.getDiscountAmount();
                originalPrice += small.getOriginalPrice() * small.getGoodsQuantity();
            }
        }
        return Triple.of(realAmount,discountAmount,originalPrice);
    }
    private Pair<Long,Long> getSmallMaterialAmount(List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.SmallMaterial> smallMaterial){
        long realAmount = 0;
        long discountAmount = 0;
        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(smallMaterial)){
            for(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.SmallMaterial small :smallMaterial){
                realAmount += small.getRealAmount();
                discountAmount += small.getDiscountAmount();
            }
        }
        return Pair.of(realAmount,discountAmount);
    }

    private void buildGoodDiscount(CartProduct cartProduct, ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods discountGood, Set<ActivityTypeSharedExclusive> couponSharedExclusive){
        if(CollectionUtils.isEmpty(discountGood.getDiscounts())){
            return;
        }
        HashMap<Integer,Integer> cashExclusiveMap = new HashMap<>();
        HashMap<Integer,Integer> cashMultipleMap = new HashMap<>();
        HashMap<Integer,Integer> discountExclusiveMap = new HashMap<>();
        HashMap<Integer,Integer> discountMultipleMap = new HashMap<>();
        for(ActivityTypeSharedExclusive sharedExclusive : couponSharedExclusive){
            if(Objects.equals(sharedExclusive.getActivityType(),ActivityTypeEnum.TYPE_3.getCode())){
                cashExclusiveMap.put(sharedExclusive.getSharedExclusiveActivityType(),sharedExclusive.getSharedExclusive());
                cashMultipleMap.put(sharedExclusive.getSharedExclusiveActivityType(),sharedExclusive.getMultiple());
            }
            if(Objects.equals(sharedExclusive.getActivityType(),ActivityTypeEnum.TYPE_31.getCode())){
                discountExclusiveMap.put(sharedExclusive.getSharedExclusiveActivityType(),sharedExclusive.getSharedExclusive());
                discountMultipleMap.put(sharedExclusive.getSharedExclusiveActivityType(),sharedExclusive.getMultiple());
            }
        }

        List<CartProduct.Discount> cartProductDiscountList = new ArrayList<>();
        for(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount discount : discountGood.getDiscounts()){
            if(Objects.equals(discount.getType(),ActivityTypeEnum.TYPE_310.getCode())){
                continue;
            }
            CartProduct.Discount cartProductDiscount = new CartProduct.Discount();
            BeanUtils.copyProperties(discount,cartProductDiscount);
            cartProductDiscount.setActualGoodsNumber(discount.getAddOnQuantity());

            //小料或者可选搭配的优惠金额合并至主商品
            long smallDiscountAmount = getSmallActivityDiscountAmount(discountGood.getSmallMaterial(),discount.getType());
            cartProductDiscount.setDiscount(cartProductDiscount.getDiscount() + smallDiscountAmount);

            //是否与代金券互斥
            boolean cashExclusive = Objects.equals(cashExclusiveMap.get(discount.getType()),YesOrNoEnum.NO.getCode());
            cartProductDiscount.setCashExclusive(cashExclusive);

            //是否与代金券叠加门槛
            boolean cashMultiple = !Objects.equals(cashMultipleMap.get(discount.getType()),YesOrNoEnum.NO.getCode());
            cartProductDiscount.setCashMultiple(cashMultiple);

            //是否与折扣券互斥
            boolean discountExclusive = Objects.equals(discountExclusiveMap.get(discount.getType()),YesOrNoEnum.NO.getCode());
            cartProductDiscount.setDiscountExclusive(discountExclusive);

            //是否与折扣券叠加门槛
            boolean discountMultiple = !Objects.equals(discountMultipleMap.get(discount.getType()),YesOrNoEnum.NO.getCode());
            cartProductDiscount.setDiscountMultiple(discountMultiple);

            cartProductDiscountList.add(cartProductDiscount);
        }
        cartProduct.setDiscounts(cartProductDiscountList);
    }

    private void buildOrderDiscount(CouponAvailableCartInfo couponAvailableCartInfo,List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount> discounts, Set<ActivityTypeSharedExclusive> couponSharedExclusive){
        if(CollectionUtils.isEmpty(discounts)){
            return;
        }
        HashMap<Integer,Integer> cashExclusiveMap = new HashMap<>();
        HashMap<Integer,Integer> cashMultipleMap = new HashMap<>();
        HashMap<Integer,Integer> discountExclusiveMap = new HashMap<>();
        HashMap<Integer,Integer> discountMultipleMap = new HashMap<>();
        for(ActivityTypeSharedExclusive sharedExclusive : couponSharedExclusive){
            if(Objects.equals(sharedExclusive.getActivityType(),ActivityTypeEnum.TYPE_3.getCode())){
                cashExclusiveMap.put(sharedExclusive.getSharedExclusiveActivityType(),sharedExclusive.getSharedExclusive());
                cashMultipleMap.put(sharedExclusive.getSharedExclusiveActivityType(),sharedExclusive.getMultiple());
            }
            if(Objects.equals(sharedExclusive.getActivityType(),ActivityTypeEnum.TYPE_31.getCode())){
                discountExclusiveMap.put(sharedExclusive.getSharedExclusiveActivityType(),sharedExclusive.getSharedExclusive());
                discountMultipleMap.put(sharedExclusive.getSharedExclusiveActivityType(),sharedExclusive.getMultiple());
            }
        }

        List<CouponAvailableCartInfo.Discount> cartDiscountList = new ArrayList<>();
        for(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount discount : discounts){
            if(Objects.equals(discount.getType(),ActivityTypeEnum.TYPE_310.getCode())){
                continue;
            }
            CouponAvailableCartInfo.Discount cartProductDiscount = new CouponAvailableCartInfo.Discount();
            BeanUtils.copyProperties(discount,cartProductDiscount);

            //是否与代金券互斥
            boolean cashExclusive = Objects.equals(cashExclusiveMap.get(discount.getType()),YesOrNoEnum.NO.getCode());
            cartProductDiscount.setCashExclusive(cashExclusive);

            //是否与代金券叠加门槛
            boolean cashMultiple = !Objects.equals(cashMultipleMap.get(discount.getType()),YesOrNoEnum.NO.getCode());
            cartProductDiscount.setCashMultiple(cashMultiple);

            //是否与折扣券互斥
            boolean discountExclusive = Objects.equals(discountExclusiveMap.get(discount.getType()),YesOrNoEnum.NO.getCode());
            cartProductDiscount.setDiscountExclusive(discountExclusive);

            //是否与折扣券叠加门槛
            boolean discountMultiple = !Objects.equals(discountMultipleMap.get(discount.getType()),YesOrNoEnum.NO.getCode());
            cartProductDiscount.setDiscountMultiple(discountMultiple);

            cartDiscountList.add(cartProductDiscount);
        }
        couponAvailableCartInfo.setDiscounts(cartDiscountList);
    }

    private Long getSmallActivityDiscountAmount(List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.SmallMaterial> smallMaterial,Integer activityType){
        long discountAmount = 0;
        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(smallMaterial)){
            for(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.SmallMaterial small :smallMaterial){
                if(CollectionUtils.isNotEmpty(small.getDiscounts())){
                    for(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount smallDiscount :small.getDiscounts()){
                        if(Objects.equals(smallDiscount.getType(),activityType)){
                            discountAmount += smallDiscount.getDiscount();
                        }
                    }
                }
            }
        }
        return discountAmount;
    }
}
