package cn.freemud.service.impl.mcoffee.calculation;

import cn.freemud.adapter.ActivityAdapter;
import cn.freemud.adapter.ShoppingCartConvertAdapter;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.activity.ActivityDiscountsDto;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.activity.ShareDiscountActivityDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.ActivityChannelEnum;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.enums.GoodsTypeEnum;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.CommonService;
import cn.freemud.service.thirdparty.ActivityClient;
import cn.freemud.utils.PropertyConvertUtil;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.membercenter.request.QueryReceiveAddressRequest;
import com.freemud.application.sdk.api.membercenter.response.QueryReceiveAddressResponse;
import com.freemud.application.sdk.api.membercenter.service.MemberCenterService;
import com.freemud.application.sdk.api.storecenter.request.QueryDeliveryRequest;
import com.freemud.application.sdk.api.storecenter.request.StoreInfoRequest;
import com.freemud.application.sdk.api.storecenter.response.QueryDeliverDetailResponse;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import com.freemud.sdk.api.assortment.shoppingcart.enums.BusinessTypeEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: CalculationServiceImpl
 * @Package cn.freemud.service.impl
 * @Description:
 * @author: shuhu.hou
 * @date: 2020/6/11 17:06
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */

@Service
public class CalculationServiceImpl {


    @Autowired
    private MemberCenterService memberCenterService;
    @Autowired
    private StoreCenterService storeCenterService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private ActivityClient activityClient;
    @Autowired
    private ActivityAdapter activityAdapter;


    @Autowired
    private TimeSaleCalculation timeSaleCalculation;
    @Autowired
    private FullPromotionCalculation fullPromotionCalculation;
    @Autowired
    private CouponDiscountCalculation couponDiscountCalculation;
    @Autowired
    private SetMealCalculation setMealCalculation;

    @Autowired
    private ShoppingCartConvertAdapter shoppingCartConvertAdapter;

    /**
     * 更新购物车行优惠信息
     */
    public ActivityCalculationDiscountResponseDto.CalculationDiscountResult updateShoppingCartGoodsDiscount(String partnerId, String storeId, String userId, String appId, Integer orderType,
                                                                                                            boolean isMember, String menuType, String receiveId,String couponCode,
                                                                                                            List<CartGoods> cartGoodsList, List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons,
                                                                                                            List<ShoppingCartInfoRequestVo.SendGoods> sendGoodsList, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo,
                                                                                                            Long payCardFee) {

        Long deliveryAmount = calculateDeliveryAmount(receiveId, partnerId, storeId, menuType);

        ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscount = getCalculationDiscount(partnerId, storeId, userId, appId, orderType, isMember,
                menuType, deliveryAmount, cartGoodsList, coupons, sendGoodsList,payCardFee);
        updateDiscount(calculationDiscount, cartGoodsList, shoppingCartGoodsResponseVo,deliveryAmount);
        //满减
        ActivityQueryDto activityQueryDto = fullPromotionCalculation.getActivityQueryDto(partnerId, storeId, userId, appId, orderType);
        fullPromotionCalculation.updateShoppingCartGoodsDiscount(activityQueryDto, calculationDiscount, cartGoodsList, shoppingCartGoodsResponseVo);

        //限时特价、单品特价、超值加购
        timeSaleCalculation.updateShoppingCartGoodsDiscount(calculationDiscount, cartGoodsList, shoppingCartGoodsResponseVo);

        //优惠券
        CouponPromotionVO couponPromotionVO = couponDiscountCalculation.getCouponPromotionVO(partnerId, storeId, userId, couponCode, orderType);
        couponDiscountCalculation.updateShoppingCartGoodsDiscount(couponPromotionVO,calculationDiscount,cartGoodsList, shoppingCartGoodsResponseVo);

        //套餐
        setMealCalculation.updateShoppingCartGoodsDiscount(calculationDiscount,cartGoodsList,shoppingCartGoodsResponseVo);

        return calculationDiscount;
    }


    public ActivityCalculationDiscountResponseDto.CalculationDiscountResult getCalculationDiscount(
            String partnerId, String storeId, String userId, String appId, Integer orderType, boolean isMember, String menuType, Long deliveryAmount,
            List<CartGoods> cartGoodsList, List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons, List<ShoppingCartInfoRequestVo.SendGoods> sendGoodsList, Long payCardFee) {

        List<ActivityCalculationDiscountRequestDto.CalculationDiscountGoods> calculationDiscountGoodsList = new ArrayList<>();
        for (CartGoods cartGoods : cartGoodsList) {
            addCalculationDiscountGoods(calculationDiscountGoodsList,
                    StringUtils.isNotEmpty(cartGoods.getCustomerCode()) ? cartGoods.getCustomerCode() : "",
                    StringUtils.isNotEmpty(cartGoods.getGoodsId()) ? cartGoods.getGoodsId() : "",
                    null != cartGoods.getQty() ? cartGoods.getQty() : 0 ,
                    null != cartGoods.getFinalPrice() ? cartGoods.getFinalPrice() : 0,
                    null != cartGoods.getMemberDiscount() ? cartGoods.getMemberDiscount() : 0,
                    cartGoods);
        }

        // 当加价购商品不为空时
        if (CollectionUtils.isNotEmpty(sendGoodsList)) {
            for (ShoppingCartInfoRequestVo.SendGoods sendGoods : sendGoodsList) {
                this.addCalculationDiscountGoods(calculationDiscountGoodsList, sendGoods.getGoodsId(), sendGoods.getGoodsId(), sendGoods.getQty(), sendGoods.getOriginalPrice(), 100,null);
            }
        }
        calculationDiscountGoodsList.removeIf(calculationDiscountGoods -> (calculationDiscountGoods.getGoodsQuantity().equals(0)));
        if (CollectionUtils.isEmpty(calculationDiscountGoodsList)) {
            return null;
        }

        ActivityCalculationDiscountRequestDto discountRequest = getActivityCalculationDiscountRequestDto(partnerId, storeId, userId, appId, orderType);
        discountRequest.setGoods(calculationDiscountGoodsList);
        discountRequest.setCoupons(coupons);
        discountRequest.setOrgIds(commonService.getOrgIds(partnerId, storeId));
        discountRequest.setDistributionFee(deliveryAmount);
        discountRequest.setIsMember(isMember);
        discountRequest.setPayCardFee(payCardFee);
        ActivityCalculationDiscountResponseDto activityCalculationDiscountResponseDto;
        try {
            activityCalculationDiscountResponseDto = activityClient.calculationDiscountSharing(discountRequest);
        } catch (Exception ex) {
            ErrorLog.printErrorLog("calculation_discount_error", "/calculation/discount/sharding", discountRequest, ex);
            throw new ServiceException(ResponseResult.OPERATE_TOO_OFTEN);
        }
        // 返回成功
        if (activityCalculationDiscountResponseDto == null || !StringUtils.equals(activityCalculationDiscountResponseDto.getStatusCode(), ResponseCodeConstant.RESPONSE_SUCCESS_STR)) {
            throw new ServiceException(ResponseResult.OPERATE_TOO_OFTEN);
        }
        return activityCalculationDiscountResponseDto.getResult();
    }


    public void updateShoppingCartGoodsApportion(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult, ShoppingCartGoodsDto shoppingCartGoodsDto, CreateOrderVo.PremiumExchangeActivity premiumExchangeActivity, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo){

        List<ShoppingCartGoodsDto.CartGoodsDetailDto> cartGoodsDetailDtoList = CollectionUtils.isEmpty(shoppingCartGoodsDto.getProducts()) ? new ArrayList<>() : shoppingCartGoodsDto.getProducts();
        List<ShareDiscountActivityDto> shareDiscountActivityDtoList = CollectionUtils.isEmpty(shoppingCartGoodsDto.getShareDiscountActivityDtos()) ? new ArrayList<>() : shoppingCartGoodsDto.getShareDiscountActivityDtos();
        //设置空
        shoppingCartGoodsDto.setProducts(cartGoodsDetailDtoList);
        shoppingCartGoodsDto.setShareDiscountActivityDtos(shareDiscountActivityDtoList);
        shoppingCartGoodsDto.setOriginalTotalAmount(shoppingCartGoodsResponseVo.getOriginalTotalAmount());
        shoppingCartGoodsDto.setTotalAmount(shoppingCartGoodsResponseVo.getTotalAmount());
        shoppingCartGoodsDto.setTotalDiscountAmount(shoppingCartGoodsResponseVo.getTotalDiscountAmount());
        //随单购 月卡价格
        shoppingCartGoodsDto.setPayCardFee(shoppingCartGoodsResponseVo.getPayCardFee());

        shoppingCartGoodsDto.setDeliveryAmount(shoppingCartGoodsResponseVo.getDeliveryAmount());
        shoppingCartGoodsDto.setDiscountDeliveryAmount(shoppingCartGoodsResponseVo.getDiscountDeliveryAmount());
        shoppingCartGoodsDto.setThresholdAmount(shoppingCartGoodsResponseVo.getThresholdAmount());
        shoppingCartGoodsDto.setIsDiscountDelivery(shoppingCartGoodsResponseVo.getIsDiscountDelivery());
        shoppingCartGoodsDto.setDiscountDeliveryActivityCode(shoppingCartGoodsResponseVo.getDiscountDeliveryActivityCode());

        // todo 包装费
        shoppingCartGoodsDto.setPackageAmount(shoppingCartGoodsResponseVo.getNewPackAmount());
        List<CartGoods> cartGoodsList = shoppingCartGoodsResponseVo.getProducts();
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods> apportionGoodsList =
                calculationDiscountResult == null ? new ArrayList<>() : calculationDiscountResult.getApportionGoods();
        Map<String, String> duplicateGoodsMap = new HashMap<>();

        cartGoodsList.stream().collect(Collectors.groupingBy(CartGoods::getGoodsId, Collectors.counting())).forEach((goodsId, count) -> {
            duplicateGoodsMap.put(goodsId,String.format("%s,0", count));
        });
        for (int i = 0, len = cartGoodsList.size(); i < len; i++) {
            CartGoods cartGoods = cartGoodsList.get(i);
            List<ShoppingCartGoodsDto.CartGoodsDetailDto> cartGoodsDetailDtos = shoppingCartConvertAdapter.convertCartGoods2DetailGoodsList(cartGoods, apportionGoodsList,duplicateGoodsMap);
            cartGoodsDetailDtoList.addAll(cartGoodsDetailDtos);
        }
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount> discounts = calculationDiscountResult == null ? new ArrayList<>() : calculationDiscountResult.getDiscounts();
        List<ActivityDiscountsDto> activityDiscountsDtos = shoppingCartGoodsDto.getActivityDiscountsDtos() == null ? new ArrayList<>() : shoppingCartGoodsDto.getActivityDiscountsDtos();
        for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount discount : discounts) {
            int discountAmount = (discount.getDiscount() == null) ? 0 : discount.getDiscount();
            Integer discountType = discount.getType();
            if (discountType != null && discountAmount > 0) {
                ActivityDiscountsDto activityDiscountsDto = new ActivityDiscountsDto();
                activityDiscountsDto.setActivityCode(discount.getActivityCode());
                activityDiscountsDto.setActivityName(discount.getActivityName());
                activityDiscountsDto.setActivityType(discountType);
                activityDiscountsDto.setDiscountAmount(0 - discountAmount);
                activityDiscountsDto.setTenderId(discount.getTenderId());
                activityDiscountsDtos.add(activityDiscountsDto);
            }
        }

        //订单级别券优惠
//        for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.CouponResults discount : calculationDiscountResult.getCouponDiscounts()) {
//            int discountAmount = (discount.getDiscountAmount() == null) ? 0 : discount.getDiscountAmount();
//            Integer discountType = discount.getActivityType();
//            if (discountType != null && discountAmount > 0) {
//                ActivityDiscountsDto activityDiscountsDto = new ActivityDiscountsDto();
//                activityDiscountsDto.setActivityCode(discount.getCouponCode());
//                activityDiscountsDto.setActivityName(discount.getActivityName());
//                activityDiscountsDto.setActivityType(discountType);
//                activityDiscountsDto.setDiscountAmount(0 - discountAmount);
//                activityDiscountsDtos.add(activityDiscountsDto);
//            }
//        }
        //过滤出加价购
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount> addMoneyDiscounts = discounts.stream().filter(discount -> ActivityTypeEnum.TYPE_81.getCode().equals(discount.getType())).collect(Collectors.toList());


        shoppingCartGoodsDto.setActivityDiscountsDtos(activityDiscountsDtos);
        if (null != calculationDiscountResult) {
            //处理加价购
            List<SubtractStockVO> stocks = filterSendGoodsStocks(calculationDiscountResult.getStocks(), shoppingCartInfoRequestVo, addMoneyDiscounts);
            if (CollectionUtils.isNotEmpty(stocks)) {
                shoppingCartGoodsDto.setStocks(stocks);
            }
        }


//        fullPromotionCalculation.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto,premiumExchangeActivity,shoppingCartInfoRequestVo);
        //限时特价
        timeSaleCalculation.updateShoppingCartGoodsApportion(calculationDiscountResult, shoppingCartGoodsDto);

        CouponPromotionVO couponPromotionVO = new CouponPromotionVO();
//        couponPromotionVO.setPartnerId("1206");
//        couponPromotionVO.setUserId(userId);
//        couponPromotionVO.setStoreId(storeId);
//        couponPromotionVO.setCouponCode(null);
//        couponPromotionVO.setOrderType(orderType);
//        couponPromotionVO.setFlg(CouponFlag.YES.getCode());
        //优惠券
        couponDiscountCalculation.updateShoppingCartGoodsApportion(calculationDiscountResult, shoppingCartGoodsDto);

        setMealCalculation.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto);

    }


    /**
     * 库存扣减加价购商品 要过滤掉没有换购的商品
     *
     * @param stocks                    扣减库存
     * @param shoppingCartInfoRequestVo 购物车请求信息
     * @param addMoneyDiscounts         加价购活动
     * @return 返回应该扣减的加价购商品库存
     */
    private List<SubtractStockVO> filterSendGoodsStocks(List<SubtractStockVO> stocks, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo, List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount> addMoneyDiscounts) {
        if (CollectionUtils.isEmpty(stocks) || CollectionUtils.isEmpty(addMoneyDiscounts)) {
            return stocks;
        }
        List<SubtractStockVO> subtractStockVOs = stocks.stream().filter(subtractStockVO -> ActivityTypeEnum.TYPE_81.getCode().equals(subtractStockVO.getActivityType())).collect(Collectors.toList());
        List<SubtractStockVO.SubtractStockGoodsVO> goodsStock = null;
        if (CollectionUtils.isNotEmpty(subtractStockVOs)) {
            SubtractStockVO subtractStockVO = subtractStockVOs.get(0);
            goodsStock = subtractStockVO.getGoodsStock();
        }
        if (null == goodsStock) {
            return stocks;
        }
        Map<String, SubtractStockVO.SubtractStockGoodsVO> mapSubstractStocks = new HashMap<>();
        if (CollectionUtils.isNotEmpty(goodsStock)) {
            mapSubstractStocks = goodsStock.stream().collect(Collectors.toMap(SubtractStockVO.SubtractStockGoodsVO::getGoodsId, Function.identity(), (k1, k2) -> k1));
        }
        //获取加价购商品
        List<ShoppingCartInfoRequestVo.SendGoods> sendGoods = shoppingCartInfoRequestVo.getSendGoods();
        if (CollectionUtils.isNotEmpty(sendGoods)) {
            List<String> needSendGoodsId = sendGoods.stream().map(ShoppingCartInfoRequestVo.SendGoods::getGoodsId).collect(Collectors.toList());
            goodsStock.clear();
            for (String goodId : needSendGoodsId) {
                SubtractStockVO.SubtractStockGoodsVO subtractStockGoodsVO = mapSubstractStocks.get(goodId);
                if (null != mapSubstractStocks.get(goodId)) {
                    goodsStock.add(subtractStockGoodsVO);
                }
            }
        } else {
            return stocks.stream().filter(subtractStockVO -> !ActivityTypeEnum.TYPE_81.getCode().equals(subtractStockVO.getActivityType())).collect(Collectors.toList());
        }
        return stocks;
    }






    /**
     * 配送金额
     */
    private Long calculateDeliveryAmount(String receiveId, String partnerId, String storeId, String menuType) {
        Long deliveryAmount = 0l;
        if (StringUtils.isBlank(receiveId) || !BusinessTypeEnum.SAAS_DELIVERY.getCode().equals(menuType)) {
            return deliveryAmount;
        }
        String trackingNo = LogThreadLocal.getTrackingNo();

        QueryReceiveAddressRequest queryReceive = new QueryReceiveAddressRequest(receiveId, partnerId);
        //查询会员后货地址经纬度
        com.freemud.application.sdk.api.base.BaseResponse<QueryReceiveAddressResponse> queryReceiveAddressResponse = memberCenterService.queryReceiveAddressById(queryReceive, trackingNo);
        if (!ResponseResult.SUCCESS.getCode().equals(queryReceiveAddressResponse.getCode()) || queryReceiveAddressResponse.getData() == null) {
            throw new ServiceException(ResponseResult.USER_GETRECEIVEADDRESS_ERROR);
        }

        StoreInfoRequest storeInfoRequest = new StoreInfoRequest();
        storeInfoRequest.setPartnerId(partnerId);
        storeInfoRequest.setStoreCode(storeId);
        StoreResponse storeInfo = storeCenterService.getStoreInfo(storeInfoRequest, trackingNo);

        if (storeInfo == null || storeInfo.getStatusCode() != 100 || storeInfo.getBizVO() == null) {
            throw new ServiceException(ResponseResult.STORE_ITEM_NOT_DELIVERY);
        }
//        if (storeInfo.getBizVO().getDeliveryPrice() == 0) {
//            throw new ServiceException(ResponseResult.STORE_DELIVERY_AMOUNT_ERROR);
//        }
        Double deliveryPrice = storeInfo.getBizVO().getDeliveryPrice()*100;
        deliveryAmount = deliveryPrice.longValue();
        return deliveryAmount;
    }


    /**
     * 构建 ActivityCalculationDiscountRequestDto
     *
     * @param partnerId
     * @param storeId
     * @param userId
     * @param appId
     * @param orderType
     * @return
     */
    private ActivityCalculationDiscountRequestDto getActivityCalculationDiscountRequestDto(String partnerId, String storeId, String userId, String appId, Integer orderType) {
        ActivityCalculationDiscountRequestDto activityCalculationDiscountRequestDto = new ActivityCalculationDiscountRequestDto();
        activityCalculationDiscountRequestDto.setPartnerCode(partnerId);
        activityCalculationDiscountRequestDto.setStoreId(storeId);
        activityCalculationDiscountRequestDto.setIsShowGoodsActivity(1);
        activityCalculationDiscountRequestDto.setUserId(userId);
        activityCalculationDiscountRequestDto.setVer(1);
        activityCalculationDiscountRequestDto.setAppId(appId);
        ActivityChannelEnum activityChannelEnum = PropertyConvertUtil.orderTypeConvert2ActivityChannel(orderType);
        if (!Objects.isNull(activityChannelEnum)) {
            activityCalculationDiscountRequestDto.setChannel(activityChannelEnum.getCode());
        }
        return activityCalculationDiscountRequestDto;
    }

    /**
     * 将calculationDiscountGoods 封装后加入 calculationDiscountGoodsList
     *
     * @param calculationDiscountGoodsList
     * @param goodsId
     * @param goodsQuantity
     * @param originalPrice
     */
    private void addCalculationDiscountGoods(List<ActivityCalculationDiscountRequestDto.CalculationDiscountGoods> calculationDiscountGoodsList,
                                             String goodsCode,String goodsId, Integer goodsQuantity, Long originalPrice, Integer memberDiscount,CartGoods cartGoods) {
        ActivityCalculationDiscountRequestDto.CalculationDiscountGoods calculationDiscountGoods = new ActivityCalculationDiscountRequestDto.CalculationDiscountGoods();
        calculationDiscountGoods.setGoodsCode(goodsCode);
        calculationDiscountGoods.setGoodsId(goodsId);
        calculationDiscountGoods.setGoodsQuantity(goodsQuantity);
        calculationDiscountGoods.setOriginalPrice(originalPrice);
        calculationDiscountGoods.setMemberDiscount(memberDiscount);
        //新增咖啡月卡券券号
        calculationDiscountGoods.setCouponCode(cartGoods.getCouponCode());

        ArrayList<ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material> materials = new ArrayList<>();
        //可选搭配
        if (cartGoods != null && CollectionUtils.isNotEmpty(cartGoods.getProductGroupList())) {
            for (CartGoods.ComboxGoods materialGoods : cartGoods.getProductGroupList()) {
                if("0".equals(materialGoods.getGoodsId())){
                    continue;
                }
                ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material material = new ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material();
                material.setType(2);
                material.setGoodsId(materialGoods.getGoodsId());
                material.setGoodsQuantity(materialGoods.getQty());
                material.setOriginalPrice(materialGoods.getFinalPrice());
                materials.add(material);
            }
        }

        //固定商品
        if (cartGoods != null && CollectionUtils.isNotEmpty(cartGoods.getProductComboList())) {
            for (CartGoods.ComboxGoods materialGoods : cartGoods.getProductComboList()) {
                //加料
                if (CollectionUtils.isNotEmpty(materialGoods.getProductMaterialList())) {
                    for (CartGoods.MaterialGoods materialGoods2 : materialGoods.getProductMaterialList()) {
                        ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material material = new ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material();
                        material.setType(1);
                        material.setGoodsId(materialGoods2.getSpuId());
                        material.setGoodsQuantity(cartGoods.getQty());
                        material.setOriginalPrice(materialGoods2.getFinalPrice());
                        materials.add(material);
                    }
                }
            }
        }

        //加料
        if (cartGoods != null && CollectionUtils.isNotEmpty(cartGoods.getProductMaterialList())) {
            for (CartGoods.MaterialGoods materialGoods : cartGoods.getProductMaterialList()) {
                ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material material = new ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material();
                material.setType(1);
                material.setGoodsId(materialGoods.getSpuId());
                material.setGoodsQuantity(cartGoods.getQty());
                material.setOriginalPrice(materialGoods.getFinalPrice());
                materials.add(material);
            }
        }
        calculationDiscountGoods.setSmallMaterial(materials);
        calculationDiscountGoodsList.add(calculationDiscountGoods);

//        //累加需加入计算的商品
//        int index;
//        // 当商品已存在时,需累加数量
//        if ((index = calculationDiscountGoodsList.indexOf(calculationDiscountGoods)) >= 0 && !GoodsTypeEnum.COUPON_GOODS.getGoodsType().equals(cartGoods.getGoodsType())) {
//            ActivityCalculationDiscountRequestDto.CalculationDiscountGoods oldCalculationDiscountGoods = calculationDiscountGoodsList.get(index);
//            oldCalculationDiscountGoods.setGoodsQuantity(oldCalculationDiscountGoods.getGoodsQuantity() + calculationDiscountGoods.getGoodsQuantity());
//        } else {
//
//        }
    }


    private void updateDiscount(ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscount, List<CartGoods> cartGoodsList, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo,Long deliveryAmount) {
        long totalOriginalAmount = 0L;
        long totalAmount = 0L;
        long totalPackgeAmount = 0L;
        for (CartGoods cartGoods : cartGoodsList) {
            // 设置商品原价与商品现价的初始值
            long originalAmount = null != cartGoods.getOriginalPrice() ? cartGoods.getOriginalPrice() : 0;
            long amount =  null != cartGoods.getOriginalPrice() ? cartGoods.getOriginalPrice() : 0;
            long packAmount =  null != cartGoods.getPackPrice() ? cartGoods.getPackPrice() : 0;
            totalOriginalAmount += originalAmount;
            totalAmount += amount;
            totalPackgeAmount += packAmount;
            cartGoods.setOriginalAmount(originalAmount);
            cartGoods.setAmount(amount);
            cartGoods.setPackPrice(packAmount);
        }
        shoppingCartGoodsResponseVo.setOriginalTotalAmount(calculationDiscount == null ? totalOriginalAmount : calculationDiscount.getOriginalTotalAmount());
        shoppingCartGoodsResponseVo.setTotalAmount(calculationDiscount == null ? totalAmount : calculationDiscount.getTotalAmount());

        shoppingCartGoodsResponseVo.setPayCardFee(calculationDiscount == null ? 0L : calculationDiscount.getPayCardFee() );
        shoppingCartGoodsResponseVo.setOriginalTotalAmount(shoppingCartGoodsResponseVo.getOriginalTotalAmount() + totalPackgeAmount);
        shoppingCartGoodsResponseVo.setTotalAmount(shoppingCartGoodsResponseVo.getTotalAmount() + totalPackgeAmount);
        shoppingCartGoodsResponseVo.setNewPackAmount(totalPackgeAmount);
        shoppingCartGoodsResponseVo.setTotalDiscountAmount(calculationDiscount == null ? 0L : calculationDiscount.getTotalDiscountAmount());
        shoppingCartGoodsResponseVo.setDeliveryAmount(deliveryAmount);
        shoppingCartGoodsResponseVo.setDiscountDeliveryAmount(calculationDiscount == null ? 0L :calculationDiscount.getDistributionFee());
    }

}
