package cn.freemud.factory;

import cn.freemud.adapter.ShoppingCartConvertAdapter;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.constant.ShoppingCartConstant;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.activity.ActivityQueryResponseDto;
import cn.freemud.entities.dto.calculate.ActivityCalculationDiscountRequestDto;
import cn.freemud.entities.dto.calculate.CalculationDiscountResult;
import cn.freemud.entities.dto.calculate.Discount;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.*;
import cn.freemud.interceptor.BizServiceException;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.ActivityService;
import cn.freemud.service.BuriedPointService;
import cn.freemud.service.ItemService;
import cn.freemud.service.ShoppingCartNewService;
import cn.freemud.service.impl.*;
import cn.freemud.service.thirdparty.CustomerApplicationClient;
import cn.freemud.service.thirdparty.StockClient;
import cn.freemud.utils.PromotionFactory;
import com.alibaba.fastjson.JSON;
import com.freemud.api.assortment.datamanager.entity.db.AssortmentOpenPlatformPartnerStoreDeliveryConfig;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.api.assortment.datamanager.manager.AssortmentOpenPlatformPartnerStoreDeliveryConfigManager;
import com.freemud.api.assortment.datamanager.manager.customer.AssortmentCustomerInfoManager;
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.productcenter.domain.ProductBeanDTO;
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 com.freemud.sdk.api.assortment.shoppingcart.service.ShoppingCartBaseService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.awt.geom.Point2D;
import java.text.DecimalFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.freemud.constant.ApplicationConstant.*;
import static cn.freemud.constant.ShoppingCartConstant.SHOPPING_CART_EMPTY_GOODS_LIST;
import static cn.freemud.constant.ShoppingCartConstant.SHOPPING_CART_INVALIAD_GOODS;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: null.java
 * @Package
 * @Description: (用一句话描述该文件做什么)
 * @author: pegnfei.liu
 * @date: 2020-9-24
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目的
 */
public abstract class AbstractShoppingCartImpl implements ShoppingCartNewService {

    @Autowired
    private CustomerApplicationClient customerApplicationClient;

    @Autowired
    private StockClient stockClient;

    @Autowired
    private MemberCenterService memberCenterService;

    @Autowired
    private StoreCenterService storeCenterService;

    @Autowired
    private StoreServiceImpl storeService;

    @Autowired
    private AssortmentOpenPlatformPartnerStoreDeliveryConfigManager deliveryConfigManager;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private BuriedPointService buriedPointService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private AssortmentSdkService assortmentSdkService;
    @Autowired
    private AssortmentCustomerInfoManager customerInfoManager;
    // 配送费逻辑是否使用旧的
    @Value("${store.delivery.use.old:true}")
    private boolean storeDeliveryUseOld;

    /**
     * 根据sessionId获取用户信息
     * @param sessionId
     * @return
     */
    public CustomerInfoVo getCustomerInfoVo(String sessionId) {
//        GetSessionUserInfoDto getSessionUserInfoDto = new GetSessionUserInfoDto();
//        getSessionUserInfoDto.setIsGetPaid(true);
//        getSessionUserInfoDto.setSessionId(sessionId);
//        BaseResponse<CustomerInfoVo> sessionUserInfo = customerApplicationClient.getSessionUserInfo(getSessionUserInfoDto);
//        if (!ResponseResult.SUCCESS.getCode().equals(sessionUserInfo.getCode()) || sessionUserInfo.getResult() == null) {
//            throw new ServiceException(ResponseResult.NOT_LOGIN);
//        }
        AssortmentCustomerInfoVo customerInfoVo = customerInfoManager.getCustomerInfoByObject(sessionId);
        if(customerInfoVo == null) throw new ServiceException(ResponseResult.NOT_LOGIN);;
        String jsonObject = JSON.toJSONString(customerInfoVo);
        CustomerInfoVo customerInfoVo1 = JSON.parseObject(jsonObject,CustomerInfoVo.class);
//        BeanUtil.convertBean(customerInfoVo,customerInfoVo1);
        return customerInfoVo1;
    }

    public UserLoginInfoDto convert2UserLoginInfoDto(CustomerInfoVo assortmentCustomerInfoVo) {

        UserLoginInfoDto userLoginInfoDto = new UserLoginInfoDto();
        userLoginInfoDto.setMemberId(assortmentCustomerInfoVo.getMemberId());
        userLoginInfoDto.setOpenId(assortmentCustomerInfoVo.getOpenId());
        userLoginInfoDto.setWxAppid(assortmentCustomerInfoVo.getWxAppId());
        userLoginInfoDto.setSessionKey(assortmentCustomerInfoVo.getSessionKey());
        userLoginInfoDto.setMobile(assortmentCustomerInfoVo.getMobile());
        userLoginInfoDto.setAppsecret(assortmentCustomerInfoVo.getAppSecret());
        userLoginInfoDto.setPartnerId(assortmentCustomerInfoVo.getPartnerId());
        userLoginInfoDto.setNewMemeber(assortmentCustomerInfoVo.getNewMember());
        userLoginInfoDto.setUnionId(assortmentCustomerInfoVo.getUnionId());

        return userLoginInfoDto;
    }

    /**
     * 汇总商品数量
     *
     * @param allCartGoodsList
     * @param cartGoods
     * @return
     */
    public Integer sumSkuQty(List<CartGoods> allCartGoodsList, CartGoods cartGoods) {
        Integer qty = 0;
        if (CollectionUtils.isEmpty(allCartGoodsList)) {
            qty = cartGoods.getQty();
        } else {
            qty = cartGoods.getQty();
            for (CartGoods goods : allCartGoodsList) {
                if (goods.getSkuId().equals(cartGoods.getSkuId()) && goods.getSpuId().equals(cartGoods.getSpuId())) {
                    qty += goods.getQty();
                }
            }
        }
        return qty;
    }

    /**
     * 查询多个商品库存信息
     *
     * @param addShoppingCartGoodsRequestVo
     * @param productIds
     * @param productBeanListSpuClass
     * @param skuId
     */
    public void queryManyGoodsStocks(AddShoppingCartGoodsRequestVo addShoppingCartGoodsRequestVo, List<Long> productIds
            , List<ProductBeanDTO> productBeanListSpuClass, String skuId, Integer qty) {
        GetProductStockRequestDto requestDto = new GetProductStockRequestDto();
        requestDto.setChannel(BusinessTypeEnum.getByType(addShoppingCartGoodsRequestVo.getMenuType()).getCode());
        requestDto.setPartnerId(addShoppingCartGoodsRequestVo.getPartnerId());
        requestDto.setStoreId(addShoppingCartGoodsRequestVo.getShopId());
        requestDto.setProductIds(productIds);
        GetProductStockResponseDto availableStocks = null;
        if (productBeanListSpuClass.get(0).getType() == ProductType.NOSPEC.getCode()
                && productBeanListSpuClass.get(0).getStockLimit() == 1) {
            availableStocks = stockClient.getAvailableStocks(requestDto);
        } else {
            for (ProductBeanDTO.SkuProductBean skuProductBean : productBeanListSpuClass.get(0).getSkuList()) {
                if (skuId.equals(skuProductBean.getSkuId()) && skuProductBean.getStockLimit() == 1) {
                    availableStocks = stockClient.getAvailableStocks(requestDto);
                    break;
                }
            }
        }
        if (availableStocks != null && !ResponseCodeConstant.RESPONSE_SUCCESS_STR.equals(availableStocks.getCode())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_STOCK_NOT_HAVE);
        }
        if (availableStocks != null && ResponseCodeConstant.RESPONSE_SUCCESS_STR.equals(availableStocks.getCode()) &&
                (CollectionUtils.isEmpty(availableStocks.getResult()) || availableStocks.getResult().get(0).getQty() == null
                        || availableStocks.getResult().get(0).getQty() < qty)) {
            Integer stock = 0;
            if (!CollectionUtils.isEmpty(availableStocks.getResult()) && (stock = availableStocks.getResult().get(0).getQty()) > 0) {
                throw new BizServiceException(ResponseResult.SHOPPING_CART_STOCK_NOT_HAVE, "仅剩" + stock + "件库存了");
            }
            throw new ServiceException(ResponseResult.SHOPPING_CART_STOCK_NOT_HAVE);
        }
    }

    public Long calculateDeliveryAmount(String receiveId, String partnerId, String storeId, String wxappid, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo) {
        Long deliveryAmount = 0L;
        if (StringUtils.isBlank(receiveId)) {
            return deliveryAmount;
        }
        if (storeDeliveryUseOld) {
            deliveryAmount = Long.parseLong(getDeliveryAmount(receiveId, partnerId, storeId).toString());
            shoppingCartGoodsResponseVo.setDeliveryFeeZeroReason(0);
        } else {
            deliveryAmount = getNewDeliveryAmount(receiveId, partnerId, storeId, shoppingCartGoodsResponseVo);
        }
        return deliveryAmount;

    }

    /**
     * 储值卡支付查询配送费
     *
     * @return
     */
    public Integer getDeliveryAmount(String receiveId, String partnerId, String storeId) {
        String trackingNo = LogThreadLocal.getTrackingNo();
        Integer amount = 0;
        if (StringUtils.isBlank(receiveId)) {
            return amount;
        }
        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 request = new StoreInfoRequest();
        request.setPartnerId(partnerId);
        request.setStoreCode(storeId);
        //查询门店信息，获取门店经纬度
        StoreResponse storeResponse = storeCenterService.getStoreInfo(request, trackingNo);
        if (storeResponse == null || storeResponse.getStatusCode() != 100 || storeResponse.getBizVO() == null) {
            throw new ServiceException(ResponseResult.STORE_NOT_FOUND);
        }
        //查询门店外卖配送配置
        AssortmentOpenPlatformPartnerStoreDeliveryConfig deliveryConfig = deliveryConfigManager.findByPartnerIdAndStoreCode(partnerId, storeId);
        if (deliveryConfig == null) {
            throw new ServiceException(ResponseResult.STORE_ITEM_NOT_DELIVERY);
        }
        StoreDeliveryInfoDto storeDeliveryInfoDto = new StoreDeliveryInfoDto();
        storeDeliveryInfoDto.setPartnerId(partnerId);
        storeDeliveryInfoDto.setStoreId(storeId);
        storeDeliveryInfoDto.setStoreName(storeResponse.getBizVO().getStoreName());
        storeDeliveryInfoDto.setDeliveryLimitAmount(deliveryConfig == null ? 0 : deliveryConfig.getDeliveryLimitAmount());
        storeDeliveryInfoDto.setDeliveryAmount(deliveryConfig == null ? 0 : deliveryConfig.getDeliveryAmount());
        storeDeliveryInfoDto.setDefaultDeliveryRange(deliveryConfig == null ? 0L : deliveryConfig.getDefaultDeliveryRange());
        storeDeliveryInfoDto.setAddRangeAmount(deliveryConfig == null ? 0L : deliveryConfig.getAddRangeAmount());
        storeDeliveryInfoDto.setAddRangeCount(deliveryConfig == null ? 0L : deliveryConfig.getAddRangeCount());
        storeDeliveryInfoDto.setPoint2DList(getDeliveryPoint2DList(storeResponse.getBizVO().getDistributionScope()));
        storeDeliveryInfoDto.setDeliveryHoursDay(storeResponse.getBizVO().getDeliveryHoursDay());
        storeDeliveryInfoDto.setLongitude(storeResponse.getBizVO().getLongitude());
        storeDeliveryInfoDto.setLatitude(storeResponse.getBizVO().getLatitude());
        storeDeliveryInfoDto.setScopeConfig(storeResponse.getBizVO().getScopeConfig());
        if (StringUtils.isNotEmpty(storeResponse.getBizVO().getDeliveryRadius())) {
            storeDeliveryInfoDto.setDeliveryRadius(Integer.valueOf(storeResponse.getBizVO().getDeliveryRadius()));
        } else {
            storeDeliveryInfoDto.setDeliveryRadius(0);
        }
        storeDeliveryInfoDto.setEnableTakeaway(true);
        String userLongitude = queryReceiveAddressResponse.getData().getLongitude();
        String userLatitude = queryReceiveAddressResponse.getData().getLatitude();
        amount = storeService.getUserRealDeliveryAmount(storeDeliveryInfoDto, userLongitude, userLatitude).intValue();
        return amount;
    }

    private Long getNewDeliveryAmount(String receiveId, String partnerId, String storeId, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo) {
        String trackingNo = LogThreadLocal.getTrackingNo();
        Long amount = 0L;
        if (StringUtils.isBlank(receiveId)) {
            return amount;
        }
        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);
        }

        QueryDeliveryRequest queryDeliveryRequest = new QueryDeliveryRequest();
        queryDeliveryRequest.setPartnerId(partnerId);
        queryDeliveryRequest.setStoreCode(storeId);
        queryDeliveryRequest.setUserLatitude(queryReceiveAddressResponse.getData().getLatitude());
        queryDeliveryRequest.setUserLongitude(queryReceiveAddressResponse.getData().getLongitude());
        com.freemud.application.sdk.api.base.BaseResponse<QueryDeliverDetailResponse> queryDeliverDetailResponse = storeCenterService.queryDeliverDetail(queryDeliveryRequest, trackingNo);
        if (queryDeliverDetailResponse == null || !ResponseResult.SUCCESS.getCode().equals(queryDeliverDetailResponse.getCode()) || queryDeliverDetailResponse.getData() == null) {
            throw new ServiceException(ResponseResult.STORE_ITEM_NOT_DELIVERY);
        }
        if(queryDeliverDetailResponse.getData().getDeliveryAmount() == null) {
            throw new ServiceException(ResponseResult.STORE_DELIVERY_AMOUNT_ERROR);
        }
        shoppingCartGoodsResponseVo.setDeliveryFeeZeroReason(queryDeliverDetailResponse.getData().getDeliveryFeeZeroReason() != null ? queryDeliverDetailResponse.getData().getDeliveryFeeZeroReason() : 0);
        return queryDeliverDetailResponse.getData().getDeliveryAmount();
    }

    /**
     * 获取配送范围内集合
     */
    public List<Point2D.Double> getDeliveryPoint2DList(String distributionScope) {
        if (StringUtils.isBlank(distributionScope)) {
            return Collections.emptyList();
        }
        /**
         * 如果点不为整数，返回空
         */
        String[] points = distributionScope.split(",");
        if (points.length % 2 != 0) {
            return Collections.emptyList();
        }
        List<String> pointList = Arrays.asList(points);
        List<Point2D.Double> point2DList = Lists.newArrayList();
        for (int i = 0; i < pointList.size(); i++) {
            Double pointX = Double.parseDouble(pointList.get(i));
            Double pointY = Double.parseDouble(pointList.get(++i));
            point2DList.add(new Point2D.Double(pointX, pointY));
        }
        return point2DList;
    }

    /**
     * 获取优惠
     */
    public CalculationDiscountResult getCalculationDiscountResult(String menuType
            , String partnerId, String storeId, String userId, String appId, String wxappid, Integer orderType, boolean isMember
            , List<CartGoods> cartGoodsList, List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons
            , List<ShoppingCartInfoRequestVo.SendGoods> sendGoodsList, String receiveId, Long deliveryAmount, long nightDistributionFee){
        // 获取优惠信息
        CalculationDiscountResult calculationDiscountResult=null;
        //外卖场景下 查询门店配送信息
        if(BusinessTypeEnum.SAAS_DELIVERY.getCode().equals(menuType)){

            calculationDiscountResult = this.getActivityCalculationDiscountResponse(partnerId, storeId, userId, appId, orderType,isMember, cartGoodsList, coupons, sendGoodsList,BusinessTypeEnum.getByType(menuType).getCode(),deliveryAmount,null, null, nightDistributionFee);
        }else{
            calculationDiscountResult = this.getActivityCalculationDiscountResponse(partnerId, storeId, userId, appId, orderType,isMember, cartGoodsList, coupons, sendGoodsList,BusinessTypeEnum.getByType(menuType).getCode(),null,null, null,0L);
        }

        return calculationDiscountResult;
    }


    /**
     * 促销活动的优惠金额计算
     *
     * @param calculationDiscountResult
     * @param cartGoodsList
     * @param shoppingCartGoodsResponseVo
     */
    public void updateShoppingCartGoodsDiscount(CouponPromotionVO couponPromotionVO, ActivityQueryDto activityQueryDto, CalculationDiscountResult calculationDiscountResult, List<CartGoods> cartGoodsList
            , ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo, UserLoginInfoDto userLoginInfoDto,String menuType,Long deliveryAmount,long nightDistributionFee) {
        deliveryAmount = Objects.isNull(deliveryAmount) ? 0L : deliveryAmount;
        //默认计算优惠
        DefaultPromotionService defaultPromotionService = (DefaultPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.DEFAULT_PROMOTION);
        defaultPromotionService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);

        // 优惠券
        CouponPromotionService couponPromotionService = (CouponPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.COUPON_DISCOUNT);
        couponPromotionService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);

        // 满减
        FullPromotionService fullPromotionService = (FullPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.FULL_REDUCTION);
        fullPromotionService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);

        if (calculationDiscountResult != null && CollectionUtils.isNotEmpty(calculationDiscountResult.getSendGoods())) {
            if (calculationDiscountResult.getSendGoods().stream()
                    .anyMatch(sendActivity -> Objects.equals(sendActivity.getActivityType(), ActivityTypeEnum.TYPE_6.getCode())
                            || Objects.equals(sendActivity.getActivityType(), ActivityTypeEnum.TYPE_61.getCode()))) {
                // 买赠
                BuySendPromotionService buySendPromotionService = (BuySendPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.BUY_ONE_SEND);
                buySendPromotionService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);
            }
            if (calculationDiscountResult.getSendGoods().stream()
                    .anyMatch(sendActivity -> Objects.equals(sendActivity.getActivityType(), ActivityTypeEnum.TYPE_81.getCode()))) {
                // 加价购
                AdditionalPromotionService additionalPromotionService = (AdditionalPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.ADDITIONAL_BUY);
                additionalPromotionService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);
            }
        }

        /**
         * 第x件y折活动计算方式：
         * 1. 从calculationDiscountResult.discounts中，type=104&discount>0则走下面的代码逻辑
         * 2. calculationDiscountResult.apportionGoods中，找到商品的所有的活动，然后把apportionAmount相加，把均摊放到当前的购物车商品里
         * 3. 限时特价和第x件y折活动冲突，故在第x件y折活动中去掉这个104type的活动
         *
         */
        if (calculationDiscountResult != null && CollectionUtils.isNotEmpty(calculationDiscountResult.getDiscounts())) {
            if (calculationDiscountResult.getDiscounts().stream()
                    .anyMatch(discount -> Objects.equals(discount.getType(), ActivityTypeEnum.TYPE_104.getCode())
                            && discount.getDiscount() > 0)) {
                XyDiscountServiceImpl xyDiscountService = (XyDiscountServiceImpl) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.XY_DISCOUNT);
                xyDiscountService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);
            }
        }

        // 限时特价
        TimeSalePromotionService timeSalePromotionService = (TimeSalePromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.TIME_SALE);
        timeSalePromotionService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);

        //套餐
        SetMealServiceImpl setMealService = (SetMealServiceImpl) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.SET_MEAL);
        setMealService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);

        //积分兑换
        CustomerScoreService customerScoreService = (CustomerScoreService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.CUSTOMER_SCORE);
        customerScoreService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);

        /**
         * 第2件N折计算划线价
         */
        if (calculationDiscountResult != null && CollectionUtils.isNotEmpty(calculationDiscountResult.getDiscounts())) {
            if (calculationDiscountResult.getDiscounts().stream()
                    .anyMatch(discount -> Objects.equals(discount.getType(), ActivityTypeEnum.TYPE_53.getCode())
                            && discount.getDiscount() > 0)) {
                TwoNDiscountServiceImpl twoNDiscountService = (TwoNDiscountServiceImpl) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.TwoN_DISCOUNT);
                twoNDiscountService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);
            }
        }
        // 买赠活动
        BuyAndGiftsPromotionService buyAndGiftsPromotionService =(BuyAndGiftsPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.BUY_GIFTS);
        buyAndGiftsPromotionService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);

        //会员价
        MemberDiscountServiceImpl memberDiscountService=(MemberDiscountServiceImpl) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.MEMBER_DISCOUNT);
        memberDiscountService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);

        /**
         * 满额减配送费
         */

        if(BusinessTypeEnum.SAAS_DELIVERY.getCode().equals(menuType)) {
            DecimalFormat df = new DecimalFormat("###.##");
            List<ActivityTypeEnum> activityTypeEnums = new LinkedList<>();
            activityTypeEnums.add(ActivityTypeEnum.TYPE_14);

            ActivityQueryResponseDto activityQueryResponseDto = activityService.queryActivityByType(activityQueryDto, activityTypeEnums, null);
            ActivityResponseDto activityResponse =null;
            BenefitBeanDto beanDto=null;
            if (activityQueryResponseDto != null &&activityQueryResponseDto.getResult()!=null && activityQueryResponseDto.getResult().size()>0) {
                activityResponse = activityQueryResponseDto.getResult().get(0);
                shoppingCartGoodsResponseVo.setDiscountDeliveryActivityCode(activityResponse.getActivityCode());
                beanDto=activityResponse.getBenefits().get(0);
            }

            Discount discount=null;
            if (calculationDiscountResult != null && CollectionUtils.isNotEmpty(calculationDiscountResult.getDiscounts())) {
                Optional<Discount> discountop
                        = calculationDiscountResult.getDiscounts().stream()
                        .filter(discount1 -> {
                            return ActivityTypeEnum.TYPE_14.getCode().equals(discount1.getType());
                        })
                        .findFirst();
                discount=discountop.orElseGet(() -> {return null ;});
            }
            if(discount!=null){
                if(beanDto.getBenefitType() == 1){
                    String desc = DELIVERY_DISCOUNT_DESC2;
                    shoppingCartGoodsResponseVo.setDeliveryDiscountDesc(String.format(desc, df.format(beanDto.getThresholdAmount().doubleValue() /100) ));
                }else{
                    String desc = DELIVERY_DISCOUNT_DESC1;
                    shoppingCartGoodsResponseVo.setDeliveryDiscountDesc(String.format(desc, df.format(beanDto.getThresholdAmount().doubleValue() /100) ,df.format(beanDto.getDiscountAmount().doubleValue() / 100)));
                }
                shoppingCartGoodsResponseVo.setDeliveryAmount(calculationDiscountResult.getDeliveryAmount());
                shoppingCartGoodsResponseVo.setDiscountDeliveryAmount(calculationDiscountResult.getDistributionFee());
                shoppingCartGoodsResponseVo.setThresholdAmount(discount.getThresholdAmount());
                shoppingCartGoodsResponseVo.setIsDiscountDelivery(true);
            }else{
                // fisherman 老算价, deliverAmount 不包含 nightDistributionFee 但是页面需要展示总价 所以 这里相加一下 做处理
                Long deliverAmountNew = deliveryAmount + nightDistributionFee;
                if (activityResponse!=null) {

                    if(beanDto.getBenefitType() == 1){
                        String desc = DELIVERY_DISCOUNT_DESC2;
                        shoppingCartGoodsResponseVo.setDeliveryDiscountDesc(String.format(desc, df.format(beanDto.getThresholdAmount().doubleValue() /100) ));
                    }else{
                        String desc = DELIVERY_DISCOUNT_DESC1;
                        shoppingCartGoodsResponseVo.setDeliveryDiscountDesc(String.format(desc, df.format(beanDto.getThresholdAmount().doubleValue() /100 ),df.format(beanDto.getDiscountAmount().doubleValue() / 100)));
                    }

                    shoppingCartGoodsResponseVo.setDeliveryAmount(deliverAmountNew);
                    shoppingCartGoodsResponseVo.setDiscountDeliveryAmount(deliverAmountNew);
                    shoppingCartGoodsResponseVo.setIsDiscountDelivery(false);

                } else {
                    String desc = DELIVERY_DISCOUNT_DESC3;
                    shoppingCartGoodsResponseVo.setDeliveryDiscountDesc(String.format(desc, df.format(deliverAmountNew.doubleValue() / 100)));
                    shoppingCartGoodsResponseVo.setDeliveryAmount(deliverAmountNew);
                    shoppingCartGoodsResponseVo.setDiscountDeliveryAmount(deliverAmountNew);
                    shoppingCartGoodsResponseVo.setIsDiscountDelivery(false);
                }
            }
        }

        /**
         * 加料
         */
        MaterialPromotionService materialPromotionService = (MaterialPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.Material);
        materialPromotionService.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, userLoginInfoDto, shoppingCartInfoRequestVo);

    }

    /**
     * 去除非活动商品的提示
     *
     * @param shoppingCartGoodsResponseVo
     * @param cartUid
     */
    public void clearMsg(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, String cartUid) {
        if (StringUtils.isNotBlank(shoppingCartGoodsResponseVo.getToastMsg()) && StringUtils.isNotBlank(shoppingCartGoodsResponseVo.getUid()) && !cartUid.equals(shoppingCartGoodsResponseVo.getUid())) {
            shoppingCartGoodsResponseVo.setUid("");
            shoppingCartGoodsResponseVo.setToastMsg("");
        }
    }

    /**
     * 组装添加商品和更新商品和查询的响应信息
     * <p>
     * 查询购物车计算包装费
     *
     * @param shoppingCartGoodsResponseVo
     * @param calculationDiscountResult
     * @param cartGoodsList
     * @param toastMsg
     * @param userId
     * @param opt
     * @param shoppingCartInfoRequestVo
     */
    public void setAddAndUpdateResponse(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, CalculationDiscountResult calculationDiscountResult
            , List<CartGoods> cartGoodsList, String toastMsg, String partnerId, String storeId, String userId, String opt, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        shoppingCartGoodsResponseVo.setProducts(cartGoodsList);
        shoppingCartGoodsResponseVo.setProductsCount(cartGoodsList.size());
        if (StringUtils.isNotEmpty(toastMsg)) {
            toastMsg=shoppingCartInfoRequestVo!=null && ObjectUtils.equals(SubmitPageEnum.YES.getCode(), shoppingCartInfoRequestVo.getFlag())?SHOPPING_CART_EMPTY_GOODS_LIST:SHOPPING_CART_INVALIAD_GOODS;
            setToastMsgIfNotExist(shoppingCartGoodsResponseVo, toastMsg);
            //结算页，只有商品全部非法（即products为空）时，才提示changed为true toastMsg 不为空
            if (shoppingCartInfoRequestVo!=null && ObjectUtils.equals(SubmitPageEnum.YES.getCode(), shoppingCartInfoRequestVo.getFlag())){
                shoppingCartGoodsResponseVo.setChanged(CollectionUtils.isEmpty(cartGoodsList));
                shoppingCartGoodsResponseVo.setToastMsg(CollectionUtils.isEmpty(cartGoodsList)?toastMsg:"");
            }

        }
        // 更新和添加商品时不需要包装费
        if (ShoppingCartConstant.ADD_AND_UPDATE.equals(opt)) {
            shoppingCartGoodsResponseVo.setNewPackAmount(null);
            return;
        }
        //==========================  购物车查询特有逻辑  =================================
        // 到店自取包装费设为null,外卖要计算包装费，flag为1表示去结算
        // 兼容老版本判断null
        if (Objects.equals(shoppingCartInfoRequestVo.getOrderType(), CreateOrderType.COLLECT_GOODS.getCode())
                && (Objects.equals(shoppingCartInfoRequestVo.getReachStoreType(), null)
                || Objects.equals(shoppingCartInfoRequestVo.getReachStoreType(), OrderType.EAT_IN.getCode()))) {
            shoppingCartGoodsResponseVo.setNewPackAmount(null);
        } else if ((Objects.equals(shoppingCartInfoRequestVo.getOrderType(), CreateOrderType.TAKE_OUT.getCode())
                || Objects.equals(shoppingCartInfoRequestVo.getReachStoreType(), OrderType.COLLECT_GOODS.getCode()))
                && Objects.equals(shoppingCartInfoRequestVo.getFlag(), SubmitPageEnum.YES.getCode())) {
            Long packAmount = shoppingCartGoodsResponseVo.getNewPackAmount() == null ? 0 : shoppingCartGoodsResponseVo.getNewPackAmount();
            Long originalTotalAmount = shoppingCartGoodsResponseVo.getOriginalTotalAmount() + packAmount;
            Long totalAmount = shoppingCartGoodsResponseVo.getTotalAmount() + packAmount;
            shoppingCartGoodsResponseVo.setOriginalTotalAmount(originalTotalAmount);
            shoppingCartGoodsResponseVo.setTotalAmount(totalAmount);
        }

    }

    /**
     * 埋点添加购物车行为
     *
     * @param addShoppingCartGoodsRequestVo
     * @param spuId
     * @param productName
     */
    public void buriedPointShoppingCart(AddShoppingCartGoodsRequestVo addShoppingCartGoodsRequestVo, String spuId, String productName) {
        if (StringUtils.isEmpty(productName)) {
            return;
        }

        List<ShoppingCartSkuAddRequestVo.ShoppingCartSkuProductVo> productVos = Lists.newArrayList();
        ShoppingCartSkuAddRequestVo.ShoppingCartSkuProductVo productVo = new ShoppingCartSkuAddRequestVo.ShoppingCartSkuProductVo();
        productVo.setProductName(productName);
        productVo.setProductId(spuId);
        productVo.setSpuId(spuId);
        productVos.add(productVo);
        BuriedPointShoppingCartRequestDto shoppingCartRequestDto = BuriedPointShoppingCartRequestDto.builder()
                .sessionId(addShoppingCartGoodsRequestVo.getSessionId()).partnerId(addShoppingCartGoodsRequestVo.getPartnerId())
                .storeId(addShoppingCartGoodsRequestVo.getShopId()).build();
//        buriedPointService.buriedPointAddShoppingCart(productVos, shoppingCartRequestDto);
    }

    /**
     * 检查购物车商品库存数量
     *
     * @param updateShoppingCartGoodsQtyRequestVo
     * @param cartGoods
     */
    public void checkUpdateStock(UpdateShoppingCartGoodsQtyRequestVo updateShoppingCartGoodsQtyRequestVo, CartGoods cartGoods) {
        Integer qty = updateShoppingCartGoodsQtyRequestVo.getQty();
        // 购物车商品数量减少
        if (cartGoods.getQty() > qty) {
            return;
        }
        String partnerId = updateShoppingCartGoodsQtyRequestVo.getPartnerId();
        String storeId = updateShoppingCartGoodsQtyRequestVo.getShopId();
        //查询商品信息
        List<String> pids = new ArrayList<>();
        pids.add(cartGoods.getGoodsId());
        Map<String, GetProductsVo> products = itemService.getProducts(pids, partnerId, storeId, BusinessTypeEnum.getByType(updateShoppingCartGoodsQtyRequestVo.getMenuType()).getCode());

        GetProductsVo getProductsVo = products.get(cartGoods.getGoodsId());
        // 商品没有库存限制
        if (getProductsVo == null || getProductsVo.getStockLimit() != 1) {
            return;
        }

        ShoppingCartConvertAdapter.setClassification(cartGoods, getProductsVo);
        GetProductStockRequestDto requestDto = new GetProductStockRequestDto();
        requestDto.setChannel(BusinessTypeEnum.getByType(updateShoppingCartGoodsQtyRequestVo.getMenuType()).getCode());
        requestDto.setPartnerId(partnerId);
        requestDto.setStoreId(storeId);
        requestDto.setProductIds(Collections.singletonList(Long.parseLong(cartGoods.getGoodsId())));
        GetProductStockResponseDto availableStocks = stockClient.getAvailableStocks(requestDto);
        if ((availableStocks != null) && (ResponseCodeConstant.RESPONSE_SUCCESS_STR.equals(availableStocks.getCode()))) {
            if ((CollectionUtils.isEmpty(availableStocks.getResult())) || (availableStocks.getResult().get(0).getQty() != null &&
                    qty > availableStocks.getResult().get(0).getQty())) {
                Integer stock = 0;
                if (!CollectionUtils.isEmpty(availableStocks.getResult()) && (stock = availableStocks.getResult().get(0).getQty()) > 0) {
                    throw new BizServiceException(ResponseResult.SHOPPING_CART_STOCK_NOT_HAVE, "仅剩" + stock + "件库存了");
                }
                throw new ServiceException(ResponseResult.SHOPPING_CART_STOCK_NOT_HAVE);
            }
        }
    }


    /**
     * 在原价、现价、折扣价上增加第一次使用会员卡的费用
     *
     * @param shoppingCartInfoRequestVo
     * @param shoppingCartGoodsResponseVo
     */
    public void addNeedCardAmount(ShoppingCartInfoRequestVo shoppingCartInfoRequestVo, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo) {
        ShoppingCartInfoRequestVo.BuyMemberCard buyMemberCard = shoppingCartInfoRequestVo.getBuyMemberCard();
        if (shoppingCartInfoRequestVo.getBuyMemberCard() == null || StringUtils.isEmpty(buyMemberCard.getPaidId()) || StringUtils.isEmpty(buyMemberCard.getRuleId())) {
            return;
        }
        GetPaidRuleRequestDto getPaidRuleRequestDto = new GetPaidRuleRequestDto();
        getPaidRuleRequestDto.setPartnerId(shoppingCartInfoRequestVo.getPartnerId());
        getPaidRuleRequestDto.setPaidId(buyMemberCard.getPaidId());
        getPaidRuleRequestDto.setRuleId(buyMemberCard.getRuleId());
        BaseResponse<GetPaidRuleResponseDto> baseResponse = customerApplicationClient.getPaidRule(getPaidRuleRequestDto);
        if (baseResponse == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode()) || baseResponse.getResult() == null
                || baseResponse.getResult().getActivityPrice() == null) {
            return;
        }
        // 购买会员卡的金额
        Integer activityPrice = baseResponse.getResult().getActivityPrice();
        // 首次使用会员卡享受的折扣金额
        Integer firstCouponAmount = baseResponse.getResult().getFirstCouponAmount() == null ? 0 : baseResponse.getResult().getFirstCouponAmount();
        Long originalTotalAmount = shoppingCartGoodsResponseVo.getOriginalTotalAmount() + activityPrice;
        Long totalAmount = shoppingCartGoodsResponseVo.getTotalAmount() + (activityPrice - firstCouponAmount);
        Long totalDiscountAmount = shoppingCartGoodsResponseVo.getTotalDiscountAmount() + firstCouponAmount;
        shoppingCartGoodsResponseVo.setOriginalTotalAmount(originalTotalAmount);
        shoppingCartGoodsResponseVo.setTotalAmount(totalAmount);
        shoppingCartGoodsResponseVo.setTotalDiscountAmount(totalDiscountAmount);
        shoppingCartGoodsResponseVo.setCardOriginalAmount(activityPrice);
        shoppingCartGoodsResponseVo.setCardDiscountAmount(firstCouponAmount);
    }

    /**
     * 处理加价购商品
     *
     * @param sendGoodsList
     * @param partnerId
     * @param storeId
     */
    public void processSendGoods(List<ShoppingCartInfoRequestVo.SendGoods> sendGoodsList
            , String partnerId, String storeId,String menuType, ShoppingCartBaseService shoppingCartService) {
        List<String> goodsIds = sendGoodsList.parallelStream().map(ShoppingCartInfoRequestVo.SendGoods::getGoodsId).collect(Collectors.toList());
        List<ProductBeanDTO> productBeanList =
                assortmentSdkService.getProductsInfoSdk(partnerId, storeId, goodsIds, menuType, shoppingCartService);
        // 将productBeanList转换为Map，key为pid，即goodsId
        Map<String, ProductBeanDTO> productBeanMap = productBeanList.parallelStream()
                .collect(Collectors.toMap(ProductBeanDTO::getPid, Function.identity(), (k1, k2) -> k1));
        // 遍历购物车进行加个更新
        for (ShoppingCartInfoRequestVo.SendGoods sendGoods : sendGoodsList) {
            ProductBeanDTO productBean;
            if ((productBean = productBeanMap.get(sendGoods.getGoodsId())) != null) {
                // 设置加价购商品原价
                sendGoods.setOriginalPrice(productBean.getFinalPrice());
            } else {
                throw new ServiceException(ResponseResult.SHOPPING_CART_SENDGOODS_NOT_EXIST);
            }
        }

    }

    public void packgeAdditional(ShoppingCartInfoRequestVo shoppingCartInfoRequestVo, CreateOrderVo.PremiumExchangeActivity premiumExchangeActivity) {

        ArrayList<ShoppingCartInfoRequestVo.SendGoods> senGoods = new ArrayList<>();
        if (premiumExchangeActivity != null && CollectionUtils.isNotEmpty(premiumExchangeActivity.getProducts())) {

            for (CreateOrderVo.PremiumExchangeActivity.Product product : premiumExchangeActivity.getProducts()) {
                ShoppingCartInfoRequestVo.SendGoods sendGoods = new ShoppingCartInfoRequestVo.SendGoods();
                sendGoods.setQty(product.getQty());
                sendGoods.setGoodsId(StringUtils.isEmpty(product.getSkuId()) ? product.getSpuId() : product.getSkuId());
                senGoods.add(sendGoods);
            }
        }
        shoppingCartInfoRequestVo.setSendGoods(senGoods);
    }

    /**
     * 促销均摊计算
     *
     * @param shoppingCartGoodsResponseVo
     * @param calculationDiscountResult
     * @param shoppingCartGoodsDto
     * @param premiumExchangeActivity
     * @param shoppingCartInfoRequestVo
     */
    public void updateShoppingCartGoodsApportion(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, CalculationDiscountResult calculationDiscountResult, ShoppingCartGoodsDto shoppingCartGoodsDto, CreateOrderVo.PremiumExchangeActivity premiumExchangeActivity, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        DefaultPromotionService defaultPromotionService = (DefaultPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.DEFAULT_PROMOTION);
        defaultPromotionService.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto, premiumExchangeActivity, shoppingCartInfoRequestVo);

        // 优惠券
        CouponPromotionService couponPromotionService = (CouponPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.COUPON_DISCOUNT);
        couponPromotionService.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto, premiumExchangeActivity, shoppingCartInfoRequestVo);

        // 买赠
        BuySendPromotionService buySendPromotionService = (BuySendPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.BUY_ONE_SEND);
        buySendPromotionService.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto, premiumExchangeActivity, shoppingCartInfoRequestVo);

        // 加价购
        AdditionalPromotionService additionalPromotionService = (AdditionalPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.ADDITIONAL_BUY);
        additionalPromotionService.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto, premiumExchangeActivity, shoppingCartInfoRequestVo);

        // 限时特价
        TimeSalePromotionService timeSalePromotionService = (TimeSalePromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.TIME_SALE);
        timeSalePromotionService.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto, premiumExchangeActivity, shoppingCartInfoRequestVo);

        //套餐
        SetMealServiceImpl setMealService = (SetMealServiceImpl) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.SET_MEAL);
        setMealService.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto, premiumExchangeActivity, shoppingCartInfoRequestVo);

        //积分兑换
        CustomerScoreService customerScoreService = (CustomerScoreService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.CUSTOMER_SCORE);
        customerScoreService.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto, premiumExchangeActivity, shoppingCartInfoRequestVo);

        //xy折
        XyDiscountServiceImpl xyDiscountService = (XyDiscountServiceImpl) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.XY_DISCOUNT);
        xyDiscountService.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto, premiumExchangeActivity, shoppingCartInfoRequestVo);

        //xy折
        BuyAndGiftsPromotionService buyAndGiftsPromotionService = (BuyAndGiftsPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.BUY_GIFTS);
        buyAndGiftsPromotionService.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto, premiumExchangeActivity, shoppingCartInfoRequestVo);

        /**
         * 设置加料商品行记录
         */
        MaterialPromotionService materialPromotionService = (MaterialPromotionService) PromotionFactory.getPromotionService(ShoppingCartPromotionEnum.Material);
        materialPromotionService.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscountResult, shoppingCartGoodsDto, premiumExchangeActivity, shoppingCartInfoRequestVo);
    }

    /**
     * 计算第一次使用会员卡需多支付的金额  单位:分
     *
     * @param shoppingCartInfoRequestVo
     * @param shoppingCartGoodsDto
     * @return
     */
    public void getNeedCardAmount(ShoppingCartInfoRequestVo shoppingCartInfoRequestVo, ShoppingCartGoodsDto shoppingCartGoodsDto) {
        ShoppingCartInfoRequestVo.BuyMemberCard buyMemberCard = shoppingCartInfoRequestVo.getBuyMemberCard();
        if (buyMemberCard != null && StringUtils.isNotEmpty(buyMemberCard.getPaidId()) && StringUtils.isNotEmpty(buyMemberCard.getRuleId())) {
            GetPaidRuleRequestDto getPaidRuleRequestDto = new GetPaidRuleRequestDto();
            getPaidRuleRequestDto.setPartnerId(shoppingCartInfoRequestVo.getPartnerId());
            getPaidRuleRequestDto.setPaidId(buyMemberCard.getPaidId());
            getPaidRuleRequestDto.setRuleId(buyMemberCard.getRuleId());
            BaseResponse<GetPaidRuleResponseDto> baseResponse = customerApplicationClient.getPaidRule(getPaidRuleRequestDto);
            if (baseResponse == null || baseResponse.getResult() == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode())
                    || baseResponse.getResult().getActivityPrice() == null) {
                return;
            }
            Integer activityPrice = baseResponse.getResult().getActivityPrice();
            Integer firstCouponAmount = baseResponse.getResult().getFirstCouponAmount()==null?0: baseResponse.getResult().getFirstCouponAmount();
            Integer needCardAmount = activityPrice - firstCouponAmount;
            shoppingCartGoodsDto.setMemberCardAmount(needCardAmount);
            shoppingCartGoodsDto.setCardOriginalAmount(baseResponse.getResult().getActivityPrice());
            shoppingCartGoodsDto.setCardDiscountAmount(firstCouponAmount);
            shoppingCartGoodsDto.setOriginalTotalAmount(shoppingCartGoodsDto.getOriginalTotalAmount() + activityPrice);
            shoppingCartGoodsDto.setTotalAmount(shoppingCartGoodsDto.getTotalAmount() + needCardAmount);
            shoppingCartGoodsDto.setTotalDiscountAmount(shoppingCartGoodsDto.getTotalDiscountAmount() + firstCouponAmount);
        }
    }


}
