package cn.freemud.service.impl;

import cn.freemud.adapter.ActivityAdapter;
import cn.freemud.adapter.CollageOrderAdapter;
import cn.freemud.adapter.CouponAdapter;
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.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.ActivityChannelEnum;
import cn.freemud.enums.ResponseResult;
import cn.freemud.factory.AbstractShoppingCartImpl;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.CommonService;
import cn.freemud.service.CouponService;
import cn.freemud.service.ShoppingCartCollageService;
import cn.freemud.service.ShoppingCartNewService;
import cn.freemud.service.thirdparty.ActivityClient;
import cn.freemud.utils.PropertyConvertUtil;
import cn.freemud.utils.RedisLock;
import cn.freemud.utils.ResponseUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.productcenter.domain.ProductBeanDTO;
import com.freemud.card.sdk.log.ErrorLog;
import com.freemud.sdk.api.assortment.shoppingcart.constant.CommonsConstant;
import com.freemud.sdk.api.assortment.shoppingcart.constant.RedisKeyConstant;
import com.freemud.sdk.api.assortment.shoppingcart.domain.CollageOrder;
import com.freemud.sdk.api.assortment.shoppingcart.domain.CollageOrderDto;
import com.freemud.sdk.api.assortment.shoppingcart.request.CheckCartRequest;
import com.freemud.sdk.api.assortment.shoppingcart.service.impl.CollageCartBaseServiceImpl;
import com.freemud.sdk.api.assortment.shoppingcart.service.impl.ShoppingCartBaseServiceImpl;
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.stereotype.Service;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 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.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目的
 */

@Service
public class ShoppingCartCollageServiceImpl extends AbstractShoppingCartImpl implements ShoppingCartNewService, ShoppingCartCollageService {

    @Autowired
    private AssortmentSdkService assortmentSdkService;

    @Autowired
    private CollageCartBaseServiceImpl collageCartBaseService;

    @Autowired
    private ShoppingCartBaseServiceImpl shoppingCartBaseService;

    @Autowired
    private ActivityAdapter activityAdapter;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private CouponService couponService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private ActivityClient activityClient;

    @Autowired
    private CouponAdapter couponAdapter;



    @Override
    public BaseResponse addGoodsByCard(AddGoodsByWeixinCardRequestVo request) {
        return null;
    }

    @Override
    public BaseResponse addGoods(AddShoppingCartGoodsRequestVo addShoppingCartGoodsRequestVo) {

        ShoppingCartConvertAdapter.convent2SkuId(addShoppingCartGoodsRequestVo);
        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();

        // 获取当前登陆用户信息
        CustomerInfoVo currentUserInfoVo = getCustomerInfoVo(addShoppingCartGoodsRequestVo.getSessionId());
        // 当前用户必须登陆
        if (null == currentUserInfoVo || StringUtils.isEmpty(currentUserInfoVo.getMemberId())) {
            throw new ServiceException(ResponseResult.NOT_LOGIN);
        }
        UserLoginInfoDto userLoginInfoDto = convert2UserLoginInfoDto(currentUserInfoVo);

        String currentUserId = currentUserInfoVo.getMemberId();
        String currentSessionId = addShoppingCartGoodsRequestVo.getSessionId();
        String partnerId = addShoppingCartGoodsRequestVo.getPartnerId();
        String storeId = addShoppingCartGoodsRequestVo.getShopId();
        String appId = addShoppingCartGoodsRequestVo.getAppId();
        String spuId = addShoppingCartGoodsRequestVo.getSpuId();
        String skuId = addShoppingCartGoodsRequestVo.getSkuId();
        String goodsId = StringUtils.isEmpty(skuId) ? spuId : skuId;
        String menuType = addShoppingCartGoodsRequestVo.getMenuType();
        Integer orderType = addShoppingCartGoodsRequestVo.getOrderType();
        String receiveId = addShoppingCartGoodsRequestVo.getReceiveId();
        // 获取拼单发起人id
        String crateUserId = addShoppingCartGoodsRequestVo.getCreateCollageUserId();

        // 拼单相关条件校验
        check(partnerId, storeId, crateUserId,spuId,currentSessionId);

        CartGoods cartGoods = ShoppingCartConvertAdapter.convent2CartGoods(addShoppingCartGoodsRequestVo);
        cartGoods.setSessionId(currentSessionId);
        cartGoods.setUserId(currentUserId);

        List<Long> productIds = new ArrayList<>();
        productIds.add(Long.parseLong(goodsId));

        // 获取商品详细信息
        List<ProductBeanDTO> productBeanListSpuClass = assortmentSdkService.getProductsInfoSdk(partnerId, storeId, Collections.singletonList(spuId),addShoppingCartGoodsRequestVo.getMenuType(), this.shoppingCartBaseService);

        // 购物车版本加锁
        dolock(partnerId, storeId, crateUserId,addShoppingCartGoodsRequestVo.getCarVer());
        List<CartGoods> allCartGoodsList = null;
        String productName = null;

        try {
            //缓存中获取购物车商品信息
            allCartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, crateUserId, currentSessionId, null, collageCartBaseService);
            if (CollectionUtils.isEmpty(allCartGoodsList)) {
                allCartGoodsList = new ArrayList<>();
            }

            Integer sumSkuQty = this.sumSkuQty(allCartGoodsList, cartGoods);
            //查询多个商品库存信息
            this.queryManyGoodsStocks(addShoppingCartGoodsRequestVo, productIds, productBeanListSpuClass, skuId, sumSkuQty);
            productName = null;

            //添加非商品券商品
            List<CartGoods> cartGoodsRedisList= addNotProductCouponGoods(addShoppingCartGoodsRequestVo, cartGoods, goodsId, crateUserId, shoppingCartGoodsResponseVo, allCartGoodsList);

            // 更新拼单购物车人员缓存中的的购物车行id集合
            List<String> cartGoodsUids = cartGoodsRedisList.stream().filter(cartGoods1 -> currentSessionId.equals(cartGoods1.getSessionId())).map(CartGoods::getCartGoodsUid).collect(Collectors.toList());
            collageCartBaseService.updateCollageCartGoodsUids(cartGoodsUids,partnerId, storeId, crateUserId,currentSessionId);

            // 当商品数量被设为0时
            if (Objects.equals(cartGoods.getQty(), 0)) {
                assortmentSdkService.updateGoodsQtyBySdk(partnerId, currentUserId, storeId, cartGoods.getCartGoodsUid(), 0, "", collageCartBaseService);
            }

        } catch (Exception e) {
            ErrorLog.errorConvertJson(SDKCommonBaseContextWare.getAppName(), LogThreadLocal.getTrackingNo(), getClass(), "updateGoodsQty:" + e.getMessage(), e);
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_VERSION_ERROR, "购物车商品有变动，请手动刷新再修改");
        }finally {
            // 购物车版本解锁
            // 版本锁的粒度控制在获取购物车、刷新购物车、刷新车人员缓存行
            // 当这些操作结束后，购物的更新操作，已经结束，其他的流程是针对已经添加到redis中的购物车做查询操作
            // 所以只有上述的流程才加锁控制
            doUnlock(partnerId, storeId, crateUserId);
        }

        // 配送费
        Long deliveryAmount = calculateDeliveryAmount(receiveId, partnerId, storeId, userLoginInfoDto.getWxAppid(), shoppingCartGoodsResponseVo);

        // 获取优惠信息
        ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult
                =getCalculationDiscountResult(menuType,partnerId,storeId,currentUserId,appId,userLoginInfoDto.getWxAppid(),orderType,currentUserInfoVo.isMemberPaid(), allCartGoodsList,new ArrayList(),new ArrayList<>(),null,deliveryAmount);

        ActivityQueryDto activityQueryDto = activityAdapter.getActivityQueryDto(partnerId, storeId, currentUserId, appId, addShoppingCartGoodsRequestVo.getOrderType());

        // 促销活动的优惠金额计算
        updateShoppingCartGoodsDiscount(null, activityQueryDto, calculationDiscountResult, allCartGoodsList, shoppingCartGoodsResponseVo, null, userLoginInfoDto, addShoppingCartGoodsRequestVo.getMenuType(), deliveryAmount);
        clearMsg(shoppingCartGoodsResponseVo, cartGoods.getCartGoodsUid());
        //设置更新响应信息
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, calculationDiscountResult, allCartGoodsList, null, partnerId, storeId, currentUserId, ShoppingCartConstant.ADD_AND_UPDATE, null);
        // 设置购物车版本号
        shoppingCartGoodsResponseVo.setCarVer(collageCartBaseService.incrementCartVersion(partnerId, storeId, crateUserId));
        //埋点添加购物车行为
        this.buriedPointShoppingCart(addShoppingCartGoodsRequestVo, spuId, productName);
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    @Override
    public BaseResponse updateGoodsQty(UpdateShoppingCartGoodsQtyRequestVo updateShoppingCartGoodsQtyRequestVo) {


        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(updateShoppingCartGoodsQtyRequestVo.getSessionId());
        UserLoginInfoDto userLoginInfoDto = convert2UserLoginInfoDto(assortmentCustomerInfoVo);
        String currentSessionId = updateShoppingCartGoodsQtyRequestVo.getSessionId();
        String currentUserId = userLoginInfoDto.getMemberId();
        String partnerId = updateShoppingCartGoodsQtyRequestVo.getPartnerId();
        String storeId = updateShoppingCartGoodsQtyRequestVo.getShopId();
        String appId = updateShoppingCartGoodsQtyRequestVo.getAppId();
        String cartGoodsUid = updateShoppingCartGoodsQtyRequestVo.getCartGoodsUid();
        Integer qty = updateShoppingCartGoodsQtyRequestVo.getQty();
        String menuType = updateShoppingCartGoodsQtyRequestVo.getMenuType();
        Integer orderType=updateShoppingCartGoodsQtyRequestVo.getOrderType();
        String receiveId = updateShoppingCartGoodsQtyRequestVo.getReceiveId();

        // 获取拼单发起人id
        String crateUserId = updateShoppingCartGoodsQtyRequestVo.getCreateCollageUserId();

        // 拼单相关条件校验
        check(partnerId, storeId, crateUserId,null,currentSessionId);

        // 购物车版本加锁
        dolock(partnerId, storeId, crateUserId,updateShoppingCartGoodsQtyRequestVo.getCarVer());
        List<CartGoods> cartGoodsList = null;

        try {

            // 先验证商品是否存在
            CartGoods cartGoods = assortmentSdkService.getCartGoodsBySdk(partnerId, crateUserId, storeId, cartGoodsUid, "", collageCartBaseService);
            if (cartGoods == null) {
                throw new ServiceException(ResponseResult.SHOPPING_CART_UPDATE_ERROR);
            }

            // 检查购物车商品库存数量
            checkUpdateStock(updateShoppingCartGoodsQtyRequestVo, cartGoods);

            // 更新购物车中数量
            cartGoodsList = assortmentSdkService.updateGoodsQtyBySdk(partnerId, crateUserId, storeId, cartGoodsUid, qty<0?0:qty, "", collageCartBaseService);

            // check购物车中所有商品
            CheckCartRequest checkCartRequest = assortmentSdkService.checkShoppingCartSdk(cartGoodsList, partnerId, storeId, shoppingCartGoodsResponseVo, updateShoppingCartGoodsQtyRequestVo.getOrderType(), "", updateShoppingCartGoodsQtyRequestVo.getMenuType(), shoppingCartBaseService);
            if (checkCartRequest.getShoppingCartGoodsResponseVo() != null) {
                shoppingCartGoodsResponseVo.setChanged(checkCartRequest.getShoppingCartGoodsResponseVo().getChanged());
                shoppingCartGoodsResponseVo.setToastMsg(checkCartRequest.getShoppingCartGoodsResponseVo().getToastMsg());
            }
            cartGoodsList = JSONArray.parseArray(JSONObject.toJSONString(checkCartRequest.getCartGoodsList()), CartGoods.class);

            // 重新存储最新购物车
            List<CartGoods> cartGoodsRedisList = assortmentSdkService.setShoppingCart(partnerId, storeId, crateUserId, cartGoodsList, currentSessionId, "", collageCartBaseService);

            // 更新拼单购物车人员缓存中的的购物车行id集合
            List<String> cartGoodsUids = cartGoodsRedisList.stream().filter(cartGoods1 -> currentSessionId.equals(cartGoods1.getSessionId())).map(CartGoods::getCartGoodsUid).collect(Collectors.toList());
            collageCartBaseService.updateCollageCartGoodsUids(cartGoodsUids,partnerId, storeId, crateUserId,currentSessionId);

        } catch (Exception e) {
            ErrorLog.errorConvertJson(SDKCommonBaseContextWare.getAppName(), LogThreadLocal.getTrackingNo(), getClass(), "shoppingCartCollageServiceImpl updateGoodsQty:" + e.getMessage(), e);
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_VERSION_ERROR, "购物车商品有变动，请手动刷新再修改");
        }finally {
            // 购物车版本解锁
            // 版本锁的粒度控制在检查购物车、刷新购物车、刷新车人员缓存行
            // 当这些操作结束后，购物的更新操作，已经结束，其他的流程是针对已经添加到redis中的购物车做查询操作
            // 所以只有上述的流程才加锁控制
            doUnlock(partnerId, storeId, crateUserId);
        }


        Long deliveryAmount = calculateDeliveryAmount(receiveId, partnerId, storeId, userLoginInfoDto.getWxAppid(), shoppingCartGoodsResponseVo);
        // 获取优惠信息
        ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult
                =getCalculationDiscountResult(menuType,partnerId,storeId,crateUserId,appId,userLoginInfoDto.getWxAppid(),orderType,assortmentCustomerInfoVo.isMemberPaid(),cartGoodsList,new ArrayList(),new ArrayList<>(),null,deliveryAmount);
        if (calculationDiscountResult == null) {
            shoppingCartGoodsResponseVo.setProducts(cartGoodsList);
//            return shoppingCartGoodsResponseVo;
        }

        ActivityQueryDto activityQueryDto = activityAdapter.getActivityQueryDto(partnerId, storeId, crateUserId, appId, updateShoppingCartGoodsQtyRequestVo.getOrderType());

        // 促销活动的优惠金额计算
        updateShoppingCartGoodsDiscount(null, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, null, userLoginInfoDto, updateShoppingCartGoodsQtyRequestVo.getMenuType(), deliveryAmount);

        clearMsg(shoppingCartGoodsResponseVo, cartGoodsUid);
        //设置更新响应信息
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), partnerId, storeId, crateUserId, ShoppingCartConstant.ADD_AND_UPDATE, null);
        // 设置购物车版本号
        shoppingCartGoodsResponseVo.setCarVer(collageCartBaseService.incrementCartVersion(partnerId, storeId, crateUserId));
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    @Override
    public BaseResponse getGoodsList(ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {

        if (StringUtils.isEmpty(shoppingCartInfoRequestVo.getShopId())){
            throw new ServiceException(ResponseResult.SHOPPING_CART_SHOP_ID_NOT_EMPTY);
        }
        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(shoppingCartInfoRequestVo.getSessionId());
        UserLoginInfoDto userLoginInfoDto = convert2UserLoginInfoDto(assortmentCustomerInfoVo);
        String currentUserId = userLoginInfoDto.getMemberId();
        String currentSessionId = shoppingCartInfoRequestVo.getSessionId();
        String partnerId = shoppingCartInfoRequestVo.getPartnerId();
        String storeId = shoppingCartInfoRequestVo.getShopId();
        String appId = shoppingCartInfoRequestVo.getAppId();
        String couponCode = shoppingCartInfoRequestVo.getCouponCode();
        String activityCode = shoppingCartInfoRequestVo.getActivityCode();
        String menuType = shoppingCartInfoRequestVo.getMenuType();
        Integer orderType = shoppingCartInfoRequestVo.getOrderType();
        String receiveId = shoppingCartInfoRequestVo.getReceiveId();

        // 获取拼单发起人id
        String crateUserId = shoppingCartInfoRequestVo.getCreateCollageUserId();

        // 拼单发起人id不能为空
        // 拼单购物相关的redis的key都需要拼单发起人id，所以这个值是不能为空的
        if (StringUtils.isEmpty(crateUserId)){
            throw new ServiceException(ResponseResult.COLLAGE_NOT_EXIST);
        }

        // 获取不到拼单的基础信息，抛出异常
        // 拼单的有效时间为1小时，当获取不到拼单的基础信息时，认为这个拼单没有发起、已经失效、已经结束
        Map<String, String> collageBase = collageCartBaseService.getCollageBase(partnerId,storeId,crateUserId);
        if(collageBase == null || collageBase.isEmpty()){
            throw new ServiceException(ResponseResult.COLLAGE_NOT_EXIST);
        }

        // 购物车版本加锁
        dolock(partnerId, storeId, crateUserId,shoppingCartInfoRequestVo.getCarVer());
        List<CartGoods> cartGoodsList = null;

        try {
            // 获取购物车商品
            cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, crateUserId, null, "", collageCartBaseService);
            // 如果购物车商品不为空， 则check购物车中所有商品
            if (CollectionUtils.isNotEmpty(cartGoodsList)){
                CheckCartRequest checkCartRequest = assortmentSdkService.checkShoppingCartSdk(cartGoodsList, partnerId, storeId, shoppingCartGoodsResponseVo, shoppingCartInfoRequestVo.getOrderType(), "", shoppingCartInfoRequestVo.getMenuType() ,shoppingCartBaseService);
                if (checkCartRequest.getShoppingCartGoodsResponseVo() != null) {
                    shoppingCartGoodsResponseVo.setChanged(checkCartRequest.getShoppingCartGoodsResponseVo().getChanged());
                    shoppingCartGoodsResponseVo.setToastMsg(checkCartRequest.getShoppingCartGoodsResponseVo().getToastMsg());
                }
                cartGoodsList = JSONArray.parseArray(JSONObject.toJSONString(checkCartRequest.getCartGoodsList()), CartGoods.class);
                // 重新存储最新购物车
                List<CartGoods> cartGoodsRedisList = assortmentSdkService.setShoppingCart(partnerId, storeId, crateUserId, cartGoodsList, assortmentCustomerInfoVo.getSessionId(), "", this.collageCartBaseService);

                // 更新拼单购物车人员缓存中的的购物车行id集合
                List<String> cartGoodsUids = cartGoodsRedisList.stream().filter(cartGoods1 -> currentSessionId.equals(cartGoods1.getSessionId())).map(CartGoods::getCartGoodsUid).collect(Collectors.toList());
                collageCartBaseService.updateCollageCartGoodsUids(cartGoodsUids,partnerId, storeId, crateUserId,currentSessionId);
            }
        } catch (Exception e) {
            ErrorLog.errorConvertJson(SDKCommonBaseContextWare.getAppName(), LogThreadLocal.getTrackingNo(), getClass(), "shoppingCartCollageServiceImpl getGoodsList:" + e.getMessage(), e);
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_VERSION_ERROR, "购物车商品有变动，请手动刷新再修改");
        }finally {
            // 购物车版本解锁
            // 版本锁的粒度控制在检查购物车、刷新购物车、刷新车人员缓存行
            // 当这些操作结束后，购物的更新操作，已经结束，其他的流程是针对已经添加到redis中的购物车做查询操作
            // 所以只有上述的流程才加锁控制
            doUnlock(partnerId, storeId, crateUserId);
        }

        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = new ArrayList<>();
        // 当couponCode不为空时，需参与价格计算
        if (StringUtils.isNotEmpty(couponCode)) {
            ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon coupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
            coupon.setCode(couponCode);
            coupon.setActivityCode(activityCode);
            coupons.add(coupon);
        }
        Long deliveryAmount = calculateDeliveryAmount(receiveId, partnerId, storeId, userLoginInfoDto.getWxAppid(), shoppingCartGoodsResponseVo);

        // 获取优惠信息
        ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult = getCalculationDiscountResult(menuType,partnerId,storeId,crateUserId,appId,userLoginInfoDto.getWxAppid(),orderType,assortmentCustomerInfoVo.isMemberPaid(),cartGoodsList,coupons,null,shoppingCartInfoRequestVo.getReceiveId(),deliveryAmount);

        if (calculationDiscountResult == null) {
            shoppingCartGoodsResponseVo.setProducts(cartGoodsList);
        }

        ActivityQueryDto activityQueryDto = activityAdapter.getActivityQueryDto(partnerId, storeId, crateUserId, appId, shoppingCartInfoRequestVo.getOrderType());

        CouponPromotionVO couponPromotionVO = couponAdapter.getCouponPromotionVO(shoppingCartInfoRequestVo, userLoginInfoDto);
        // 促销活动的优惠金额计算
        this.updateShoppingCartGoodsDiscount(couponPromotionVO, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, shoppingCartInfoRequestVo, userLoginInfoDto,shoppingCartInfoRequestVo.getMenuType(),deliveryAmount);
        //设置更新响应信息
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), partnerId, storeId, crateUserId, ShoppingCartConstant.QUERY_INFO, shoppingCartInfoRequestVo);
        // 在原价、现价、折扣价上增加第一次使用会员卡的费用
        this.addNeedCardAmount(shoppingCartInfoRequestVo, shoppingCartGoodsResponseVo);
        // 设置购物车版本号
        shoppingCartGoodsResponseVo.setCarVer(collageCartBaseService.incrementCartVersion(partnerId, storeId, crateUserId));
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    @Override
    public BaseResponse getGoodsListCheck(ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        return null;
    }

    @Override
    public BaseResponse clear(ShoppingCartClearRequestVo request) {

        // 拼单发起人
        String createCollageUserId = request.getCreateCollageUserId();
        if (StringUtils.isBlank(createCollageUserId)) {
            throw new ServiceException(ResponseResult.COLLAGE_NOT_EXIST);
        }
        String partnerId = request.getPartnerId();
        String storeId = request.getShopId();
        if(StringUtils.isEmpty(partnerId) || StringUtils.isEmpty(storeId)){
            throw new ServiceException(ResponseResult.PARAMETER_MISSING);
        }

        CustomerInfoVo userLoginInfoDto = getCustomerInfoVo(request.getSessionId());
        if(null == userLoginInfoDto || StringUtils.isEmpty(userLoginInfoDto.getMemberId())){
            throw new ServiceException(ResponseResult.NOT_LOGIN);
        }

        com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = new com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto();
        cartParamDto.setPartnerId(partnerId);
        cartParamDto.setStoreId(storeId);
        cartParamDto.setUserId(createCollageUserId);
        collageCartBaseService.clear(cartParamDto, LogThreadLocal.getTrackingNo());
        return ResponseUtil.success();
    }

    @Override
    public BaseResponse<ShoppingCartGoodsDto> getShoppingCartGoods(ShoppingCartInfoRequestVo shoppingCartInfoRequestVo, CreateOrderVo.PremiumExchangeActivity premiumExchangeActivity) {
        return null;
    }

    @Override
    public ActivityCalculationDiscountResponseDto.CalculationDiscountResult getActivityCalculationDiscountResponse(String partnerId, String storeId, String userId, String appId, Integer orderType, boolean isMember, List<CartGoods> cartGoodsList, List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons, List<ShoppingCartInfoRequestVo.SendGoods> sendGoodsList, String menuType, Long distributionFee) {
        ActivityCalculationDiscountRequestDto activityCalculationDiscountRequestDto = getActivityCalculationDiscountRequestDto(partnerId, storeId, userId, appId, orderType);
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountGoods> calculationDiscountGoodsList = new ArrayList<>();
        // 校验后有效的商品券map
        Map<String, CheckSpqInfoResponseDto> validCouponMap = new HashMap<>(16);
        for (int i = cartGoodsList.size() - 1; i >= 0; i--) {
            CartGoods cartGoods = cartGoodsList.get(i);
            String cartGoodsUid = cartGoods.getCartGoodsUid();
            // 商品不是商品券
            if (!cartGoodsUid.startsWith(CommonsConstant.COUPON_PREFIX)) {
                //this.addCalculationDiscountGoods(calculationDiscountGoodsList, cartGoods.getGoodsId(), cartGoods.getQty(), cartGoods.getFinalPrice(), cartGoods.getMemberDiscount(), cartGoodsUid);
                this.addCalculationDiscountGoods(calculationDiscountGoodsList, cartGoods);
            }
            // 商品是商品券
            else {
                // 商品券ID换取商品
                String spqId = cartGoods.getCartGoodsUid().substring(CommonsConstant.COUPON_PREFIX.length());
                CheckSpqInfoRequestDto checkSpqInfoRequestDto = new CheckSpqInfoRequestDto(partnerId, storeId, spqId,menuType);
                CheckSpqInfoResponseDto checkSpqInfoResponseDto = couponService.checkSpqInfo(checkSpqInfoRequestDto);
                // 商品券不存在时，将商品券从购物车移除
                if (checkSpqInfoResponseDto == null) {
                    cartGoodsList.remove(i);
                    assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, null, null, this.shoppingCartBaseService);
                    throw new ServiceException(ResponseResult.SHOPPING_CART_COUPON_NOT_EXIST);
                }
                validCouponMap.put(spqId, checkSpqInfoResponseDto);
                cartGoods.setName(checkSpqInfoResponseDto.getCouponName());
                cartGoods.setSpuName(checkSpqInfoResponseDto.getCouponName());
                // 添加请求的优惠券信息
                ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon coupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
                coupon.setCode(checkSpqInfoResponseDto.getCouponCode());
                coupon.setActivityCode(checkSpqInfoResponseDto.getActiveCode());
                coupons.add(coupon);
                // 添加商品券代表的商品
                String goodsId = StringUtils.isEmpty(checkSpqInfoResponseDto.getSkuId()) ? checkSpqInfoResponseDto.getSpuId() : checkSpqInfoResponseDto.getSkuId();
                this.addCalculationDiscountGoods(calculationDiscountGoodsList, goodsId, 1, checkSpqInfoResponseDto.getPrice(), 100, cartGoodsUid);
            }
        }
        // 当加价购商品不为空时
        if (CollectionUtils.isNotEmpty(sendGoodsList)) {
            for (ShoppingCartInfoRequestVo.SendGoods sendGoods : sendGoodsList) {
                this.addCalculationDiscountGoods(calculationDiscountGoodsList, sendGoods.getGoodsId(), sendGoods.getQty(), sendGoods.getOriginalPrice(), 100, "");
            }
        }
        calculationDiscountGoodsList.removeIf(calculationDiscountGoods -> (calculationDiscountGoods.getGoodsQuantity().equals(0)));
        if (CollectionUtils.isEmpty(calculationDiscountGoodsList)) {
            return null;
        }
        activityCalculationDiscountRequestDto.setGoods(calculationDiscountGoodsList);
        activityCalculationDiscountRequestDto.setCoupons(coupons);
        activityCalculationDiscountRequestDto.setOrgIds(commonService.getOrgIds(partnerId, storeId));
        activityCalculationDiscountRequestDto.setDistributionFee(distributionFee);
        activityCalculationDiscountRequestDto.setIsMember(isMember);
        ActivityCalculationDiscountResponseDto activityCalculationDiscountResponseDto;
        try {
            System.out.println("start discount");
            System.out.println(JSON.toJSONString(activityCalculationDiscountRequestDto));
            activityCalculationDiscountResponseDto = activityClient.calculationDiscount(activityCalculationDiscountRequestDto);
        } catch (Exception ex) {
            com.freemud.application.sdk.api.log.ErrorLog.printErrorLog("calculation_discount_error", "/calculation/discount", activityCalculationDiscountRequestDto, ex);
            throw new ServiceException(ResponseResult.OPERATE_TOO_OFTEN);
        }
        // 返回成功
        if (activityCalculationDiscountResponseDto != null && StringUtils.equals(activityCalculationDiscountResponseDto.getStatusCode(), ResponseCodeConstant.RESPONSE_SUCCESS_STR)) {
            ActivityCalculationDiscountResponseDto.CalculationDiscountResult result = activityCalculationDiscountResponseDto.getResult();
            result.setValidCouponMap(validCouponMap);
            result.setDeliveryAmount(distributionFee);
            result.setDistributionFee(result.getDistributionFee());
            return result;
        }
        // 支付宝华莱士紧急修改代码，当促销返回103错误码时，需要报券不适用于该门店，且清空购物车
        ShoppingCartClearRequestVo shoppingCartClearRequestVo = new ShoppingCartClearRequestVo();
        shoppingCartClearRequestVo.setAppId(appId);
        shoppingCartClearRequestVo.setPartnerId(partnerId);
        shoppingCartClearRequestVo.setUserId(userId);
        shoppingCartClearRequestVo.setShopId(storeId);
        shoppingCartClearRequestVo.setOperationType(1);
        clear(shoppingCartClearRequestVo);
        if (activityCalculationDiscountResponseDto != null && StringUtils.equals(activityCalculationDiscountResponseDto.getStatusCode(), "103")){
            throw new ServiceException(ResponseResult.SHOPPING_CART_COUPON_CAN_NOT_USE_THIS_SHOP);
        }
        throw new ServiceException(ResponseResult.OPERATE_TOO_OFTEN);
    }

    @Override
    public List<CartGoods> updateCartGoodsLegal(CartGoods cartGoods, String userId, ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo, AddShoppingCartGoodsRequestVo addShoppingCartGoodsRequestVo, List<CartGoods> oldAllCartGoodsList) {
        //存储新添加的购物车信息
        List<CartGoods> nowCartGoodsList = new ArrayList<>();
        oldAllCartGoodsList.add(cartGoods);

        //当商品全部添加完毕,校验购物车商品(是否合法,上下架,点餐方式,是否在当前菜单中...),并移除非法商品
        CheckCartRequest checkCartRequest = assortmentSdkService.checkShoppingCartSdk(oldAllCartGoodsList, addShoppingCartGoodsRequestVo.getPartnerId(),
                addShoppingCartGoodsRequestVo.getShopId(), shoppingCartGoodsResponseVo, addShoppingCartGoodsRequestVo.getOrderType(),
                "", addShoppingCartGoodsRequestVo.getMenuType(),shoppingCartBaseService);
        if (checkCartRequest.getShoppingCartGoodsResponseVo() != null) {
            shoppingCartGoodsResponseVo.setToastMsg(checkCartRequest.getShoppingCartGoodsResponseVo().getToastMsg());
            shoppingCartGoodsResponseVo.setChanged(checkCartRequest.getShoppingCartGoodsResponseVo().getChanged());
        }
        List<CartGoods> allCartGoodsList = JSONArray.parseArray(JSONObject.toJSONString(checkCartRequest.getCartGoodsList()), CartGoods.class);

        //判断当前商品在购物车是否已存在,存在则数量＋1,不存在商品行 + 1
        allCartGoodsList.forEach(oldCartGoods -> {
            int index;
            if ((index = nowCartGoodsList.indexOf(oldCartGoods)) >= 0) {
                nowCartGoodsList.get(index).setQty(nowCartGoodsList.get(index).getQty() + cartGoods.getQty());
            } else {
                nowCartGoodsList.add(oldCartGoods);
            }
        });
        // 重新set购物车信息到缓存中
        assortmentSdkService.setShoppingCart(addShoppingCartGoodsRequestVo.getPartnerId(), addShoppingCartGoodsRequestVo.getShopId(),
                userId, nowCartGoodsList, addShoppingCartGoodsRequestVo.getSessionId(), addShoppingCartGoodsRequestVo.getTableNumber(), this.collageCartBaseService);
        oldAllCartGoodsList.clear();
        oldAllCartGoodsList.addAll(nowCartGoodsList);
        return nowCartGoodsList;
    }

    public List<CartGoods> getShoppingCart(AddShoppingCartGoodsRequestVo addShoppingCartGoodsRequestVo) {
        return null;
    }


    /**
     * 添加非商品券商品
     *
     * @param addShoppingCartGoodsRequestVo
     * @param cartGoods
     * @param goodsId
     * @param userId
     * @param shoppingCartGoodsResponseVo
     * @param allCartGoodsList
     */
    public List<CartGoods> addNotProductCouponGoods(AddShoppingCartGoodsRequestVo addShoppingCartGoodsRequestVo, CartGoods cartGoods
            , String goodsId, String userId, ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo, List<CartGoods> allCartGoodsList) {

        // 校验合法性,更新缓存中购物车信息
        List<CartGoods> cartGoodsList = updateCartGoodsLegal(cartGoods, userId, shoppingCartGoodsResponseVo, addShoppingCartGoodsRequestVo, allCartGoodsList);

        // 如果购物车中有商品券，则当前添加的商品是特价商品时，需要提示“已选商品券，与其他优惠商品不同享，商品将恢复原价”
        // 拼单没有商品券、换购券
        return cartGoodsList;
    }

    /**
     * 拼单相关校验<br/>
     * 1、店铺id不能为空<br/>
     * 2、拼单不支持用商品券、换购券<br/>
     * 3、拼单发起人id不能为空<br/>
     * 4、拼单的基础信息不能为空<br/>
     * 5、判断拼单的锁定状态<br/>
     * 6、判单拼单的点餐位是否存在<br/>
     * 7、校验用户选好了状态
     * @param partnerId
     * @param storeId
     * @param crateUserId
     * @param spuId
     * @param currentSessionId
     */
        public void check(String partnerId,String storeId,String crateUserId,String spuId,String currentSessionId){

        //店铺id不能为空
        if (StringUtils.isEmpty(storeId)){
            throw new ServiceException(ResponseResult.SHOPPING_CART_SHOP_ID_NOT_EMPTY);
        }

        //拼单不支持用商品券、换购券
        if (null != spuId && spuId.startsWith(CommonsConstant.COUPON_PREFIX)){
            throw new ServiceException(ResponseResult.COUPON_SHOP_NOTSUPPORT);
        }
        // 拼单发起人id不能为空
        // 拼单购物相关的redis的key都需要拼单发起人id，所以这个值是不能为空的
        if (StringUtils.isEmpty(crateUserId)){
            throw new ServiceException(ResponseResult.COLLAGE_NOT_EXIST);
        }

        // 获取不到拼单的基础信息，抛出异常
        // 拼单的有效时间为1小时，当获取不到拼单的基础信息时，认为这个拼单没有发起、已经失效、已经结束
        Map<String, String> collageBase = collageCartBaseService.getCollageBase(partnerId,storeId,crateUserId);
        if(collageBase == null || collageBase.isEmpty()){
            throw new ServiceException(ResponseResult.COLLAGE_NOT_EXIST);
        }

        // 获取拼单的锁定状态，锁定，抛出异常
        // 发起人支付的时候需要对拼单进行锁定，当已锁定的时候，不能操作购物车
        Boolean collageLock = collageCartBaseService.getCollageLock(partnerId,storeId,crateUserId);
        if(collageLock != null && collageLock){
            throw new ServiceException(ResponseResult.COLLAGE_LOCK);
        }

        // 判单拼单的点餐位是否存在
        // 发起拼单、加入拼单，都会给用户创建点餐位，用来存储用户的购物车行id
        // 并设置其相应的购物车行id为空集合，没有点餐位，则认为该用户是没有加入拼单
        List<String> cartGoodsUids = collageCartBaseService.getCollageMemberHashKey(partnerId, storeId,crateUserId ,currentSessionId);
        if(cartGoodsUids == null){
            throw new ServiceException(ResponseResult.COLLAGE_NOT_ADD);
        }

        // 校验用户选好了状态
        // 只有用户不是选好了状态的时候才能更改购物车
        Boolean memberState = collageCartBaseService.getCollageMemStateHashKey(partnerId, storeId, crateUserId,currentSessionId);
        if(memberState != null && memberState){
            throw new ServiceException(ResponseResult.COLLAGE_ALREADY_CHOOSE);
        }

    }

    /**
     * 购物车版本锁检查和加锁
     * @param partnerId
     * @param storeId
     * @param crateUserId
     * @param carVer
     */
    private void dolock(String partnerId,String storeId,String crateUserId,Integer carVer) {
        // 设置版本锁控制购物车只能一个人进行操作
        if (carVer == null || carVer < 1) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_VERSION_ERROR);
        }
        // 构建拼单购物车版本号缓存key
        String collageCartVerKey = genCollageCarVerKey(partnerId, storeId, crateUserId);
        Integer cartVersion = collageCartBaseService.getCartVersion(collageCartVerKey);
        if (!carVer.equals(cartVersion)) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_VERSION_ERROR);
        }

        boolean lock = RedisLock.getInstance(redisCache.getRedisTemplate()).lock(collageCartVerKey);
        if (!lock) {
            //加锁失败
            throw new ServiceException(ResponseResult.SHOPPING_CART_VERSION_ERROR);
        }
    }

    /**
     * 购物车版本解锁
     * @param partnerId
     * @param storeId
     * @param crateUserId
     */
    private void doUnlock(String partnerId,String storeId,String crateUserId) {
        try {
            String collageCartVerKey = genCollageCarVerKey(partnerId, storeId, crateUserId);
            RedisLock.getInstance(redisCache.getRedisTemplate()).unlock(collageCartVerKey);
        } catch (Exception e) {
            ErrorLog.errorConvertJson(SDKCommonBaseContextWare.getAppName(), LogThreadLocal.getTrackingNo(), getClass(), "购物车版本解锁解锁失败" , e);
        }
    }

    /**
     * 构建拼单购物车版本号缓存key
     * @param partnerId
     * @param storeId
     * @param userId
     * @return
     */
    private String genCollageCarVerKey(String partnerId, String storeId, String userId) {
        return MessageFormat.format(RedisKeyConstant.COLLAGE_CART_VER_KEY, partnerId, storeId, userId);
    }

    /**
     * 构建 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;
    }

    /**
     * 促销增加
     *
     * @param calculationDiscountGoodsList
     * @param cartGoods
     */
    private void addCalculationDiscountGoods(List<ActivityCalculationDiscountRequestDto.CalculationDiscountGoods> calculationDiscountGoodsList, CartGoods cartGoods) {
        ActivityCalculationDiscountRequestDto.CalculationDiscountGoods calculationDiscountGoods = new ActivityCalculationDiscountRequestDto.CalculationDiscountGoods();

        calculationDiscountGoods.setGoodsId(cartGoods.getGoodsId());
        calculationDiscountGoods.setCartGoodsUid(cartGoods.getCartGoodsUid());
        calculationDiscountGoods.setGoodsQuantity(cartGoods.getQty());
        calculationDiscountGoods.setOriginalPrice(cartGoods.getFinalPrice());
        calculationDiscountGoods.setMemberDiscount(cartGoods.getMemberDiscount());
        calculationDiscountGoods.setSpuId(cartGoods.getSpuId());

        //加料
        if (CollectionUtils.isNotEmpty(cartGoods.getProductMaterialList())) {
            new ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material();
            ArrayList<ActivityCalculationDiscountRequestDto.CalculationDiscountGoods.Material> materials = new ArrayList<>();
            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(materialGoods.getFinalPrice());
                materials.add(material);
            }
            calculationDiscountGoods.setSmallMaterial(materials);
        }
        this.addCalculationDiscountGoods(calculationDiscountGoodsList, calculationDiscountGoods);
    }


    /**
     * 将calculationDiscountGoods 封装后加入 calculationDiscountGoodsList
     *
     * @param calculationDiscountGoodsList
     * @param goodsId
     * @param goodsQuantity
     * @param originalPrice
     */
    private void addCalculationDiscountGoods(List<ActivityCalculationDiscountRequestDto.CalculationDiscountGoods> calculationDiscountGoodsList,
                                             String goodsId, Integer goodsQuantity, Long originalPrice, Integer memberDiscount, String cartGoodsUid) {
        ActivityCalculationDiscountRequestDto.CalculationDiscountGoods calculationDiscountGoods = new ActivityCalculationDiscountRequestDto.CalculationDiscountGoods();
        calculationDiscountGoods.setGoodsId(goodsId);
        calculationDiscountGoods.setCartGoodsUid(cartGoodsUid);
        calculationDiscountGoods.setGoodsQuantity(goodsQuantity);
        calculationDiscountGoods.setOriginalPrice(originalPrice);
        calculationDiscountGoods.setMemberDiscount(memberDiscount);
        this.addCalculationDiscountGoods(calculationDiscountGoodsList, calculationDiscountGoods);
    }

    /**
     * 累加需加入计算的商品
     *
     * @param calculationDiscountGoodsList
     * @param calculationDiscountGoods
     */
    private void addCalculationDiscountGoods(List<ActivityCalculationDiscountRequestDto.CalculationDiscountGoods> calculationDiscountGoodsList,
                                             ActivityCalculationDiscountRequestDto.CalculationDiscountGoods calculationDiscountGoods) {
        int index;
        // 当商品已存在时,需累加数量
        if ((index = calculationDiscountGoodsList.indexOf(calculationDiscountGoods)) >= 0) {
            ActivityCalculationDiscountRequestDto.CalculationDiscountGoods oldCalculationDiscountGoods = calculationDiscountGoodsList.get(index);
            oldCalculationDiscountGoods.setGoodsQuantity(oldCalculationDiscountGoods.getGoodsQuantity() + calculationDiscountGoods.getGoodsQuantity());
        } else {
            calculationDiscountGoodsList.add(calculationDiscountGoods);
        }
    }

    @Override
    public BaseResponse clearPartCarGoods(ShoppingCartCollageClearRequestVo shoppingCartCollageClearRequestVo) {

        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(shoppingCartCollageClearRequestVo.getSessionId());
        UserLoginInfoDto userLoginInfoDto = convert2UserLoginInfoDto(assortmentCustomerInfoVo);
        String currentUserId = userLoginInfoDto.getMemberId();
        String currentSessionId = shoppingCartCollageClearRequestVo.getSessionId();
        String partnerId = shoppingCartCollageClearRequestVo.getPartnerId();
        String storeId = shoppingCartCollageClearRequestVo.getShopId();
        String appId = shoppingCartCollageClearRequestVo.getAppId();
        String menuType = shoppingCartCollageClearRequestVo.getMenuType();
        Integer orderType=shoppingCartCollageClearRequestVo.getOrderType();
        String receiveId = shoppingCartCollageClearRequestVo.getReceiveId();

        // 获取拼单发起人id
        String crateUserId = shoppingCartCollageClearRequestVo.getCreateCollageUserId();
        // 拼单发起人id不能为空
        // 拼单购物相关的redis的key都需要拼单发起人id，所以这个值是不能为空的
        if (StringUtils.isEmpty(crateUserId)){
            throw new ServiceException(ResponseResult.COLLAGE_NOT_EXIST);
        }

        // 获取不到拼单的基础信息，抛出异常
        // 拼单的有效时间为1小时，当获取不到拼单的基础信息时，认为这个拼单没有发起、已经失效、已经结束
        Map<String, String> collageBase = collageCartBaseService.getCollageBase(partnerId,storeId,crateUserId);
        if(collageBase == null || collageBase.isEmpty()){
            throw new ServiceException(ResponseResult.COLLAGE_NOT_EXIST);
        }

        // 购物车版本加锁
        dolock(partnerId, storeId, crateUserId,shoppingCartCollageClearRequestVo.getCarVer());
        List<CartGoods> cartGoodsList = null;

        try {
            // 获取用户的购物车行id
            List<String> goodsUids = collageCartBaseService.getCollageCartGoodsUids(partnerId, storeId, crateUserId,shoppingCartCollageClearRequestVo.getSessionId());
            // 清除购物车中的购物车行信息
            List<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods> nowCartGoodsList = collageCartBaseService.removeGoodsUids(partnerId, storeId, crateUserId,goodsUids);
            if(null != nowCartGoodsList && !nowCartGoodsList.isEmpty()){
                cartGoodsList =  JSONArray.parseArray(JSONObject.toJSONString(nowCartGoodsList), CartGoods.class);
            }

            // check购物车中所有商品
            CheckCartRequest checkCartRequest = assortmentSdkService.checkShoppingCartSdk(cartGoodsList, partnerId, storeId, shoppingCartGoodsResponseVo, shoppingCartCollageClearRequestVo.getOrderType(), "", shoppingCartCollageClearRequestVo.getMenuType(), shoppingCartBaseService);
            if (checkCartRequest.getShoppingCartGoodsResponseVo() != null) {
                shoppingCartGoodsResponseVo.setChanged(checkCartRequest.getShoppingCartGoodsResponseVo().getChanged());
                shoppingCartGoodsResponseVo.setToastMsg(checkCartRequest.getShoppingCartGoodsResponseVo().getToastMsg());
            }
            cartGoodsList = JSONArray.parseArray(JSONObject.toJSONString(checkCartRequest.getCartGoodsList()), CartGoods.class);

            // 重新存储最新购物车
            List<CartGoods> cartGoodsRedisList = assortmentSdkService.setShoppingCart(partnerId, storeId, crateUserId, cartGoodsList, shoppingCartCollageClearRequestVo.getSessionId(), "", collageCartBaseService);

            // 更新拼单购物车人员缓存中的的购物车行id集合
            List<String> cartGoodsUids = cartGoodsRedisList.stream().filter(cartGoods1 -> currentSessionId.equals(cartGoods1.getSessionId())).map(CartGoods::getCartGoodsUid).collect(Collectors.toList());
            collageCartBaseService.updateCollageCartGoodsUids(cartGoodsUids,partnerId, storeId, crateUserId,shoppingCartCollageClearRequestVo.getSessionId());

        } catch (Exception e) {
            ErrorLog.errorConvertJson(SDKCommonBaseContextWare.getAppName(), LogThreadLocal.getTrackingNo(), getClass(), "shoppingCartCollageServiceImpl updateGoodsQty:" + e.getMessage(), e);
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_VERSION_ERROR, "购物车商品有变动，请手动刷新再修改");
        }finally {
            // 购物车版本解锁
            // 版本锁的粒度控制在检查购物车、刷新购物车、刷新车人员缓存行
            // 当这些操作结束后，购物的更新操作，已经结束，其他的流程是针对已经添加到redis中的购物车做查询操作
            // 所以只有上述的流程才加锁控制
            doUnlock(partnerId, storeId, crateUserId);
        }


        Long deliveryAmount = calculateDeliveryAmount(receiveId, partnerId, storeId, userLoginInfoDto.getWxAppid(), shoppingCartGoodsResponseVo);
        // 获取优惠信息
        ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult
                =getCalculationDiscountResult(menuType,partnerId,storeId,crateUserId,appId,userLoginInfoDto.getWxAppid(),orderType,assortmentCustomerInfoVo.isMemberPaid(),cartGoodsList,new ArrayList(),new ArrayList<>(),null,deliveryAmount);
        if (calculationDiscountResult == null) {
            shoppingCartGoodsResponseVo.setProducts(cartGoodsList);
        }

        ActivityQueryDto activityQueryDto = activityAdapter.getActivityQueryDto(partnerId, storeId, crateUserId, appId, shoppingCartCollageClearRequestVo.getOrderType());

        // 促销活动的优惠金额计算
        updateShoppingCartGoodsDiscount(null, activityQueryDto, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo, null, userLoginInfoDto, shoppingCartCollageClearRequestVo.getMenuType(), deliveryAmount);

        //设置更新响应信息
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, calculationDiscountResult, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), partnerId, storeId, crateUserId, ShoppingCartConstant.ADD_AND_UPDATE, null);
        // 设置购物车版本号
        shoppingCartGoodsResponseVo.setCarVer(collageCartBaseService.incrementCartVersion(partnerId, storeId, crateUserId));
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }
}
