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

import cn.freemud.adapter.ShoppingCartMccafeAdapter;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.dto.GetMenuResponseDto;
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.calculate.ActivityCalculationDiscountRequestDto;
import cn.freemud.entities.dto.calculate.ActivityCalculationDiscountResponseDto;
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.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.CommonService;
import cn.freemud.service.impl.ItemServiceImpl;
import cn.freemud.service.thirdparty.ActivityClient;
import cn.freemud.utils.PropertyConvertUtil;
import com.alibaba.fastjson.JSON;
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.StoreInfoRequest;
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 com.freemud.sdk.api.assortment.shoppingcart.util.ShoppingSdkLogUtil;
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 ItemServiceImpl itemService;

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

    @Autowired
    private MaterialCalculation materialCalculation;
    @Autowired
    private ShoppingCartMccafeAdapter shoppingCartMccafeAdapter;
    @Autowired
    private BuySendCalculation buySendCalculation;
    @Autowired
    private FreightCalculation freightCalculation;

    /**
     * 更新购物车行优惠信息
     */
    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, List<CartGoods> cartSendGoodsList) {

        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);

        //优惠券
        couponDiscountCalculation.updateShoppingCartGoodsDiscount(calculationDiscount, cartGoodsList, shoppingCartGoodsResponseVo);

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

        //加料
//        materialCalculation.updateShoppingCartGoodsApportion(calculationDiscount,cartGoodsList);

        if(null != calculationDiscount) {
            //买赠
            buySendCalculation.updateBuySendActivityTip(calculationDiscount, shoppingCartGoodsResponseVo, cartSendGoodsList);
            //运费
            freightCalculation.updateBuySendActivityTip(calculationDiscount, 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);
        discountRequest.setProductChannel(orderType == 1 ? "saasdelivery" : "saas");
        ActivityCalculationDiscountResponseDto activityCalculationDiscountResponseDto;
//        try {
            activityCalculationDiscountResponseDto = activityClient.calculationDiscountSharing(discountRequest);
//        } catch (Exception ex) {
//            throw new ServiceException(ResponseResult.OPERATE_TOO_OFTEN);
//        }
        //优惠券互斥
        if (null != activityCalculationDiscountResponseDto && StringUtils.equals(activityCalculationDiscountResponseDto.getStatusCode(),ResponseCodeConstant.RESPONSE_CONFLICTS_STR)){
            throw new ServiceException(ResponseResult.COUPON_CONFLICTS_ERROR);
        }
        // 返回成功
        if (activityCalculationDiscountResponseDto == null || !StringUtils.equals(activityCalculationDiscountResponseDto.getStatusCode(), ResponseCodeConstant.RESPONSE_SUCCESS_STR)) {
            throw new ServiceException(ResponseResult.OPERATE_TOO_OFTEN);
        }

        ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult = activityCalculationDiscountResponseDto.getResult();
        if(null != calculationDiscountResult) {
            if(CollectionUtils.isNotEmpty(calculationDiscountResult.getDiscounts())) {
                Integer discount = calculationDiscountResult.getDiscounts().stream().filter(o -> o.getType() == 230).mapToInt(o -> o.getDiscount()).sum();
                calculationDiscountResult.setTotalDiscountAmount(calculationDiscountResult.getTotalDiscountAmount() - discount);
                calculationDiscountResult.setOriginalTotalAmount(calculationDiscountResult.getOriginalTotalAmount() - discount);
                calculationDiscountResult.getDiscounts().removeIf(o -> o.getType() == 230);
            }
            if(CollectionUtils.isNotEmpty(calculationDiscountResult.getGoods())) {
                List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods> goods = new ArrayList<>();
                ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity sendActivity = new ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity();
                List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods> sendGoodsList2 = new ArrayList<>();
                sendActivity.setSendGoods(sendGoodsList2);
                sendActivity.setActivityType(ActivityTypeEnum.TYPE_230.getCode());
                calculationDiscountResult.getGoods().stream().forEach(o -> {
                    if(o.getCartGoodType() == 1) {
                        ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods sendGoods = new ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods();
                        sendGoods.setGoodsId(o.getGoodsId());
                        sendGoods.setNowPrice(o.getNowPrice());
                        sendGoods.setOriginalPrice(o.getOriginalPrice());
                        sendGoods.setSendNumber(o.getGoodsQuantity());
                        sendGoods.setOriginalGoodsUid(o.getOriginalGoodsUid());
                        sendGoodsList2.add(sendGoods);
                    } else {
                        goods.add(o);
                    }
                });
                calculationDiscountResult.setGoods(goods);
                calculationDiscountResult.setSendGoods(Arrays.asList(sendActivity));
            }
        }
        ShoppingSdkLogUtil.printLog("calculationDiscountResultAfterProcess" ,JSON.toJSONString(calculationDiscountGoodsList),null);
        return calculationDiscountResult;
    }


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

        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().filter(cartGoods -> !StringUtils.equals(cartGoods.getSkuId(),"9999"))
                .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);
            ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto = shoppingCartMccafeAdapter.convertCartGoods2DetailGoodsList(cartGoods, apportionGoodsList,duplicateGoodsMap);
            if(null != cartGoodsDetailDto) {
                cartGoodsDetailDtoList.add(cartGoodsDetailDto);
            }
        }
        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.setCartGoodsUid(discount.getCartGoodsUid());
                activityDiscountsDto.setDiscountAmount(0 - discountAmount);
                activityDiscountsDto.setTenderId(discount.getTenderId());
                activityDiscountsDto.setExtendType(discount.getExtendType());
                activityDiscountsDto.setCartGoodsUid(StringUtils.isNotEmpty(discount.getCartGoodsUid()) ? discount.getCartGoodsUid() : "");
                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);
            }
        }

        List<ShoppingCartGoodsDto.CartGoodsDetailDto> products = shoppingCartGoodsDto.getProducts().stream().filter(p-> !StringUtils.equals("9999",p.getSkuId())).collect(Collectors.toList());
        List<String> productIds = products.stream().map(t -> t.getSkuId()).collect(Collectors.toList());

        //调用商品的接口获取商品键位
        BaseResponse<Map<String, GetMenuResponseDto.DataBean.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean>> baseResponse = itemService.getProducts(shoppingCartInfoRequestVo.getPartnerId(),
                shoppingCartInfoRequestVo.getShopId(), productIds, false, shoppingCartInfoRequestVo.getMenuType());
        if (ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode()) && baseResponse.getResult() != null){
            for (ShoppingCartGoodsDto.CartGoodsDetailDto cartGoods: products) {
                GetMenuResponseDto.DataBean.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean productBean = baseResponse.getResult().get(cartGoods.getSkuId());
                cartGoods.setProductCode(productBean.getCustomerCode());
            }
        }

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

        //优惠券
        couponDiscountCalculation.updateShoppingCartGoodsApportion(calculationDiscountResult, shoppingCartGoodsDto, shoppingCartInfoRequestVo);

        setMealCalculation.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto);

        buySendCalculation.updateBuySendGoods(calculationDiscountResult, shoppingCartGoodsDto, cartSendGoodsList);
    }


    /**
     * 库存扣减加价购商品 要过滤掉没有换购的商品
     *
     * @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.setCartGoodsUid(cartGoods.getCartGoodsUid());
        //新增咖啡月卡券券号,同一行商品才替换券号，防止不同商品券相同sku之间的覆盖
        if (cartGoods.getCartGoodsUid().equals(calculationDiscountGoods.getCartGoodsUid())) {
            calculationDiscountGoods.setCouponCode(StringUtils.isEmpty(cartGoods.getCouponCode()) ? null : 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 productGroup =
                        new ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material();
                productGroup.setType(2);
                productGroup.setGoodsId(materialGoods.getGoodsId());
                productGroup.setGoodsQuantity(materialGoods.getQty());
                productGroup.setOriginalPrice(null != materialGoods.getFinalPrice() ?
                        materialGoods.getFinalPrice() : 0);
                materials.add(productGroup);

                if (CollectionUtils.isNotEmpty(materialGoods.getProductMaterialList())){
                    for (CartGoods.MaterialGoods goods : materialGoods.getProductMaterialList()) {
                        ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material material = new ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material();
                        material.setType(1);
                        material.setGoodsId(goods.getSpuId());
                        material.setGoodsQuantity(1);
                        material.setOriginalPrice(null != goods.getFinalPrice() ?
                                goods.getFinalPrice() : 0);
                        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()) {
                        if (StringUtils.isEmpty(materialGoods2.getSpuId())) {
                            continue;
                        }
                        ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material material = new ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material();
                        material.setType(1);
                        material.setGoodsId(materialGoods2.getSpuId());
                        material.setGoodsQuantity(1);
                        material.setOriginalPrice(null != materialGoods2.getFinalPrice() ?
                                materialGoods2.getFinalPrice() : 0);
                        materials.add(material);
                    }
                }
            }
        }

        //加料
        if (null != cartGoods && 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(1);
                material.setOriginalPrice(null != materialGoods.getOriginalPrice() ?
                        materialGoods.getOriginalPrice() : 0);
                material.setNowPrice(null != materialGoods.getFinalPrice() ? materialGoods.getFinalPrice().intValue():0);
                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()* cartGoods.getQty() : 0;
            long amount =  null != cartGoods.getFinalPrice() ? cartGoods.getFinalPrice()* cartGoods.getQty() : 0;
            long packAmount =  null != cartGoods.getPackPrice() ? cartGoods.getPackPrice()* cartGoods.getQty() : 0;
            totalOriginalAmount += originalAmount;
            totalAmount += amount;
            totalPackgeAmount += packAmount;
            long materialPrice = getMaterialPrice(cartGoods);
            cartGoods.setOriginalAmount(originalAmount + materialPrice);
            cartGoods.setAmount(amount + materialPrice);
            cartGoods.setPackPrice(packAmount);
        }
        shoppingCartGoodsResponseVo.setOriginalTotalAmount(calculationDiscount == null ? totalOriginalAmount : calculationDiscount.getOriginalTotalAmount());
        shoppingCartGoodsResponseVo.setTotalAmount(calculationDiscount == null ? totalAmount : calculationDiscount.getTotalAmount());

        shoppingCartGoodsResponseVo.setPayCardFee(calculationDiscount == null ? 0L : (calculationDiscount.getPayCardFee()== 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());
    }


    private Long getMaterialPrice(CartGoods cartGoods){
        Long materialPrice = 0L;
        //单品、多规格加料
        if(CollectionUtils.isNotEmpty(cartGoods.getProductMaterialList())){
            for (CartGoods.MaterialGoods materialGoods : cartGoods.getProductMaterialList()){
                materialPrice+= (null != materialGoods.getFinalPrice() ? materialGoods.getFinalPrice() : 0) * (null != cartGoods.getQty() ? cartGoods.getQty() : 0);
            }
        }
        return materialPrice;
    }


}
