package cn.freemud.service.impl.mcoffee;

import ch.qos.logback.classic.Level;
import cn.freemud.adapter.ActivityAdapter;
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.product.*;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.dto.user.GetSessionUserInfoDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.*;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.ActivityService;
import cn.freemud.service.CouponService;
import cn.freemud.service.impl.AssortmentSdkService;
import cn.freemud.service.impl.CouponServiceImpl;
import cn.freemud.service.impl.FullSubtractionActivityServiceImpl;
import cn.freemud.service.impl.mcoffee.calculation.CalculationServiceImpl;
import cn.freemud.service.impl.mcoffee.calculation.CouponDiscountCalculation;
import cn.freemud.service.impl.mcoffee.entity.CopyShoppingCartRequestVo;
import cn.freemud.service.impl.mcoffee.entity.MCoffeeAddGoodsRequestVo;
import cn.freemud.service.impl.mcoffee.entity.MCoffeeCardAddVo;
import cn.freemud.service.impl.mcoffee.entity.SwitchShoppingCartRequestVo;
import cn.freemud.service.impl.mcoffee.entity.*;
import cn.freemud.service.thirdparty.CustomerApplicationClient;
import cn.freemud.utils.BeanUtil;
import cn.freemud.service.thirdparty.ProductClient;
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.ApiLog;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.enums.ProductTypeEnum;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderItemResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.QueryByCodeResponse;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import com.freemud.application.sdk.api.productcenter.domain.ProductBeanDTO;
import com.freemud.sdk.api.assortment.shoppingcart.constant.CartResponseConstant;
import com.freemud.application.sdk.api.storecenter.request.StoreInfoRequest;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import com.freemud.sdk.api.assortment.shoppingcart.constant.CommonsConstant;
import com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoodsStates;
import com.freemud.sdk.api.assortment.shoppingcart.enums.BusinessTypeEnum;
import com.freemud.sdk.api.assortment.shoppingcart.enums.SaveCouponType;
import com.freemud.sdk.api.assortment.shoppingcart.request.CheckCartRequest;
import com.freemud.sdk.api.assortment.shoppingcart.service.ShoppingCartBaseService;
import com.freemud.sdk.api.assortment.shoppingcart.service.impl.ShoppingCartBaseServiceImpl;
import com.freemud.sdk.api.assortment.shoppingcart.util.CartResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

import static cn.freemud.constant.ShoppingCartConstant.SHOPPING_CART_EMPTY_GOODS_LIST;
import static cn.freemud.constant.ShoppingCartConstant.SHOPPING_CART_INVALIAD_GOODS;
import static com.freemud.sdk.api.assortment.shoppingcart.constant.ShoppingCartConstant.*;

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

@Service
public class ShoppingCartMCoffeeServiceImpl {

    @Autowired
    private ActivityAdapter activityAdapter;
    @Autowired
    private ShoppingCartBaseServiceImpl shoppingCartBaseService;
    @Autowired
    private FullSubtractionActivityServiceImpl fullSubtractionActivityService;
    @Autowired
    private AssortmentSdkService assortmentSdkService;
    @Autowired
    private CustomerApplicationClient customerApplicationClient;
    @Autowired
    private CalculationServiceImpl calculationService;
    @Autowired
    private CouponDiscountCalculation couponDiscountCalculation;
    @Autowired
    private OrderSdkService orderSdkService;
    @Autowired
    private StoreCenterService storeCenterService;
    @Autowired
    private CouponServiceImpl couponService;
    @Autowired
    private ProductClient productClient;
    @Autowired
    private ShoppingCartConvertAdapter shoppingCartConvertAdapter;

    private static final String nullSeat = "508106";

    @Value("${mccafe.universal.coupon.code}")
    private String mcCafeUniversalCouponCode;
    @Value("${mccafe.pay.card.fee}")
    private String payCardFee;
    @Value("${mccafe.tableware.skuId}")
    private String mcCafeTablewareSkuId;

    /**
     * 添加商品、超值加购、商品券
     */
    public BaseResponse addGoods(MCoffeeAddGoodsRequestVo addShoppingCartGoodsRequestVo) {
        // 参数校验
        if (StringUtils.isEmpty(addShoppingCartGoodsRequestVo.getShopId())) {
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_SHOP_ID_NOT_EMPTY);
        }
        if (addShoppingCartGoodsRequestVo.getQty() != null && addShoppingCartGoodsRequestVo.getQty() < 0) {
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_ADD_ERROR);
        }
        String sessionId = addShoppingCartGoodsRequestVo.getSessionId();
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(sessionId);
        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        String userId = assortmentCustomerInfoVo.getMemberId();
        String partnerId = addShoppingCartGoodsRequestVo.getPartnerId();
        String storeId = addShoppingCartGoodsRequestVo.getShopId();
        String appId = addShoppingCartGoodsRequestVo.getAppId();
        String spuId = addShoppingCartGoodsRequestVo.getSpuId();
        String skuId = StringUtils.isNotBlank(addShoppingCartGoodsRequestVo.getSkuId()) ? addShoppingCartGoodsRequestVo.getSkuId() : "";
        String goodsId = StringUtils.isEmpty(skuId) ? spuId : skuId;
        String tableNumber = addShoppingCartGoodsRequestVo.getTableNumber();
        String menuType = addShoppingCartGoodsRequestVo.getMenuType();
        Integer orderType = addShoppingCartGoodsRequestVo.getOrderType();
        String receiveId = addShoppingCartGoodsRequestVo.getReceiveId();
        Integer operationType = addShoppingCartGoodsRequestVo.getOperationType();
        String couponCode = addShoppingCartGoodsRequestVo.getCouponCode();

        String spuId2 = spuId;
        List<Long> productIds = new ArrayList<>();

        productIds.add(Long.parseLong(goodsId));
        List<ProductBeanDTO> productBeanListSpuClass = null;
        // 获取添加商品的详细信息
        if (!StringUtils.equals("9999",addShoppingCartGoodsRequestVo.getSkuId()) && !StringUtils.equals("9998",addShoppingCartGoodsRequestVo.getSkuId())) {
            productBeanListSpuClass = assortmentSdkService.getProductsInfoSdk(partnerId, storeId, Collections.singletonList(spuId2), menuType, this.shoppingCartBaseService);
        }

        // 查询购物车缓存
        List<CartGoods> oldCartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, null, null, shoppingCartBaseService);
        if (CollectionUtils.isEmpty(oldCartGoodsList)) {
            oldCartGoodsList = new ArrayList<>();
        }

        //种子券商品信息校验
        if (1 == addShoppingCartGoodsRequestVo.getIsMonthCard()) {
            seedCouponGoodsValidate(addShoppingCartGoodsRequestVo, oldCartGoodsList);
        }
        if (1 == addShoppingCartGoodsRequestVo.getIsB3S1Coupon()) {
            seedB3S1CouponGoodsValidate(addShoppingCartGoodsRequestVo, oldCartGoodsList);
        }

        //加锁，防止重复请求导致的加购数量错误
        synchronized (oldCartGoodsList) {
            //餐具和月享卡数量限制
            if (mcCafeTablewareSkuId.equals(skuId) || StringUtils.equals("9999",skuId)) {
                for (CartGoods cartGoods : oldCartGoodsList) {
                    if (mcCafeTablewareSkuId.equals(cartGoods.getSkuId())) {
                        return ResponseUtil.error(ResponseResult.SHOPPING_CART_ADD_ERROR.getCode(), "不能重复添加餐具商品");
                    }
                    if (StringUtils.equals("9999",cartGoods.getSkuId())) {
                        // 返回购物车数据
                        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, oldCartGoodsList, null, ShoppingCartConstant.ADD_AND_UPDATE, null);
                        return ResponseUtil.success(shoppingCartGoodsResponseVo);
                    }
                }
            }

            CartGoods addCartGoods = convent2CartGoods(addShoppingCartGoodsRequestVo, goodsId);
            //商品券已添加情况校验
            List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = checkGoodsCoupon(oldCartGoodsList, operationType, couponCode, goodsId, addCartGoods);
            setClassificationAndPrice(addCartGoods, productBeanListSpuClass);
            if (StringUtils.isNotEmpty(addShoppingCartGoodsRequestVo.getGroupName())) {
                addCartGoods.setSkuName(addShoppingCartGoodsRequestVo.getGroupName());
                addCartGoods.setSpuName(addShoppingCartGoodsRequestVo.getGroupName());
                addCartGoods.setName(addShoppingCartGoodsRequestVo.getGroupName());
            }
            //根据券号获取券名称
            String couponName = "";
            if (StringUtils.isNotEmpty(couponCode)) {
                couponName = getCouponNameByCode(couponCode, assortmentCustomerInfoVo,
                        BusinessTypeEnum.getByType(addShoppingCartGoodsRequestVo.getMenuType()).getCode(), storeId);
                //月享卡2.0之后不在显示月享卡券的名称 与普通商品券不同，故过滤掉月享卡券名称查询
                if (!("9999").equals(addCartGoods.getSpuId())){
                    addCartGoods.setCouponName(couponName);
                }else{
                    //将卡券名称赋值给 虚拟商品作为 月享卡2.0的优惠项展示
                    addCartGoods.setSpuName(couponName);
                    addCartGoods.setSkuName(couponName);
                }
            }

            // 如果购物车中有商品券，则当前添加的商品是特价商品时，需要提示“已选商品券，与其他优惠商品不同享，商品将恢复原价”
            boolean haveCouponProduct = oldCartGoodsList.parallelStream().anyMatch(k -> k.getCartGoodsUid().startsWith(CommonsConstant.COUPON_PREFIX));
            if (haveCouponProduct && isSpecialGoods(partnerId, storeId, userId, appId, goodsId, orderType)) {
                // 如果购物车先加入商品券，再加入促销商品，toast提示“已选商品券，与其他优惠商品不同享，商品将恢复原价”
                setToastMsgIfNotExist(shoppingCartGoodsResponseVo, ShoppingCartConstant.HAS_GOODS_COUPON_WHEN_ADD_SPECIAL_GOODS);
            }

            List<CartGoods> newCartGoods = null;
            if(StringUtils.equals("9999",skuId)) {
                // 将月享卡2.0的虚拟商品保存到购物车中
                oldCartGoodsList.add(addCartGoods);
                // 促销活动的优惠金额计算
                calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, couponCode,
                        oldCartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo,null);
                assortmentSdkService.setShoppingCart(partnerId, storeId, userId, oldCartGoodsList, null, tableNumber, this.shoppingCartBaseService);
                newCartGoods = oldCartGoodsList;
            } else if(StringUtils.equals("9998",skuId)){
                Optional<CartGoods> cartGoods = oldCartGoodsList.stream().filter(o -> "9998".equals(skuId) && o.getIsB3S1Coupon() == 1).findFirst();
                if(cartGoods.isPresent()) {
                    cartGoods.get().getB3S1CouponGoodsInfo().getCardCodeSet().add(addCartGoods.getCouponCode());
                } else {
                    B3S1CouponGoodsInfoVo b3S1CouponGoodsInfoVo = new B3S1CouponGoodsInfoVo();
                    addCartGoods.setB3S1CouponGoodsInfo(b3S1CouponGoodsInfoVo);
                    addCartGoods.setQty(1);
                    Set<String> set = new HashSet<>();
                    b3S1CouponGoodsInfoVo.setCardCodeSet(set);
                    set.add(addShoppingCartGoodsRequestVo.getCouponCode());
                    oldCartGoodsList.add(addCartGoods);
                }
                // 促销活动的优惠金额计算
                calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, couponCode,
                        oldCartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo,null);
                assortmentSdkService.setShoppingCart(partnerId, storeId, userId, oldCartGoodsList, null, tableNumber, this.shoppingCartBaseService);
                newCartGoods = oldCartGoodsList;
            } else {
                ApiLog.debug("【addGoodsList】:{} ,【addGoodsRequestVo】:{}",JSONObject.toJSONString(oldCartGoodsList),JSONObject.toJSONString(addCartGoods));
                // 购物车数据更新(保存商品原价)
                newCartGoods = updateCartGoodsLegal(partnerId, storeId, orderType, tableNumber, menuType, userId, addCartGoods, shoppingCartGoodsResponseVo, oldCartGoodsList);

                // 促销活动等价格计算
                calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, null,
                        newCartGoods, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo, null);
                if(addShoppingCartGoodsRequestVo.getIsB3S1Coupon() == 1) {
                    Optional<CartGoods> cartGoods = oldCartGoodsList.stream().filter(o -> "9998".equals(skuId) && o.getIsB3S1Coupon() == 1).findFirst();
                    if(cartGoods.isPresent()) {
                        cartGoods.get().getB3S1CouponGoodsInfo().getCardCodeSet().add(addShoppingCartGoodsRequestVo.getB3S1CouponGoodsInfo().getCardCode());
                    } else {
                        CartGoods cartGoods9998 = new CartGoods();
                        cartGoods9998.setSkuId("9998");
                        cartGoods9998.setQty(1);
                        B3S1CouponGoodsInfoVo b3S1CouponGoodsInfoVo = new B3S1CouponGoodsInfoVo();
                        cartGoods9998.setB3S1CouponGoodsInfo(b3S1CouponGoodsInfoVo);
                        Set<String> set = new HashSet<>();
                        b3S1CouponGoodsInfoVo.setCardCodeSet(set);
                        set.add(addShoppingCartGoodsRequestVo.getB3S1CouponGoodsInfo().getCardCode());
                        newCartGoods.add(cartGoods9998);
                    }
                }
                // 重新保存购物车数据
                assortmentSdkService.setShoppingCart(partnerId, storeId, userId, newCartGoods, null, tableNumber, this.shoppingCartBaseService);
            }
            // 返回购物车数据
            setAddAndUpdateResponse(shoppingCartGoodsResponseVo, newCartGoods, null, ShoppingCartConstant.ADD_AND_UPDATE, null);
        }
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    public BaseResponse addBatchGoods(MCoffeeBatchAddGoodsRequestVo requestVo){
        // 参数校验
        if (CollectionUtils.isEmpty(requestVo.getGoodsInfos())) {
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_ADD_INVAILD);
        }
        BaseResponse baseResponse = null;
        for (BatchGoodsInfoVo goodsInfo : requestVo.getGoodsInfos()) {
            baseResponse = addGoods(convertBatchAdd2SingleAdd(goodsInfo,requestVo));
            if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR,baseResponse.getCode())){
                return baseResponse;
            }
        }
        return baseResponse;
    }


    private List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> checkGoodsCoupon(List<CartGoods> oldCartGoodsList, Integer operationType, String couponCode, String goodsId, CartGoods addShoppingCartGoodsRequestVo) {
        if (operationType != null && operationType == 1 && StringUtils.isBlank(couponCode)) {
            throw new ServiceException(ResponseResult.PARAMETER_MISSING, "商品券券号为空");
        }
        if (CollectionUtils.isEmpty(oldCartGoodsList) && operationType != null && operationType == 1 && StringUtils.isNotBlank(couponCode)) {
            throw new ServiceException(ResponseResult.PARAMETER_MISSING, "请先添加商品再使用商品券");
        }
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = new ArrayList<>();
        //月享卡加购时，将券号传给促销
        if (null != addShoppingCartGoodsRequestVo
                && null != addShoppingCartGoodsRequestVo.getMonthCardInfo()
                && StringUtils.isNotEmpty(addShoppingCartGoodsRequestVo.getMonthCardInfo().getCardCode())){
            ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
            calculationDiscountCoupon.setCode(addShoppingCartGoodsRequestVo.getMonthCardInfo().getCardCode());
            coupons.add(calculationDiscountCoupon);
        }
        if (null != addShoppingCartGoodsRequestVo
                && null != addShoppingCartGoodsRequestVo.getB3S1CouponGoodsInfo()
                && StringUtils.isNotEmpty(addShoppingCartGoodsRequestVo.getB3S1CouponGoodsInfo().getCardCode())){
            ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
            calculationDiscountCoupon.setCode(addShoppingCartGoodsRequestVo.getB3S1CouponGoodsInfo().getCardCode());
            coupons.add(calculationDiscountCoupon);
        }
        if(null != addShoppingCartGoodsRequestVo && "9998".equals(addShoppingCartGoodsRequestVo.getSkuId())) {
            ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
            calculationDiscountCoupon.setCode(addShoppingCartGoodsRequestVo.getCouponCode());
            coupons.add(calculationDiscountCoupon);
        }

        if (CollectionUtils.isNotEmpty(oldCartGoodsList)) {
            Boolean isContinue =true;
            for (CartGoods cartGoods : oldCartGoodsList) {
                //购物车已存在商品券
                if (StringUtils.isNotBlank(cartGoods.getCouponCode())) {
                    ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
                    calculationDiscountCoupon.setCode(cartGoods.getCouponCode());
                    coupons.add(calculationDiscountCoupon);
                }

                //月享卡加购时，将券号传给促销
                if (null != cartGoods && null != cartGoods.getMonthCardInfo()
                        && StringUtils.isNotEmpty(cartGoods.getMonthCardInfo().getCardCode())
                        && 1 == cartGoods.getMonthCardInfo().getIsUseMonthCard()){
                    ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
                    calculationDiscountCoupon.setCode(cartGoods.getMonthCardInfo().getCardCode());
                    coupons.add(calculationDiscountCoupon);
                }
                if (null != cartGoods && null != cartGoods.getB3S1CouponGoodsInfo()
                        && StringUtils.isNotEmpty(cartGoods.getB3S1CouponGoodsInfo().getCardCode())
                        && 1 == cartGoods.getB3S1CouponGoodsInfo().getIsUseB3S1Coupon()){
                    ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
                    calculationDiscountCoupon.setCode(cartGoods.getB3S1CouponGoodsInfo().getCardCode());
                    coupons.add(calculationDiscountCoupon);
                }
                if(null != cartGoods && "9998".equals(cartGoods.getSkuId())) {
                    for (String code : cartGoods.getB3S1CouponGoodsInfo().getCardCodeSet()) {
                        ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
                        calculationDiscountCoupon.setCode(code);
                        coupons.add(calculationDiscountCoupon);
                    }
                }

                //使用券的是，如果购物车已经存在这个券，先清除，再添加
                //过滤月享卡种子券
                if (StringUtils.isNotEmpty(couponCode) && couponCode.equals(cartGoods.getCouponCode()) && Objects.equals(0,cartGoods.getIsMonthCardGoods())) {
                    cartGoods.setQty(0);
                }
                if (StringUtils.isNotEmpty(goodsId) && StringUtils.isNotEmpty(couponCode) && isContinue
                        && goodsId.equals(cartGoods.getSkuId()) && StringUtils.isBlank(cartGoods.getCouponCode())) {
                    // 如果购物车商品存在商品规格，替换时复制规格信息
                    if (CollectionUtils.isNotEmpty(cartGoods.getSpecialExtra())) {
                        addShoppingCartGoodsRequestVo.setSpecialExtra(cartGoods.getSpecialExtra());
                    }
                    if (cartGoods.getQty() > 1 ){
                        cartGoods.setQty(cartGoods.getQty() - 1);
                    } else {
                        //如果购物车存在相同的商品，则先删除购物车商品，在新增商品券购物车行
                        if (Objects.equals(0,cartGoods.getIsMonthCardGoods())){
                            cartGoods.setQty(0);
                        }
                    }
                    isContinue= false;
                }
                if(StringUtils.isNotEmpty(goodsId) && StringUtils.isNotEmpty(couponCode) && isContinue
                        && "啡常搭".equals(cartGoods.getName()) && GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType().equals(cartGoods.getGoodsType())
                        && CollectionUtils.isNotEmpty(cartGoods.getProductComboList()) && cartGoods.getProductComboList().size() == 1
                        && cartGoods.getProductComboList().get(0).getSkuId().equals(goodsId)
                        && CollectionUtils.isNotEmpty(cartGoods.getProductGroupList()) && cartGoods.getProductGroupList().size() == 1
                        && cartGoods.getProductGroupList().get(0).getSkuId().equals("0") && cartGoods.getProductGroupList().get(0).getSkuName().equals("无")) {
                    // 如果购物车商品存在商品规格，替换时复制规格信息
                    if (CollectionUtils.isNotEmpty(cartGoods.getProductComboList().get(0).getSpecialExtra())) {
                        addShoppingCartGoodsRequestVo.setSpecialExtra(cartGoods.getProductComboList().get(0).getSpecialExtra());
                    }
                    if (cartGoods.getQty() > 1 ){
                        cartGoods.setQty(cartGoods.getQty() - 1);
                    } else {
                        //如果购物车存在相同的商品，则先删除购物车商品，在新增商品券购物车行
                        cartGoods.setQty(0);
                    }
                    isContinue= false;
                }
                //同样商品券不能使用
               /* if (StringUtils.isNotEmpty(couponCode)&& StringUtils.isNotEmpty(cartGoods.getCouponCode()) && goodsId.equals(cartGoods.getGoodsId())) {
                    throw new ServiceException(ResponseResult.SHOPPING_CART_GOODS_COUPON_CAN_NOT_USE);
                }*/
            }
        }
        //新增商品券
        if (StringUtils.isNotBlank(couponCode)) {
            ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
            calculationDiscountCoupon.setCode(couponCode);
//            calculationDiscountCoupon.setIsSeedCouponGoods(addShoppingCartGoodsRequestVo.getIsSeedCouponGoods());
//            if (addShoppingCartGoodsRequestVo.getIsSeedCouponGoods()>0) {
//                calculationDiscountCoupon.setCartGoodsUid(addShoppingCartGoodsRequestVo.getCartGoodsUid());
//            }
            coupons.add(calculationDiscountCoupon);
        }
        if (CollectionUtils.isNotEmpty(coupons)){
            coupons = coupons.stream().distinct().collect(Collectors.toList());
        }
        return coupons;
    }

    /**
     * 批量更新购物车商品信息(add or del)
     * @param requestVo
     * @return
     */
    public BaseResponse batchOperateShoppingCartGoods(BatchOperateCartGoodsRequestVo requestVo){
        // 参数校验
        if (StringUtils.isEmpty(requestVo.getShopId())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_SHOP_ID_NOT_EMPTY);
        }

        BaseResponse baseResponse = new BaseResponse();
        //清除券信息
        if (StringUtils.isNotEmpty(requestVo.getRedundancyCouponCode())){
            ClearCouponCodeRequestVo clearCouponCodeRequestVo = new ClearCouponCodeRequestVo();
            clearCouponCodeRequestVo.setRedundancyCouponCode(requestVo.getRedundancyCouponCode());
            clearCouponCodeRequestVo.setSessionId(requestVo.getSessionId());
            clearCouponCodeRequestVo.setPartnerId(requestVo.getPartnerId());
            clearCouponCodeRequestVo.setShopId(requestVo.getShopId());
            clearCouponCodeRequestVo.setOrderType(requestVo.getOrderType());
            clearCouponCodeRequestVo.setChannelType(requestVo.getChannelType());
            clearCouponCodeRequestVo.setIsUseMonthCard(requestVo.getIsUseMonthCard());
            baseResponse = clearCouponInfoByCode(clearCouponCodeRequestVo);
        }
        if (CollectionUtils.isNotEmpty(requestVo.getRedundancyB3S1CouponCode())){
            MCoffeeAddGoodsRequestVo clearCouponCodeRequestVo = new MCoffeeAddGoodsRequestVo();
            clearCouponCodeRequestVo.setCouponCodeList(requestVo.getRedundancyB3S1CouponCode());
            clearCouponCodeRequestVo.setSessionId(requestVo.getSessionId());
            clearCouponCodeRequestVo.setPartnerId(requestVo.getPartnerId());
            clearCouponCodeRequestVo.setShopId(requestVo.getShopId());
            clearCouponCodeRequestVo.setOrderType(requestVo.getOrderType());
            clearCouponCodeRequestVo.setChannelType(requestVo.getChannelType());
            baseResponse = removeB3S1Coupon(clearCouponCodeRequestVo);
            if (!Objects.equals(ResponseResult.SUCCESS.getCode(), baseResponse.getCode())) {
                return baseResponse;
            }
        }

        if (CollectionUtils.isNotEmpty(requestVo.getQtyInfoList())) {
            BatchUpdateGoodsQtyRequestVo updateGoodsQtyRequestVo = new BatchUpdateGoodsQtyRequestVo();
            updateGoodsQtyRequestVo.setAppId(requestVo.getAppId());
            updateGoodsQtyRequestVo.setChannelType(requestVo.getChannelType());
            updateGoodsQtyRequestVo.setCarVer(requestVo.getCarVer());
            updateGoodsQtyRequestVo.setMenuType(requestVo.getMenuType());
            updateGoodsQtyRequestVo.setReceiveId(requestVo.getReceiveId());
            updateGoodsQtyRequestVo.setSessionId(requestVo.getSessionId());
            updateGoodsQtyRequestVo.setVersion(requestVo.getVersion());
            updateGoodsQtyRequestVo.setShopId(requestVo.getShopId());
            updateGoodsQtyRequestVo.setPartnerId(requestVo.getPartnerId());
            updateGoodsQtyRequestVo.setQtyInfoList(requestVo.getQtyInfoList());
            baseResponse = this.batchUpdateGoodsQty(updateGoodsQtyRequestVo);
            //批量更新失败，直接返回错误
            if (!Objects.equals(ResponseResult.SUCCESS.getCode(), baseResponse.getCode())) {
                return baseResponse;
            }
        }

        if (CollectionUtils.isNotEmpty(requestVo.getGoodsInfos())) {
            MCoffeeBatchAddGoodsRequestVo addGoodsRequestVo = new MCoffeeBatchAddGoodsRequestVo();
            addGoodsRequestVo.setAppId(requestVo.getAppId());
            addGoodsRequestVo.setChannelType(requestVo.getChannelType());
            addGoodsRequestVo.setMenuType(requestVo.getMenuType());
            addGoodsRequestVo.setReceiveId(requestVo.getReceiveId());
            addGoodsRequestVo.setSessionId(requestVo.getSessionId());
            addGoodsRequestVo.setGoodsInfos(requestVo.getGoodsInfos());
            addGoodsRequestVo.setShopId(requestVo.getShopId());
            addGoodsRequestVo.setOrderType(requestVo.getOrderType());
            addGoodsRequestVo.setPartnerId(requestVo.getPartnerId());
            addGoodsRequestVo.setGoodsInfos(requestVo.getGoodsInfos());
            baseResponse = this.addBatchGoods(addGoodsRequestVo);
            //批量新增失败，直接返回错误
            if (!Objects.equals(ResponseResult.SUCCESS.getCode(), baseResponse.getCode())) {
                return baseResponse;
            }
        }
        return baseResponse;
    }

    /**
     * 批量更新购物车商品数量
     * @param requestVo
     * @return
     */
    public BaseResponse batchUpdateGoodsQty(BatchUpdateGoodsQtyRequestVo requestVo){
        if (StringUtils.isEmpty(requestVo.getShopId())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_SHOP_ID_NOT_EMPTY);
        }

        if (CollectionUtils.isEmpty(requestVo.getQtyInfoList())){
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_UPDATE_ERROR);
        }

        BaseResponse baseResponse = null;
        for (GoodsQtyInfo goodsQtyInfo : requestVo.getQtyInfoList()) {
            if(StringUtils.isBlank(goodsQtyInfo.getCartGoodsUid()) || goodsQtyInfo.getQty() == null) {
                return ResponseUtil.error(ResponseResult.SHOPPING_CART_UPDATE_ERROR.getCode(), "批量更新购物车商品数量时，商品列表信息不能为空");
            }
            UpdateShoppingCartGoodsQtyRequestVo singleUpdateRequest = batchQtyRequestConvert2SingleQtyRequest(goodsQtyInfo,requestVo);
            baseResponse = this.updateGoodsQty(singleUpdateRequest);
            if (!Objects.equals(ResponseResult.SUCCESS.getCode(),baseResponse.getCode())){
                return baseResponse;
            }
        }
        return baseResponse;
    }

    /**
     * 批量更新购物车商品数量
     * @param addShoppingCartGoodsRequestVo
     * @return
     */
    public BaseResponse removeB3S1Coupon(MCoffeeAddGoodsRequestVo addShoppingCartGoodsRequestVo){
        if (StringUtils.isEmpty(addShoppingCartGoodsRequestVo.getShopId())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_SHOP_ID_NOT_EMPTY);
        }

        if (CollectionUtils.isEmpty(addShoppingCartGoodsRequestVo.getCouponCodeList())){
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_UPDATE_ERROR, "买3赠1券号不能为空");
        }


        String sessionId = addShoppingCartGoodsRequestVo.getSessionId();
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(sessionId);
        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        String userId = assortmentCustomerInfoVo.getMemberId();
        String partnerId = addShoppingCartGoodsRequestVo.getPartnerId();
        String storeId = addShoppingCartGoodsRequestVo.getShopId();
        String appId = addShoppingCartGoodsRequestVo.getAppId();
        String spuId = addShoppingCartGoodsRequestVo.getSpuId();
        String skuId = StringUtils.isNotBlank(addShoppingCartGoodsRequestVo.getSkuId()) ? addShoppingCartGoodsRequestVo.getSkuId() : "";
        String goodsId = StringUtils.isEmpty(skuId) ? spuId : skuId;
        String tableNumber = addShoppingCartGoodsRequestVo.getTableNumber();
        String menuType = addShoppingCartGoodsRequestVo.getMenuType();
        Integer orderType = addShoppingCartGoodsRequestVo.getOrderType();
        String receiveId = addShoppingCartGoodsRequestVo.getReceiveId();
        Integer operationType = addShoppingCartGoodsRequestVo.getOperationType();

        // 查询购物车缓存
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, null, null, shoppingCartBaseService);
        if (CollectionUtils.isEmpty(cartGoodsList)) {
            cartGoodsList = new ArrayList<>();
        }

        cartGoodsList = clearB3S1CouponInfo(cartGoodsList, addShoppingCartGoodsRequestVo.getCouponCodeList());
        Optional<CartGoods> cartGoods9998 = cartGoodsList.stream().filter(o -> "9998".equals(skuId) && o.getIsB3S1Coupon() == 1).findFirst();
        if(cartGoods9998.isPresent()) {
            cartGoods9998.get().getB3S1CouponGoodsInfo().getCardCodeSet().removeAll(addShoppingCartGoodsRequestVo.getCouponCodeList());
        }

        CartGoods monthCardProduct = null;
        // 如果购物车商品不为空， 则check购物车中所有商品
        if (CollectionUtils.isNotEmpty(cartGoodsList)) {
            // check购物车中所有商品
            List<CartGoods> temList = new ArrayList<>();
            for (CartGoods goods : cartGoodsList) {
                if (StringUtils.equals(goods.getSkuId(),"9999")){
                    monthCardProduct = goods;
                    continue;
                }
                temList.add(goods);
            }
            cartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, temList, sessionId);
            if (null != monthCardProduct) {
                cartGoodsList.add(monthCardProduct);
            }

            if (CollectionUtils.isNotEmpty(cartGoodsList)) {
                int size = cartGoodsList.size();
                for(int i=0;i<size;i++) {
                    //先把月卡放到最后
                    if(null != cartGoodsList.get(i) && Objects.equals(1,cartGoodsList.get(i).getIsB3S1Coupon())) {
                        CartGoods cartGoods = cartGoodsList.get(i);
                        if(i != size-1) {
                            cartGoodsList.remove(i);
                            cartGoodsList.add(cartGoods);
                            break;
                        }
                    }
                }
                for(int i=0;i<size;i++) {
                    //先把月卡放到最后
                    if(null != cartGoodsList.get(i) && Objects.equals(1,cartGoodsList.get(i).getIsMonthCard())) {
                        CartGoods cartGoods = cartGoodsList.get(i);
                        if(i != size-1) {
                            cartGoodsList.remove(i);
                            cartGoodsList.add(cartGoods);
                            break;
                        }
                    }
                }
                for(int i=0;i<size;i++) {
                    //如果是餐具商品，则放到最后
                    if(null != cartGoodsList.get(i) && cartGoodsList.get(i).getSkuId().equals(mcCafeTablewareSkuId)) {
                        CartGoods cartGoods = cartGoodsList.get(i);
                        cartGoods.setIsTableware(true);
                        if(i != size-1) {
                            cartGoodsList.remove(i);
                            cartGoodsList.add(cartGoods);
                            break;
                        }
                    }
                }
            }
        }

        String productCouponCode = assortmentSdkService.getShoppingCartCoupon(partnerId, storeId, userId, shoppingCartBaseService, SaveCouponType.COUPON.getCode());

        String freightCouponCode = assortmentSdkService.getShoppingCartCoupon(partnerId, storeId, userId, shoppingCartBaseService, SaveCouponType.FREIGHT_COUPON.getCode());

        // 当couponCode不为空时，需参与价格计算
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = getCoupon(productCouponCode, null, cartGoodsList,freightCouponCode,null);
        // 促销活动的优惠金额计算
        calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, addShoppingCartGoodsRequestVo.getCouponCode(),
                cartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo,null);

        assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, null, tableNumber, this.shoppingCartBaseService);

        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, null, ShoppingCartConstant.ADD_AND_UPDATE, null);

        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    /**
     * 根据券号清除券信息
     * @param requestVo
     * @return
     */
    public BaseResponse clearCouponInfoByCode(ClearCouponCodeRequestVo requestVo){
        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        if (StringUtils.isEmpty(requestVo.getShopId())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_SHOP_ID_NOT_EMPTY);
        }
        String sessionId = requestVo.getSessionId();
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(sessionId);
        String userId = assortmentCustomerInfoVo.getMemberId();
        String partnerId = requestVo.getPartnerId();
        String storeId = requestVo.getShopId();
        // 获取购物车商品
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, sessionId, "", shoppingCartBaseService);
        for (CartGoods cartGoods : cartGoodsList) {
            if (StringUtils.equals(cartGoods.getCouponCode(),requestVo.getRedundancyCouponCode())){
                cartGoods.setCouponCode(null);
                cartGoods.setIsMonthCardGoods(0);
            }

            /**
             * 是否继续使用月享卡优惠
             */
            if (null != cartGoods.getMonthCardInfo()){
                cartGoods.getMonthCardInfo().setIsUseMonthCard(requestVo.getIsUseMonthCard());
                ApiLog.info("【清除券信息】是否使用月享卡优惠:{},月享卡实体:{}",requestVo.getIsUseMonthCard(),JSONObject.toJSONString(cartGoods));
            }
        }
        cartGoodsList = cartGoodsList.stream().filter(cartGoods -> !StringUtils.equals("9999",cartGoods.getSkuId())).collect(Collectors.toList());
        //重新保存购物车
        assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, null, null, this.shoppingCartBaseService);
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), ShoppingCartConstant.QUERY_INFO, null);
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    /**
     * 更新商品数量
     */
    public BaseResponse updateGoodsQty(UpdateShoppingCartGoodsQtyRequestVo updateShoppingCartGoodsQtyRequestVo) {
        if (StringUtils.isEmpty(updateShoppingCartGoodsQtyRequestVo.getShopId())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_SHOP_ID_NOT_EMPTY);
        }
        if (updateShoppingCartGoodsQtyRequestVo.getQty() != null && updateShoppingCartGoodsQtyRequestVo.getQty() < 0) {
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_ADD_ERROR);
        }
        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        String sessionId = updateShoppingCartGoodsQtyRequestVo.getSessionId();
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(sessionId);
        String userId = assortmentCustomerInfoVo.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();

        // 先验证商品是否存在
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, null, null, shoppingCartBaseService);
        CartGoods cartGoods = null;
        String skuId = "";
        Integer finalQty = qty;
        boolean isB3S1Coupon = false;
        String b3S1CouponCode = "";
        for (CartGoods cartGoods_ : cartGoodsList) {
            //如果菜单购月卡数量大于10，则不作数量修改，直接算价并返回之前购物车信息
            if (Objects.equals(1,cartGoods_.getIsMonthCard())
                    && cartGoods_.getCartGoodsUid().equals(cartGoodsUid)
                    && updateShoppingCartGoodsQtyRequestVo.getQty()>10) {
                shoppingCartGoodsResponseVo.setChanged(true);
                shoppingCartGoodsResponseVo.setToastMsg(ResponseResult.SHOPPING_CART_QTY_LIMIT_ERR.getMessage());
                setAddAndUpdateResponse(shoppingCartGoodsResponseVo,cartGoodsList,
                        ResponseResult.SHOPPING_CART_QTY_LIMIT_ERR.getMessage(),
                        ShoppingCartConstant.ADD_AND_UPDATE,null);
                String freightCouponCode = assortmentSdkService.getShoppingCartCoupon(partnerId, storeId, userId, shoppingCartBaseService, SaveCouponType.FREIGHT_COUPON.getCode());
                String couponCode = assortmentSdkService.getShoppingCartCoupon(partnerId, storeId, userId, shoppingCartBaseService, SaveCouponType.COUPON.getCode());
                // 当couponCode不为空时，需参与价格计算
                List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = getCoupon(couponCode, null, cartGoodsList,freightCouponCode,null);
                // 促销活动的优惠金额计算
                calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, couponCode,
                        cartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo,null);
                return ResponseUtil.success(shoppingCartGoodsResponseVo);
            }
            if (cartGoodsUid.equals(cartGoods_.getCartGoodsUid())) {
                if (cartGoods_.getIsMonthCard() == 1 && cartGoods_.getMonthCardInfo() != null && qty != null && qty == 0){
                    cartGoodsList = clearMonthCouponInfo(cartGoodsList,cartGoods_.getMonthCardInfo().getCardCode(),cartGoodsUid);
                }
                if (cartGoods_.getIsB3S1Coupon() == 1 && cartGoods_.getB3S1CouponGoodsInfo() != null && qty != null && qty == 0){
                    isB3S1Coupon = true;
                    b3S1CouponCode = cartGoods_.getB3S1CouponGoodsInfo().getCardCode();
                }
                cartGoods = cartGoods_;
                cartGoods_.setQty(qty);
                skuId = cartGoods_.getSkuId();
                finalQty = cartGoods_.getQty();
                break;
            }
        }
        if(isB3S1Coupon) {
            cartGoodsList = clearB3S1CouponInfo(cartGoodsList,b3S1CouponCode);
        }

        if(!mcCafeTablewareSkuId.equals(skuId) && finalQty == 0 && CollectionUtils.isNotEmpty(cartGoodsList) && cartGoodsList.size() == 2) {
            for (CartGoods cartGoods_ : cartGoodsList) {
                if(mcCafeTablewareSkuId.equals(cartGoods_.getSkuId())) {
                    cartGoods_.setQty(0);
                }
            }
        }

        if (cartGoods == null) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_UPDATE_ERROR);
        }

        //商品券行商品数量不可增加
        if (StringUtils.isNotEmpty(cartGoods.getCouponCode()) && qty > 1 && cartGoods.getIsMonthCardGoods() < 1 && cartGoods.getIsMonthCard() < 1) {
            throw new ServiceException(ResponseResult.NOT_SUPPORTED);
        }

        // check购物车中所有商品
        cartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, cartGoodsList, sessionId);
//        List<CartGoods> temList = new ArrayList<>();
//        for (CartGoods goods : cartGoodsList) {
//            temList.addAll(checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, Arrays.asList(goods), sessionId));
//        }
//        cartGoodsList = temList;

        // 重新存储最新购物车
        assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, sessionId, "", shoppingCartBaseService);

        String couponCode = assortmentSdkService.getShoppingCartCoupon(partnerId, storeId, userId, shoppingCartBaseService, SaveCouponType.COUPON.getCode());

        String freightCouponCode = assortmentSdkService.getShoppingCartCoupon(partnerId, storeId, userId, shoppingCartBaseService, SaveCouponType.FREIGHT_COUPON.getCode());

        // 当couponCode不为空时，需参与价格计算
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = getCoupon(couponCode, null, cartGoodsList,freightCouponCode,null);
        // 促销活动的优惠金额计算
        calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, couponCode,
                cartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo,null);

        //把月卡放到最后
        if (CollectionUtils.isNotEmpty(cartGoodsList)) {
            int size = cartGoodsList.size();
            for(int i=0;i<size;i++) {
                if(Objects.equals(1,cartGoodsList.get(i).getIsMonthCard())) {
                    CartGoods montCardGoods = cartGoodsList.get(i);
                    if(i != size-1) {
                        cartGoodsList.remove(i);
                        cartGoodsList.add(montCardGoods);
                        break;
                    }
                }
            }
        }
        //设置更新响应信息
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), ShoppingCartConstant.ADD_AND_UPDATE, null);
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }


    /**
     * 购物车商品详情接口
     *
     * @param shoppingCartInfoRequestVo
     * @return
     */
    public BaseResponse getGoodsList(ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        if (StringUtils.isEmpty(shoppingCartInfoRequestVo.getShopId())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_SHOP_ID_NOT_EMPTY);
        }
        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        String sessionId = shoppingCartInfoRequestVo.getSessionId();
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(sessionId);
        String userId = assortmentCustomerInfoVo.getMemberId();
        String partnerId = shoppingCartInfoRequestVo.getPartnerId();
        String storeId = shoppingCartInfoRequestVo.getShopId();
        String appId = shoppingCartInfoRequestVo.getAppId();
        String couponCode = shoppingCartInfoRequestVo.getCouponCode();
        String freightCouponCode = shoppingCartInfoRequestVo.getFreightCouponCode();
//        String activityCode = shoppingCartInfoRequestVo.getActivityCode();
        String menuType = shoppingCartInfoRequestVo.getMenuType();
        Integer orderType = shoppingCartInfoRequestVo.getOrderType();
        String receiveId = shoppingCartInfoRequestVo.getReceiveId();
        String buyMonthlyCard = shoppingCartInfoRequestVo.getBuyMonthlyCard();

        // 获取购物车商品
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, sessionId, "", shoppingCartBaseService);
        ApiLog.debug("cartGoodsList: {}",JSONObject.toJSONString(cartGoodsList));
        CartGoods monthCardProduct = null;
        CartGoods B3S1CouponProduct = null;
        // 如果购物车商品不为空， 则check购物车中所有商品
        if (CollectionUtils.isNotEmpty(cartGoodsList)) {
            // check购物车中所有商品
            List<CartGoods> temList = new ArrayList<>();
            for (CartGoods goods : cartGoodsList) {
                if(shoppingCartInfoRequestVo.getIsUseMonthCard() != null && goods.getMonthCardInfo() != null) {
                    goods.getMonthCardInfo().setIsUseMonthCard(shoppingCartInfoRequestVo.getIsUseMonthCard());
                }
                if(shoppingCartInfoRequestVo.getIsUseB3S1Coupon() != null && goods.getB3S1CouponGoodsInfo() != null) {
                    goods.getB3S1CouponGoodsInfo().setIsUseB3S1Coupon(shoppingCartInfoRequestVo.getIsUseB3S1Coupon());
                }
                if (StringUtils.equals(goods.getSkuId(),"9999")){
                    monthCardProduct = goods;
                    continue;
                }
                if (StringUtils.equals(goods.getSkuId(),"9998")){
                    B3S1CouponProduct = goods;
                    continue;
                }
                temList.add(goods);
            }
            cartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, temList, sessionId);
            if (null != monthCardProduct) {
                cartGoodsList.add(monthCardProduct);
            }
            if (null != B3S1CouponProduct) {
                cartGoodsList.add(B3S1CouponProduct);
            }

            if (CollectionUtils.isNotEmpty(cartGoodsList)) {
                int size = cartGoodsList.size();
                for(int i=0;i<size;i++) {
                    //先把月卡放到最后
                    if(null != cartGoodsList.get(i) && Objects.equals(1,cartGoodsList.get(i).getIsB3S1Coupon())) {
                        CartGoods cartGoods = cartGoodsList.get(i);
                        if(i != size-1) {
                            cartGoodsList.remove(i);
                            cartGoodsList.add(cartGoods);
                            break;
                        }
                    }
                }
                for(int i=0;i<size;i++) {
                    //先把月卡放到最后
                    if(null != cartGoodsList.get(i) && Objects.equals(1,cartGoodsList.get(i).getIsMonthCard())) {
                        CartGoods cartGoods = cartGoodsList.get(i);
                        if(i != size-1) {
                            cartGoodsList.remove(i);
                            cartGoodsList.add(cartGoods);
                            break;
                        }
                    }
                }
                for(int i=0;i<size;i++) {
                    //如果是餐具商品，则放到最后
                    if(null != cartGoodsList.get(i) && cartGoodsList.get(i).getSkuId().equals(mcCafeTablewareSkuId)) {
                        CartGoods cartGoods = cartGoodsList.get(i);
                        cartGoods.setIsTableware(true);
                        if(i != size-1) {
                            cartGoodsList.remove(i);
                            cartGoodsList.add(cartGoods);
                            break;
                        }
                    }
                }
            }
            // 重新存储最新购物车
            assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, sessionId, "", shoppingCartBaseService);
        }

        // 门店列表页面无法获取到购物车行id导致前端需求，不管券信息是否为空，都更新到缓存
        //兼容前端逻辑，前端传递的券信息为空 或者 为 remove　时，清空购物车券，否则更新
        if(StringUtils.isEmpty(couponCode) || "remove".equals(couponCode)) {
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, "",shoppingCartBaseService, SaveCouponType.COUPON.getCode());
        } else {
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, couponCode, shoppingCartBaseService, SaveCouponType.COUPON.getCode());
        }
        if(StringUtils.isEmpty(freightCouponCode) || "remove".equals(freightCouponCode)) {
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, "",shoppingCartBaseService, SaveCouponType.FREIGHT_COUPON.getCode());
        } else {
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, freightCouponCode, shoppingCartBaseService, SaveCouponType.FREIGHT_COUPON.getCode());
        }


        //放到参数里
        if(StringUtils.isNotEmpty(couponCode) ) {
            shoppingCartInfoRequestVo.setCouponCode(couponCode);
            shoppingCartGoodsResponseVo.setCouponCode(couponCode);
        }
        if(StringUtils.isNotEmpty(freightCouponCode)) {
            shoppingCartInfoRequestVo.setFreightCouponCode(freightCouponCode);
            shoppingCartGoodsResponseVo.setFreightCouponCode(freightCouponCode);
        }

        String code = "";
        Long payCardPrice =null;
        if (StringUtils.isNotEmpty(buyMonthlyCard) ) {
            if (Objects.equals(buyMonthlyCard, "2")) {
                code = shoppingCartInfoRequestVo.getMonthlyCardCode();
                payCardPrice = Long.valueOf(payCardFee);
            } else if ( Objects.equals(buyMonthlyCard, "3")){
                code = mcCafeUniversalCouponCode;
                payCardPrice = Long.valueOf(payCardFee);
            }
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, code, shoppingCartBaseService, SaveCouponType.MON_COUPON.getCode());
        }
        // 当couponCode不为空时，需参与价格计算
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = getCoupon(couponCode, null, cartGoodsList,shoppingCartInfoRequestVo.getFreightCouponCode(), code);

        // 促销活动的优惠金额计算
        ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult = calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, null,
                cartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo, payCardPrice);

        //如果促销返回的商品里有月享卡2.0的虚拟商品，重新保存一次购物车
        if(CollectionUtils.isNotEmpty(cartGoodsList) && cartGoodsList.stream().anyMatch(cartGoods -> cartGoods.getSkuId().equals("9999") || cartGoods.getSkuId().equals("9998"))){
            // 重新存储最新购物车
            assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, sessionId, "", shoppingCartBaseService);
        }
        //设置更新响应信息
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), ShoppingCartConstant.QUERY_INFO, shoppingCartInfoRequestVo);

        //先出参里的券设置为空，然后如果可用，再放到出参里
        shoppingCartGoodsResponseVo.setCouponCode("");
        shoppingCartGoodsResponseVo.setFreightCouponCode("");
        if(StringUtils.isNotEmpty(couponCode) || StringUtils.isNotEmpty(freightCouponCode)) {
            String finalCouponCode = couponCode;
            String finalFreightCouponCode = freightCouponCode;
            if(null != calculationDiscountResult && CollectionUtils.isNotEmpty(calculationDiscountResult.getDiscounts())) {
                calculationDiscountResult.getDiscounts().stream().forEach(o -> {
                    if(o.getActivityCode().equals(finalCouponCode)) {
                        shoppingCartGoodsResponseVo.setCouponCode(finalCouponCode);
                    }
                    if(o.getActivityCode().equals(finalFreightCouponCode)) {
                        shoppingCartGoodsResponseVo.setFreightCouponCode(finalFreightCouponCode);
                    }
                });
            }
        }
        if(ObjectUtils.notEqual(shoppingCartGoodsResponseVo.getCouponCode(), couponCode)) {
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, shoppingCartGoodsResponseVo.getCouponCode(), shoppingCartBaseService, SaveCouponType.COUPON.getCode());
        }
        if(ObjectUtils.notEqual(shoppingCartGoodsResponseVo.getFreightCouponCode(), freightCouponCode)) {
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, shoppingCartGoodsResponseVo.getFreightCouponCode(), shoppingCartBaseService, SaveCouponType.FREIGHT_COUPON.getCode());
        }
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }


    /**
     * 券码用-查询购物车最新信息，计算优惠
     * @param requestVo
     * @return
     */
    public BaseResponse getCartInfoByUser(QueryCartInfoRequestVo requestVo){
        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(requestVo.getSessionId());
        // 获取购物车商品
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCartForCoupon(requestVo.getPartnerId(), requestVo.getStoreId(), requestVo.getUserId(), "", shoppingCartBaseService);
        String buyMonthlyCard = assortmentSdkService.getShoppingCartCoupon(requestVo.getPartnerId(), requestVo.getStoreId(), requestVo.getUserId(), shoppingCartBaseService, SaveCouponType.MON_COUPON.getCode());
        Long payCardPrice = null;
        if (StringUtils.isNotEmpty(buyMonthlyCard)){
            payCardPrice = Long.valueOf(payCardFee);
        }
        // 当couponCode不为空时，需参与价格计算
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = getCoupon(null, null, cartGoodsList,null,buyMonthlyCard);
        // 促销活动的优惠金额计算
        calculationService.updateShoppingCartGoodsDiscount(requestVo.getPartnerId(), requestVo.getStoreId(), requestVo.getUserId(), requestVo.getAppId(), requestVo.getOrderType(), assortmentCustomerInfoVo.isMemberPaid(), requestVo.getMenuType(), requestVo.getReceiveId(), null,
                cartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo,payCardPrice);
        String moneyCoupon = assortmentSdkService.getShoppingCartCoupon(requestVo.getPartnerId(),
                requestVo.getStoreId(), requestVo.getUserId(), shoppingCartBaseService,SaveCouponType.COUPON.getCode());
        String deliveryFeeCoupon = assortmentSdkService.getShoppingCartCoupon(requestVo.getPartnerId(),requestVo.getStoreId(),requestVo.getUserId(),shoppingCartBaseService,SaveCouponType.FREIGHT_COUPON.getCode());
        List<String> couponCodes = new ArrayList<>();
        couponCodes.add(deliveryFeeCoupon);
        couponCodes.add(moneyCoupon);
        List<CouponAvailableReqByCart> resList = couponDiscountCalculation.buildAvailableCoupons(requestVo,cartGoodsList,
                couponCodes);
        return ResponseUtil.success(resList);
    }

    /**
     * 查询购物车可用券
     */
    public BaseResponse availableCoupon(ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        if (StringUtils.isEmpty(shoppingCartInfoRequestVo.getShopId())) {
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_SHOP_ID_NOT_EMPTY);
        }
        ActivityClassifyCouponBean availableCoupon;
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(shoppingCartInfoRequestVo.getSessionId());
        String userId = assortmentCustomerInfoVo.getMemberId();
        String thirdPartyMemberID = assortmentCustomerInfoVo.getThirdPartyMemberID();
        String unionId = assortmentCustomerInfoVo.getUnionId();
        String partnerId = shoppingCartInfoRequestVo.getPartnerId();
        String storeId = shoppingCartInfoRequestVo.getShopId();
        String appId = shoppingCartInfoRequestVo.getAppId();
        //非商品券券号
        String couponCode = shoppingCartInfoRequestVo.getCouponCode();
        String menuType = shoppingCartInfoRequestVo.getMenuType();
        Integer orderType = shoppingCartInfoRequestVo.getOrderType();
//        String receiveId = shoppingCartInfoRequestVo.getReceiveId();

        // 获取购物车商品
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, null, "", shoppingCartBaseService);
        if (CollectionUtils.isEmpty(cartGoodsList)) {
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_ADD_INVAILD);
        }
        // 获取购物车商品-查询用户券-券码校验可用券
        availableCoupon = couponDiscountCalculation.availableCoupon(partnerId, storeId, userId, thirdPartyMemberID, unionId, appId, couponCode, orderType, menuType,cartGoodsList);
        return ResponseUtil.success(availableCoupon);
    }

    /**
     * 清空购物车
     *
     * @param shoppingCartClearRequestVo
     * @return
     */
    public BaseResponse clear(ShoppingCartClearRequestVo shoppingCartClearRequestVo) {

        String appId = shoppingCartClearRequestVo.getAppId();
        if (StringUtils.isBlank(appId)) {
            return ResponseUtil.error(ResponseResult.PARAMETER_MISSING, "appId不能为空");
        }
        String userId = shoppingCartClearRequestVo.getUserId();
        if (StringUtils.isEmpty(userId)) {
            CustomerInfoVo userLoginInfoDto = getCustomerInfoVo(shoppingCartClearRequestVo.getSessionId());
            userId = userLoginInfoDto.getMemberId();
        }
        String partnerId = shoppingCartClearRequestVo.getPartnerId();
        String storeId = shoppingCartClearRequestVo.getShopId();
        com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = assortmentSdkService.getCartParamDto(partnerId, storeId, userId);
        shoppingCartBaseService.clearMCCafe(cartParamDto, LogThreadLocal.getTrackingNo());
        if (ObjectUtils.equals(shoppingCartClearRequestVo.getOperationType(), OperationTypeEnum.PAY_SUCCESS.getOperationType())) {
            return ResponseUtil.success();
        }

        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        ActivityQueryDto activityQueryDto = activityAdapter.getActivityQueryDto(partnerId, storeId, userId, appId, shoppingCartClearRequestVo.getOrderType());
        ArrayList<ActivityList> activityList = new ArrayList<>();
        PromotionMessageDto promotionMessageDto = fullSubtractionActivityService.getFullPromotionActivityInfo(activityQueryDto, null, activityList);

        ActivityTip activityTip = new ActivityTip();
        if (promotionMessageDto != null) {
            activityTip.setActivityCode(promotionMessageDto.getActivityId());
            activityTip.setActivityType(promotionMessageDto.getActivityType());
            activityTip.setActivityName(promotionMessageDto.getPromotionMessage());
            activityTip.setActivityList(activityList);
        }
        shoppingCartGoodsResponseVo.setActivityTip(activityTip);
        shoppingCartGoodsResponseVo.setProducts(new ArrayList<>());
        shoppingCartGoodsResponseVo.setProductsCount(0);
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }


    /**
     * 去支付使用
     */
    public BaseResponse<ShoppingCartGoodsDto> getShoppingCartGoods(GetShoppingCartGoodsApportionRequestVo requestVo) {
        ShoppingCartInfoRequestVo shoppingCartInfoRequestVo = requestVo.getShoppingCartInfoRequestVo();
        CreateOrderVo.PremiumExchangeActivity premiumExchangeActivity = requestVo.getPremiumExchangeActivity();
        ShoppingCartGoodsDto shoppingCartGoodsDto = new ShoppingCartGoodsDto();
        shoppingCartGoodsDto.setIsDiscountDelivery(false);
        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        shoppingCartGoodsResponseVo.setIsDiscountDelivery(false);
        String sessionId = shoppingCartInfoRequestVo.getSessionId();
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(sessionId);
        String userId = assortmentCustomerInfoVo.getMemberId();
        String partnerId = shoppingCartInfoRequestVo.getPartnerId();
        String storeId = shoppingCartInfoRequestVo.getShopId();
        String appId = StringUtils.isEmpty(shoppingCartInfoRequestVo.getAppId()) ? assortmentCustomerInfoVo.getAppId() : shoppingCartInfoRequestVo.getAppId();
        String couponCode = shoppingCartInfoRequestVo.getCouponCode();
//        String activityCode = shoppingCartInfoRequestVo.getActivityCode();
        String tableNumber = assortmentCustomerInfoVo.getTableNumber();
        String menuType = shoppingCartInfoRequestVo.getMenuType();
        Integer orderType = shoppingCartInfoRequestVo.getOrderType();
        String receiveId = shoppingCartInfoRequestVo.getReceiveId();
        String buyMonthlyCard = shoppingCartInfoRequestVo.getBuyMonthlyCard();

        // 获取购物车商品
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, null, tableNumber, shoppingCartBaseService);
        ApiLog.debug("cartGoodsList: {}",JSONObject.toJSONString(cartGoodsList));
        if (cartGoodsList == null || CollectionUtils.isEmpty(cartGoodsList)) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_GETINFO_INVAILD);
        }

        // check购物车中所有商品
        List<CartGoods> allCartGoodsList = new ArrayList<>();

        CheckCartRequest checkCartRequest = checkCartGoodsForToPay(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, cartGoodsList);
        if (null != checkCartRequest) {
            //商品不再售卖状态或价格变动，直接返回报错
            if (null != checkCartRequest.getShoppingCartGoodsResponseVo()) {
                com.freemud.sdk.api.assortment.shoppingcart.domain.ShoppingCartGoodsResponseVo cartGoodsResponseVo = checkCartRequest.getShoppingCartGoodsResponseVo();
                if (cartGoodsResponseVo.getCartGoodsStates() != null && cartGoodsResponseVo.getCartGoodsStates().isHasInvalidGoods()) {
                    return ResponseUtil.error(ResponseResult.STORE_ITEM_CHECK_INVAILD);
                }
                if (cartGoodsResponseVo.getCartGoodsStates() != null && cartGoodsResponseVo.getCartGoodsStates().isPriceChanged()) {
                    return ResponseUtil.error(ResponseResult.SHOPPING_CART_ACTIVITY_CHANGE);
                }
                shoppingCartGoodsResponseVo.setToastMsg(cartGoodsResponseVo.getToastMsg());
            }
            allCartGoodsList = JSONArray.parseArray(JSONObject.toJSONString(checkCartRequest.getCartGoodsList()), CartGoods.class);
        }
        //加价购商品
        List<CartGoods> reduceGoods = cartGoodsList.stream().filter(cartGoods -> cartGoods.getGoodsType() == GoodsTypeEnum.REDUCE_PRICE_GOODS.getGoodsType()).collect(Collectors.toList());
        //添加商品为加价购商品
        if (CollectionUtils.isNotEmpty(reduceGoods)) {
            allCartGoodsList.addAll(reduceGoods);
        }

        // 重新存储最新购物车
        assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, sessionId, tableNumber, shoppingCartBaseService);

        String code = "";
        Long payCardPrice =null;
        if (StringUtils.isNotEmpty(buyMonthlyCard) ) {
            if (Objects.equals(buyMonthlyCard, "2")) {
                code = shoppingCartInfoRequestVo.getMonthlyCardCode();
                payCardPrice = Long.valueOf(payCardFee);
            } else if ( Objects.equals(buyMonthlyCard, "3")){
                code = mcCafeUniversalCouponCode;
                payCardPrice = Long.valueOf(payCardFee);
            }
        }

        // 当couponCode不为空时，需参与价格计算
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = getCoupon(couponCode, null, cartGoodsList,shoppingCartInfoRequestVo.getFreightCouponCode(),code);

        //加价购商品
        List<ShoppingCartInfoRequestVo.SendGoods> sendGoodsList = shoppingCartInfoRequestVo.getSendGoods();
        // 促销活动的优惠金额计算
        ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscount = calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, null,
                cartGoodsList, coupons, sendGoodsList, shoppingCartGoodsResponseVo, payCardPrice);

        //过滤月享卡2.0虚拟商品
        cartGoodsList = cartGoodsList.stream().filter(goods-> !StringUtils.equals("9999",goods.getSkuId())).collect(Collectors.toList());

        //设置更新响应信息
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), ShoppingCartConstant.QUERY_INFO, shoppingCartInfoRequestVo);

        //设置均摊信息
        calculationService.updateShoppingCartGoodsApportion(shoppingCartGoodsResponseVo, calculationDiscount, shoppingCartGoodsDto, premiumExchangeActivity, shoppingCartInfoRequestVo);

        //如果是餐具商品，则放到最后
        if (CollectionUtils.isNotEmpty(shoppingCartGoodsDto.getProducts())) {
            int size = shoppingCartGoodsDto.getProducts().size();
            for(int i=0;i<size;i++) {
                //先把月卡放到最后
                if(Objects.equals(1,shoppingCartGoodsDto.getProducts().get(i).getIsMonthCard())) {
                    ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto = shoppingCartGoodsDto.getProducts().get(i);
                    if(i != size-1) {
                        shoppingCartGoodsDto.getProducts().remove(i);
                        shoppingCartGoodsDto.getProducts().add(cartGoodsDetailDto);
                        break;
                    }
                }
                if(shoppingCartGoodsDto.getProducts().get(i).getSkuId().equals(mcCafeTablewareSkuId)) {
                    ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto = shoppingCartGoodsDto.getProducts().get(i);
                    cartGoodsDetailDto.setIsTableware(1);
                    if(i != size-1) {
                        shoppingCartGoodsDto.getProducts().remove(i);
                        shoppingCartGoodsDto.getProducts().add(cartGoodsDetailDto);
                        break;
                    }
                }
            }
        }

        return ResponseUtil.success(shoppingCartGoodsDto);
    }

    /**
     * 切换点餐门店
     */
    public BaseResponse switchCartGoods(SwitchShoppingCartRequestVo requestVo) {
        String jsonString = JSONObject.toJSONString(requestVo);
        ShoppingCartInfoRequestVo shoppingCartInfoRequestVo = JSONObject.parseObject(jsonString, ShoppingCartInfoRequestVo.class);
        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        String sessionId = shoppingCartInfoRequestVo.getSessionId();
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(sessionId);
        String userId = assortmentCustomerInfoVo.getMemberId();
        String partnerId = shoppingCartInfoRequestVo.getPartnerId();
        String fromStoreId = requestVo.getFromShopId();
        String toStoreId = requestVo.getToShopId();
        String couponCode = requestVo.getCouponCode();
        String appId = shoppingCartInfoRequestVo.getAppId();
        String menuType = shoppingCartInfoRequestVo.getMenuType();
        String receiveId = shoppingCartInfoRequestVo.getReceiveId();
        Integer orderType = shoppingCartInfoRequestVo.getOrderType();

        // 获取原门店购物车商品
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, fromStoreId, userId, sessionId, "", shoppingCartBaseService);
        ApiLog.debug("【switchCardGoods】原门店数据: {} {}", requestVo.getSessionId(), JSONObject.toJSONString(cartGoodsList));
        // 如果购物车商品不为空， 则check购物车中所有商品
        if (CollectionUtils.isEmpty(cartGoodsList)) {
            return ResponseUtil.success(shoppingCartGoodsResponseVo);
        } else {
            //移除餐具商品
            for(int i=0;i<cartGoodsList.size();i++) {
                if(mcCafeTablewareSkuId.equals(cartGoodsList.get(i).getSkuId())) {
                    cartGoodsList.remove(i);
                    break;
                }
            }

            //清空商品券商品
            cartGoodsList = clearCartCouponGoods(partnerId, fromStoreId, userId, sessionId, cartGoodsList);
        }

        List<CartGoods> onlyCheckGoodsList = new ArrayList<>();
        if (requestVo.getOperationType() == ShoppingCartOperationType.CHECK.getCode()){
            // 新门店check购物车中所有商品
            for (CartGoods cartGoods : cartGoodsList) {
                onlyCheckGoodsList.addAll(checkCartGoods(partnerId, toStoreId, orderType, menuType, shoppingCartGoodsResponseVo, Arrays.asList(cartGoods), sessionId));
            }
        }else{
            // 新门店check购物车中所有商品
            List<CartGoods> temList = new ArrayList<>();
            for (CartGoods goods : cartGoodsList) {
                temList.addAll(checkCartGoods(partnerId, toStoreId, orderType, menuType, shoppingCartGoodsResponseVo, Arrays.asList(goods), sessionId));
            }
            cartGoodsList = temList;
        }

        if (requestVo.getOperationType() == ShoppingCartOperationType.CHECK.getCode()) {
            if (StringUtils.isNotEmpty(shoppingCartGoodsResponseVo.getToastMsg())){
                //设置更新响应信息,校验失败只弹框提示消息，不切换门店，故将门店id重置为原来门店
                shoppingCartGoodsResponseVo.setProducts(cartGoodsList);
                shoppingCartInfoRequestVo.setShopId(requestVo.getFromShopId());
                setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), ShoppingCartConstant.QUERY_INFO, shoppingCartInfoRequestVo);
            }
            // 重新存储新门店购物车
            if(CollectionUtils.isNotEmpty(cartGoodsList)) {
                assortmentSdkService.setShoppingCart(partnerId, toStoreId, userId, cartGoodsList, sessionId, "", shoppingCartBaseService);
            } else {
                com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = assortmentSdkService.getCartParamDto(partnerId, toStoreId, userId);
                shoppingCartBaseService.clear(cartParamDto, LogThreadLocal.getTrackingNo());
            }
            return ResponseUtil.success(shoppingCartGoodsResponseVo);
        }else {
            // 新门店check购物车中所有商品
            List<CartGoods> temList = new ArrayList<>();
            for (CartGoods goods : cartGoodsList) {
                temList.addAll(checkCartGoods(partnerId, toStoreId, orderType, menuType, shoppingCartGoodsResponseVo, Arrays.asList(goods), sessionId));
            }
            cartGoodsList = temList;
            // 当couponCode不为空时，需参与价格计算
            List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = getCoupon(couponCode, null, cartGoodsList, null, null);

            // 促销活动的优惠金额计算
            calculationService.updateShoppingCartGoodsDiscount(partnerId, toStoreId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, null,
                    cartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo, null);
            // 重新存储新门店购物车
            if(CollectionUtils.isNotEmpty(cartGoodsList)) {
                assortmentSdkService.setShoppingCart(partnerId, toStoreId, userId, cartGoodsList, sessionId, "", shoppingCartBaseService);
            } else {
                com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = assortmentSdkService.getCartParamDto(partnerId, toStoreId, userId);
                shoppingCartBaseService.clear(cartParamDto, LogThreadLocal.getTrackingNo());
            }
            //设置更新响应信息
            setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), ShoppingCartConstant.QUERY_INFO, shoppingCartInfoRequestVo);
            shoppingCartGoodsResponseVo.setChanged(false);
        }
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    /**
     * 清除购物车商品券
     */
    private List<CartGoods> clearCartCouponGoods(String partnerId, String storeId, String userId, String sessionId, List<CartGoods> cartGoodsList) {
        if (CollectionUtils.isEmpty(cartGoodsList)) {
            return cartGoodsList;
        }
        cartGoodsList = cartGoodsList.stream().filter(cartGoods ->
                (StringUtils.isEmpty(cartGoods.getCouponCode()) && !StringUtils.equals("9999",cartGoods.getSkuId()))
                && cartGoods.getIsMonthCard() != 1
        ).collect(Collectors.toList());
        // 重新存储门店购物车
//        assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, sessionId, "", shoppingCartBaseService);
        return cartGoodsList;
    }


    /**
     * 再来一单
     */
    public BaseResponse copyOrder(CopyShoppingCartRequestVo requestVo) {
        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        String sessionId = requestVo.getSessionId();
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(sessionId);
        String menuType = "saas";
        Integer orderType = 1;
        String userId = assortmentCustomerInfoVo.getMemberId();
        String partnerId = requestVo.getPartnerId();
        String appId = requestVo.getAppId();
        String orderId = requestVo.getOrderId();
        String trackingNo = LogThreadLocal.getTrackingNo();
        QueryByCodeResponse orderInfo = orderSdkService.getOrderInfo(null, orderId, null, null, trackingNo);

        if (orderInfo == null || orderInfo.getResult() == null) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR);
        }
        if (orderInfo.getResult().getOrderType() == 3 || orderInfo.getResult().getOrderType() == 4) {
            menuType = "saasdelivery";
            orderType = 2;
        }
        String storeId = orderInfo.getResult().getStoreId();
        if(StringUtils.isNotEmpty(requestVo.getShopId())){
            storeId = requestVo.getShopId();
        }
        BaseResponse storeCheckResponse = checkOrderByStore(orderInfo.getResult().getPartnerId(), storeId, LogThreadLocal.getTrackingNo());
        if(!ResponseCodeConstant.RESPONSE_SUCCESS_STR.equals(storeCheckResponse.getCode())) {
            shoppingCartGoodsResponseVo.setChanged(true);
            shoppingCartGoodsResponseVo.setToastMsg(storeCheckResponse.getMessage());
        }

        List<CartGoods> cartGoodsList = getOrderGoods(orderInfo.getResult());
        if (CollectionUtils.isEmpty(cartGoodsList)) {
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_GETINFO_INVAILD);
        }
        // check购物车中所有商品
//        cartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, cartGoodsList);
        List<CartGoods> temList = new ArrayList<>();
        for (CartGoods goods : cartGoodsList) {
            temList.addAll(checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, Arrays.asList(goods), sessionId));
        }
        cartGoodsList = temList;

        // 如果购物车商品不为空， 则check购物车中所有商品
        if (shoppingCartGoodsResponseVo.getChanged() && requestVo.getOperationType() == ShoppingCartOperationType.CHECK.getCode()) {
            return ResponseUtil.success(shoppingCartGoodsResponseVo);
        }
        // 重新存储最新购物车
        assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, sessionId, "", shoppingCartBaseService);
        // 促销活动的优惠金额计算
        calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, null, null,
                cartGoodsList, new ArrayList<>(), new ArrayList<>(), shoppingCartGoodsResponseVo,null);
        //设置更新响应信息
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), ShoppingCartConstant.ADD_AND_UPDATE, null);
        //再来一单清除配送费
        shoppingCartGoodsResponseVo.setDeliveryAmount(0L);
        shoppingCartGoodsResponseVo.setDiscountDeliveryAmount(0L);
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    /**
     * 门店相关校验
     */
    private BaseResponse checkOrderByStore(String partnerId, String shopId, String trackingNo) {

        // 获取门店信息
        StoreInfoRequest storeInfoRequest = new StoreInfoRequest(partnerId, shopId,null);
        StoreResponse storeResponse = storeCenterService.getStoreInfo(storeInfoRequest, trackingNo);
        if (storeResponse == null || storeResponse.getBizVO() == null) {
            return ResponseUtil.error(ResponseResult.STORE_NOT_FOUND);
        }
        StoreResponse.BizVO storeResponseDto = storeResponse.getBizVO();
        String storeName = storeResponseDto.getStoreName();
        // 校验门店是否营业
        if (storeResponseDto.getActiveFlag() == null || storeResponseDto.getActiveFlag() != 1
                || storeResponseDto.getState() == null || storeResponseDto.getState().equals("3")) {
            ResponseResult storeClose = ResponseResult.CART_STORE_CLOSE;
            storeClose.setMessage(storeClose.getMessage().replace("$storeName",storeName));
            return ResponseUtil.error(storeClose);
        }
        if (storeResponseDto.getActiveFlag() == 1 && storeResponseDto.getState().equals("2")) {
            ResponseResult storeRest = ResponseResult.CART_STORE_REST;
            storeRest.setMessage(storeRest.getMessage().replace("$storeName",storeName));
            return ResponseUtil.error(storeRest);
        }
        return ResponseUtil.success();
    }

    private List<CartGoods> getOrderGoods(OrderInfoReqs orderInfo) {
        if (orderInfo == null || CollectionUtils.isEmpty(orderInfo.getOrderItemList())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_PRODUCT_NOT_EXIST);
        }
        List<OrderItemResp> orderItemList = orderInfo.getOrderItemList();
        List<CartGoods> cartGoodsList = new ArrayList<>();
        List<OrderItemResp> parentOrderItemList = orderItemList.stream()
                .filter(item -> StringUtils.isEmpty(item.getParentProductId()) || ObjectUtils.equals("0", item.getParentProductId()))
                .collect(Collectors.toList());
        for (OrderItemResp orderItem : parentOrderItemList) {
            CartGoods cartGoods = new CartGoods();
            cartGoods.setGoodsId(orderItem.getProductSpec());
            cartGoods.setQty(orderItem.getProductQuantity());
            cartGoods.setSpuId(orderItem.getProductId());
            cartGoods.setSkuId(orderItem.getProductSpec());
            cartGoods.setOriginalPrice(orderItem.getProductPrice().longValue());
            cartGoods.setFinalPrice(orderItem.getProductPrice().longValue());
            cartGoods.setOriginalAmount(cartGoods.getOriginalPrice() * cartGoods.getQty());
            cartGoods.setAmount(cartGoods.getFinalPrice() * cartGoods.getQty());
            cartGoods.setPic(orderItem.getProductPicUrl());
            if(6 == orderItem.getProductType()) {
                cartGoods.setGoodsType(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType());
            } else if(10 ==orderItem.getProductType()) {
                cartGoods.setGoodsType(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.SKU_GOODS.getGoodsType());
            }else if(!orderItem.getProductId().equals(orderItem.getProductSpec())) {
                cartGoods.setGoodsType(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.SKU_GOODS.getGoodsType());
            }else {
                cartGoods.setGoodsType(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.COMMON_GOODS.getGoodsType());
            }
            if(("早餐啡常搭".equals(orderItem.getProductName()) && "早餐啡常搭".equals(orderItem.getProductSpecName()))
                    || ("啡常搭".equals(orderItem.getProductName()) && "啡常搭".equals(orderItem.getProductSpecName()))) {
                cartGoods.setName(orderItem.getProductName());
                cartGoods.setSpuName(orderItem.getProductName());
                cartGoods.setSkuName(orderItem.getProductName());
            } else {
                cartGoods.setName(orderItem.getProductName());
                cartGoods.setSkuName(orderItem.getProductSpecName());
                cartGoods.setSpuName(orderItem.getProductName());
            }
            if (ObjectUtils.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), orderItem.getProductType())
                    || ObjectUtils.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), orderItem.getProductType())) {
                // 获取套餐子商品列表
                cartGoods.setProductComboList(new ArrayList<>());
                cartGoods.setProductGroupList(new ArrayList<>());
                String partnerProductId = orderItem.getProductId() + "_" + orderItem.getProductSeq();
                List<OrderItemResp> comboProducts = orderItemList.stream().filter(item -> ObjectUtils.equals(partnerProductId, item.getParentProductId())).collect(Collectors.toList());
                comboProducts.forEach(combo -> {
                    getComboxGoods(cartGoods, combo, orderItemList);
                });
                //取所有固定套餐的价格计算套餐总价
                Long originalPrice = comboProducts.stream().filter(orderItemResp -> null != orderItemResp.getProductPrice()).mapToLong(orderItemResp ->orderItemResp.getProductPrice().longValue()).sum();
                cartGoods.setOriginalPrice(originalPrice);
            }
            //特制
            if (StringUtils.isNotEmpty(orderItem.getExtInfo())){
                JSONObject extJson = JSONObject.parseObject(orderItem.getExtInfo());
                if (extJson.containsKey("specialAttrs")) {
                    CartGoods.SpecialExtra specialExtra = new CartGoods.SpecialExtra();
                    JSONArray specialAttrs = JSONArray.parseArray(extJson.getString("specialAttrs"));
                    for (Object specialAttr : specialAttrs) {
                        JSONObject object = JSONObject.parseObject(specialAttr.toString());
                        specialExtra.setAttributeId(object.containsKey("attributeId") ? object.getString("attributeId") : "");
                        specialExtra.setAttributeName(object.containsKey("attributeName") ? object.getString("attributeName") : "");
                        specialExtra.setSpecialCode(object.containsKey("specialCode") ? object.getString("specialCode") : "");
                    }
                    cartGoods.setSpecialExtra(Arrays.asList(specialExtra));
                }
            }

            if (ObjectUtils.equals(88, orderItem.getProductType())) {
                // 获取套餐子商品列表
                cartGoods.setProductMaterialList(new ArrayList<>());
                String partnerProductId = orderItem.getProductId() + "_" + orderItem.getProductSeq();
                List<OrderItemResp> materialProducts = orderItemList.stream().filter(item -> ObjectUtils.equals(partnerProductId, item.getParentProductId())).collect(Collectors.toList());
                materialProducts.forEach(material -> getMaterialGoods(cartGoods, material));
            }
            cartGoodsList.add(cartGoods);
        }

        return cartGoodsList;
    }


    private CartGoods.ComboxGoods getComboxGoods(CartGoods cartGoods, OrderItemResp orderItemResp, List<OrderItemResp> orderItemList) {
        CartGoods.ComboxGoods comboxGoods = new CartGoods.ComboxGoods();
        comboxGoods.setSkuId(orderItemResp.getProductSpec());
        comboxGoods.setGoodsId(orderItemResp.getProductId());
        comboxGoods.setQty(orderItemResp.getProductQuantity());
        comboxGoods.setOriginalPrice(orderItemResp.getProductPrice().longValue());
        comboxGoods.setFinalPrice(orderItemResp.getSalePrice().longValue());
        comboxGoods.setPic(orderItemResp.getProductPicUrl());
        comboxGoods.setName(StringUtils.isNotEmpty(orderItemResp.getProductName()) ? orderItemResp.getProductName() :"");
        comboxGoods.setSpuName(StringUtils.isNotEmpty(orderItemResp.getProductName()) ? orderItemResp.getProductName() :"");
        comboxGoods.setSkuName(StringUtils.isNotEmpty(orderItemResp.getProductSpecName()) ? orderItemResp.getProductSpecName() :"");
        comboxGoods.setSubName(StringUtils.isNotEmpty(orderItemResp.getProductSpecName()) ? orderItemResp.getProductSpecName() : "");
        comboxGoods.setOriginalAmount(comboxGoods.getOriginalPrice() * comboxGoods.getQty());
        comboxGoods.setAmount(comboxGoods.getFinalPrice() * comboxGoods.getQty());
        if (StringUtils.isNotBlank(orderItemResp.getProductProperty())) {
            List<CartGoods.CartGoodsExtra> extra = new ArrayList<>();
            String[] split = orderItemResp.getProductProperty().split("/");
            for (int i = 0; i < split.length; i++) {
                CartGoods.CartGoodsExtra cartGoodsExtra = new CartGoods.CartGoodsExtra();
                cartGoodsExtra.setAttributeName(split[i]);
                extra.add(cartGoodsExtra);
            }
            comboxGoods.setExtra(extra);
        }

        for (OrderItemResp itemResp : orderItemList) {
            //特制
            if (StringUtils.isNotEmpty(itemResp.getExtInfo())){
                JSONObject extJson = JSONObject.parseObject(itemResp.getExtInfo());
                if (extJson.containsKey("specialAttrs")) {
                    CartGoods.SpecialExtra specialExtra = new CartGoods.SpecialExtra();
                    JSONArray specialAttrs = JSONArray.parseArray(extJson.getString("specialAttrs"));
                    for (Object specialAttr : specialAttrs) {
                        JSONObject object = JSONObject.parseObject(specialAttr.toString());
                        specialExtra.setAttributeId(object.containsKey("attributeId") ? object.getString("attributeId") : "");
                        specialExtra.setAttributeName(object.containsKey("attributeName") ? object.getString("attributeName") : "");
                        specialExtra.setSpecialCode(object.containsKey("specialCode") ? object.getString("specialCode") : "");
                    }
                    comboxGoods.setSpecialExtra(Arrays.asList(specialExtra));
                }
            }
        }

        Map<String, Object> map = JSONObject.parseObject(orderItemResp.getExtInfo(), Map.class);
        if (map.containsKey("isFixedProduct") && (boolean) map.get("isFixedProduct")) {
            cartGoods.getProductComboList().add(comboxGoods);
        }
        if (map.containsKey("isFixedProduct") && !(boolean) map.get("isFixedProduct")) {
            cartGoods.getProductGroupList().add(comboxGoods);
        }
        if (ObjectUtils.equals(88, orderItemResp.getProductType())) {
            comboxGoods.setProductMaterialList(new ArrayList<>());
            String partnerProductId = orderItemResp.getProductId() + "_" + orderItemResp.getProductSeq();
            List<OrderItemResp> materialProducts = orderItemList.stream().filter(item -> ObjectUtils.equals(partnerProductId, item.getParentProductId())).collect(Collectors.toList());
            materialProducts.forEach(material -> getMaterialGoods(comboxGoods, material));
        }
        return comboxGoods;
    }


    private CartGoods.MaterialGoods getMaterialGoods(CartGoods cartGoods, OrderItemResp orderItemResp) {
        CartGoods.MaterialGoods materialGoods = new CartGoods.MaterialGoods();
        materialGoods.setSpuId(orderItemResp.getProductId());
        materialGoods.setCustomerCode(orderItemResp.getThirdProductId());
        materialGoods.setFinalPrice(orderItemResp.getSalePrice().longValue());
        materialGoods.setOriginalPrice(orderItemResp.getProductPrice().longValue());
        materialGoods.setOriginalAmount(materialGoods.getOriginalPrice());
        materialGoods.setAmount(materialGoods.getFinalPrice());
        materialGoods.setSpuName(orderItemResp.getProductName());
        cartGoods.getProductMaterialList().add(materialGoods);
        return materialGoods;
    }


    private CartGoods.MaterialGoods getMaterialGoods(CartGoods.ComboxGoods comboGoods, OrderItemResp orderItemResp) {
        CartGoods.MaterialGoods materialGoods = new CartGoods.MaterialGoods();
        materialGoods.setSpuId(orderItemResp.getProductId());
        materialGoods.setCustomerCode(orderItemResp.getThirdProductId());
        materialGoods.setFinalPrice(orderItemResp.getSalePrice().longValue());
        materialGoods.setOriginalPrice(orderItemResp.getProductPrice().longValue());
        materialGoods.setOriginalAmount(materialGoods.getOriginalPrice());
        materialGoods.setAmount(materialGoods.getFinalPrice());
        materialGoods.setSpuName(orderItemResp.getProductName());
        comboGoods.getProductMaterialList().add(materialGoods);
        return materialGoods;
    }


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


    /**
     * 获取购物车商品,添加商品,校验商品合法性,合并商品行,重新set购物车信息到缓存中
     *
     * @param addCartGoods
     * @param sessionId
     * @param shoppingCartGoodsResponseVo
     */
    public List<CartGoods> updateCartGoodsLegal(String partnerId, String storeId, Integer orderType, String tableNumber, String menuType, String sessionId,
                                                CartGoods addCartGoods, ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo, List<CartGoods> oldCartGoodsList) {

        oldCartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType,shoppingCartGoodsResponseVo, oldCartGoodsList, sessionId);
        List<CartGoods> newCartGoods = new ArrayList<>();
        newCartGoods.add(addCartGoods);

        //如果加购的商品与购物车缓存中月享卡2.0的商品goodsId相同，则给新增商品的couponCode 赋值为月享卡2.0的券号，否则会分行展示
        List<CartGoods> montCardGoods = oldCartGoodsList.stream().filter(c-> c.getIsMonthCardGoods()>0).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(montCardGoods)){
            for (CartGoods montCardGood : montCardGoods) {
                if (StringUtils.isEmpty(newCartGoods.get(0).getCouponCode()) && newCartGoods.get(0).getGoodsId().equals(montCardGood.getGoodsId())){
                    newCartGoods.get(0).setCouponCode(montCardGood.getCouponCode());
                }
            }
        }

        //加购商品校验
        List<CartGoods> newCartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType,shoppingCartGoodsResponseVo, newCartGoods, sessionId);
        List<CartGoods> nowCartGoodsList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(oldCartGoodsList)){
            nowCartGoodsList.addAll(oldCartGoodsList);
        }
        if(CollectionUtils.isNotEmpty(newCartGoodsList)){
            ApiLog.debug("【merge-before】:{} ,【newCardGoods】:{}",JSONObject.toJSONString(nowCartGoodsList),JSONObject.toJSONString(newCartGoods));
            newCartGoodsList.forEach(newCartGood -> {
                int index;
                if ((index = nowCartGoodsList.indexOf(newCartGood)) >= 0) {
                    nowCartGoodsList.get(index).setQty(nowCartGoodsList.get(index).getQty() + addCartGoods.getQty());
                } else {
                    nowCartGoodsList.add(newCartGood);
                }
            });
        }
        return nowCartGoodsList;
    }

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

        // 更新和添加商品时不需要包装费
        if (ShoppingCartConstant.ADD_AND_UPDATE.equals(opt)) {
            shoppingCartGoodsResponseVo.setNewPackAmount(null);
            return;
        }

        if (shoppingCartGoodsResponseVo.getNewPackAmount() == null || shoppingCartGoodsResponseVo.getNewPackAmount() == 0L) {
            return;
        }
        if (shoppingCartInfoRequestVo != null && Objects.equals(shoppingCartInfoRequestVo.getReachStoreType(), OrderType.EAT_IN.getCode())) {
            shoppingCartGoodsResponseVo.setNewPackAmount(null);
        } else {
            Long packAmount = shoppingCartGoodsResponseVo.getNewPackAmount();
            Long originalTotalAmount = shoppingCartGoodsResponseVo.getOriginalTotalAmount() + packAmount;
            Long totalAmount = shoppingCartGoodsResponseVo.getTotalAmount() + packAmount;
            shoppingCartGoodsResponseVo.setOriginalTotalAmount(originalTotalAmount);
            shoppingCartGoodsResponseVo.setTotalAmount(totalAmount);
        }
    }

    /**
     * 检查sku数量
     *
     * @param oldCartGoodsList
     * @param addCartGoods
     * @return
     */
    private Integer checkSkuQty(List<CartGoods> oldCartGoodsList, CartGoods addCartGoods) {
        Integer qty = addCartGoods.getQty() == null ? 0 : addCartGoods.getQty();
        if (CollectionUtils.isNotEmpty(oldCartGoodsList)) {
            for (CartGoods goods : oldCartGoodsList) {
                if (goods.getSkuId().equals(addCartGoods.getSkuId()) && goods.getSpuId().equals(addCartGoods.getSpuId())) {
                    qty += goods.getQty();
                }
            }
        }
        return qty;
    }

//    /**
//     * 套餐空键位处理
//     */
//    private Map<String, String> checkNewCartGoods(List<CartGoods> newCartGoods,Integer oper,Map<String, String> result) {
//
//        Map<String, String> map = new HashMap<>();
//
//        //删除套餐空键位
//        if(oper == 1){
//            for (CartGoods goods : newCartGoods) {
//                if (CollectionUtils.isNotEmpty(goods.getProductGroupList())) {
//                    List<CartGoods.ComboxGoods> productGroupList = new ArrayList<>();
//                    for (CartGoods.ComboxGoods comboxGoods : goods.getProductGroupList()) {
//                        if (nullSeat.equals(comboxGoods.getGoodsId())) {
//                            map.put(goods.getCartGoodsUid(), goods.getGoodsId());
//                        } else {
//                            productGroupList.add(comboxGoods);
//                        }
//                    }
//                    goods.setProductGroupList(productGroupList);
//                }
//            }
//            return map;
//        }
//
//        //恢复套餐空键位
//        if(oper == 2 && result.size() != 0){
//            for (CartGoods cartGoods : newCartGoods) {
//                if (result.get(cartGoods.getCartGoodsUid()) != null) {
//                    CartGoods.ComboxGoods comboxGoods = new CartGoods.ComboxGoods();
//                    comboxGoods.setGoodsId(nullSeat);
//                    comboxGoods.setSkuId(nullSeat);
//                    comboxGoods.setCustomerCode(nullSeat);
//                    comboxGoods.setQty(1);
//                    comboxGoods.setOriginalPrice(0L);
//                    comboxGoods.setFinalPrice(0L);
//                    cartGoods.getProductGroupList().add(comboxGoods);
//                }
//            }
//        }
//
//        return map;
//    }


    private void setToastMsgIfNotExist(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, String message) {
        if (StringUtils.isEmpty(shoppingCartGoodsResponseVo.getToastMsg())) {
            shoppingCartGoodsResponseVo.setToastMsg(message);
        }
    }

    /**
     * 查询用户信息
     *
     * @param sessionId
     * @return
     */
    private CustomerInfoVo getCustomerInfoVo(String sessionId) {
        GetSessionUserInfoDto getSessionUserInfoDto = new GetSessionUserInfoDto();
        getSessionUserInfoDto.setIsGetPaid(true);
        getSessionUserInfoDto.setSessionId(sessionId);
        BaseResponse<CustomerInfoVo> sessionUserInfo = customerApplicationClient.getSessionUserInfo(getSessionUserInfoDto);
        if (sessionUserInfo == null || !ResponseResult.SUCCESS.getCode().equals(sessionUserInfo.getCode()) || sessionUserInfo.getResult() == null || sessionUserInfo.getResult().getMemberId() == null) {
            throw new ServiceException(ResponseResult.NOT_LOGIN);
        }
        return sessionUserInfo.getResult();
    }


    private boolean isSpecialGoods(String partnerId, String storeId, String userId, String appId, String goodsId, Integer orderType) {
        boolean isSpecialGoods = false;
        ActivityAdapter activityAdapter = SDKCommonBaseContextWare.getBean(ActivityAdapter.class);
        ActivityQueryDto activityQueryDto = activityAdapter.getActivityQueryDto(partnerId, storeId, userId, appId, orderType);
        ActivityService activityService = SDKCommonBaseContextWare.getBean(ActivityService.class);
        ActivityQueryResponseDto activityQueryResponseDto = activityService.queryActivitys(activityQueryDto, ActivityTypeEnum.TYPE_2, null);

        if (activityQueryResponseDto == null || activityQueryResponseDto.getResult() == null) {
            return isSpecialGoods;
        }

        List<ActivityResponseDto> activityResponseDtoList = activityQueryResponseDto.getResult();
        for (int i = 0, len = activityResponseDtoList.size(); i < len; i++) {
            List<GoodsBeanDto> goodsBeanDtos = activityResponseDtoList.get(i).getGoods();
            if (CollectionUtils.isEmpty(goodsBeanDtos)) {
                continue;
            }
            boolean match = goodsBeanDtos.stream().anyMatch(k -> k.getGoodsId().equals(goodsId));
            if (match) {
                isSpecialGoods = true;
                break;
            }
        }
        return isSpecialGoods;
    }

    public static void setClassificationAndPrice(CartGoods cartGoods, List<ProductBeanDTO> productBeanListSpuClass) {
        if (productBeanListSpuClass == null || productBeanListSpuClass.size() == 0) {
            return;
        }
        cartGoods.setClassificationId(productBeanListSpuClass.get(0).getCategory());
        cartGoods.setClassificationName(productBeanListSpuClass.get(0).getCategoryName());

        if (StringUtils.isBlank(productBeanListSpuClass.get(0).getCustomerCode())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_SEAT_EMPTY);
        }

        //超值加购商品赋值
        if (ObjectUtils.equals(GoodsTypeEnum.REDUCE_PRICE_GOODS.getGoodsType(), cartGoods.getGoodsType())
                || ObjectUtils.equals(GoodsTypeEnum.COUPON_GOODS.getGoodsType(), cartGoods.getGoodsType())) {
            cartGoods.setOriginalPrice(productBeanListSpuClass.get(0).getOriginalPrice());
            cartGoods.setFinalPrice(productBeanListSpuClass.get(0).getFinalPrice());
            cartGoods.setPackPrice(productBeanListSpuClass.get(0).getPackPrice());
            cartGoods.setCustomerCode(productBeanListSpuClass.get(0).getCustomerCode());
            cartGoods.setName(productBeanListSpuClass.get(0).getName());
            cartGoods.setSpuName(productBeanListSpuClass.get(0).getName());
            cartGoods.setSkuName(productBeanListSpuClass.get(0).getName());
            cartGoods.setPic(productBeanListSpuClass.get(0).getPicture());
            cartGoods.setStockLimit(productBeanListSpuClass.get(0).getStockLimit() == 1);
            cartGoods.setTax(productBeanListSpuClass.get(0).getTax());
            cartGoods.setTaxId(productBeanListSpuClass.get(0).getTaxId());
        }

        //套餐商品赋值
        if (ObjectUtils.equals(GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType(), cartGoods.getGoodsType())){
//            cartGoods.setOriginalPrice(productBeanListSpuClass.get(0).getOriginalPrice());
//            cartGoods.setFinalPrice(productBeanListSpuClass.get(0).getFinalPrice());
//            cartGoods.setPackPrice(productBeanListSpuClass.get(0).getPackPrice());
            cartGoods.setCustomerCode(productBeanListSpuClass.get(0).getCustomerCode());
            cartGoods.setName(productBeanListSpuClass.get(0).getName());
            cartGoods.setSpuName(productBeanListSpuClass.get(0).getName());
            cartGoods.setSkuName(productBeanListSpuClass.get(0).getName());
            cartGoods.setPic(productBeanListSpuClass.get(0).getPicture());
            cartGoods.setStockLimit(productBeanListSpuClass.get(0).getStockLimit() == 1);
            cartGoods.setTax(productBeanListSpuClass.get(0).getTax());
            cartGoods.setTaxId(productBeanListSpuClass.get(0).getTaxId());

            //套餐固定商品赋值
            if (CollectionUtils.isNotEmpty(productBeanListSpuClass.get(0).getProductComboList()) && CollectionUtils.isNotEmpty(cartGoods.getProductComboList())){

                Map<String, Integer> productMap = productBeanListSpuClass.get(0).getProductComboList().stream()
                        .collect(Collectors.toMap(ProductBeanDTO.ProductComboType::getProductId, ProductBeanDTO.ProductComboType::getQuantity, (k1,k2) -> k1+k2));

                if(StringUtils.isNotBlank(cartGoods.getCouponCode())) {
                    for (CartGoods.ComboxGoods comboxGoods : cartGoods.getProductComboList()) {
                        comboxGoods.setQty(productMap.get(comboxGoods.getGoodsId()));
                    }
                } else {
                    Map<String, Integer> cartGoodsMap = cartGoods.getProductComboList().stream()
                            .collect(Collectors.toMap(
                                    o -> (StringUtils.isBlank(o.getSpuId()) || "0".equals(o.getSpuId()))?o.getSkuId():o.getSpuId(),
                                    CartGoods.ComboxGoods::getQty,
                                    (k1, k2) -> k1+k2));

                    if(productMap.entrySet().stream().filter(o -> !o.getValue().equals(cartGoodsMap.get(o.getKey()))).findFirst().isPresent()) {
                        throw new ServiceException(ResponseResult.SHOPPING_CART_VERSION_ERROR, "加购套餐子商品数量异常");
                    }
                }
            }

            //套餐可选商品赋值
//            if (CollectionUtils.isNotEmpty(productBeanListSpuClass.get(0).getProductGroupList())){
//                for (ProductBeanDTO.ProductGroupType groupType : productBeanListSpuClass.get(0).getProductGroupList()) {
//                    if (CollectionUtils.isNotEmpty(groupType.getGroupDetail())){
//                        for (ProductBeanDTO.ProductGroupType.GroupDetailType detailType : groupType.getGroupDetail()) {
//                            for (CartGoods.ComboxGoods groupGoods : cartGoods.getProductGroupList()) {
//                                if (detailType.getProductId().equals(groupGoods.getGoodsId())) {
//                                    groupGoods.setFinalPrice(detailType.getMarkUpPrice().longValue());
//                                    groupGoods.setOriginalPrice(detailType.getProductPrice().longValue());
//                                }
//                            }
//                        }
//                    }
//                }
//            }
        }
    }


    public static CartGoods convent2CartGoods(MCoffeeAddGoodsRequestVo addShoppingCartGoodsRequestVo, String goodsId) {
        String spuId = addShoppingCartGoodsRequestVo.getSpuId();
        String skuId = addShoppingCartGoodsRequestVo.getSkuId();
//        String goodsId = StringUtils.isEmpty(skuId) ? spuId : skuId;
        Integer qty = addShoppingCartGoodsRequestVo.getQty() == null ? 1 : addShoppingCartGoodsRequestVo.getQty();
        CartGoods cartGoods = new CartGoods();
        cartGoods.setGoodsId(goodsId);
        cartGoods.setSpuId(spuId);
        cartGoods.setSkuId(skuId);
        cartGoods.setQty(qty);
        cartGoods.setIsMonthCard(addShoppingCartGoodsRequestVo.getIsMonthCard());
        cartGoods.setIsB3S1Coupon(addShoppingCartGoodsRequestVo.getIsB3S1Coupon());
        cartGoods.setIsMonthCardGoods(addShoppingCartGoodsRequestVo.getIsMonthCardGoods());
        cartGoods.setIsB3S1CouponGoods(addShoppingCartGoodsRequestVo.getIsB3S1Coupon());
        cartGoods.setCouponCode(addShoppingCartGoodsRequestVo.getCouponCode());
        Integer goodsType = StringUtils.isEmpty(skuId) || ObjectUtils.equals(spuId, skuId) ? GoodsTypeEnum.SPU_GOODS.getGoodsType() : GoodsTypeEnum.SKU_GOODS.getGoodsType();
        if (CollectionUtils.isNotEmpty(addShoppingCartGoodsRequestVo.getProductComboList()) || CollectionUtils.isNotEmpty(addShoppingCartGoodsRequestVo.getProductGroupList())) {
            goodsType = GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType();
        } else if (CommonsConstant.COUPON_TYPE.equals(addShoppingCartGoodsRequestVo.getCouponType())){
            goodsType = GoodsTypeEnum.ALL_COUPON_GOODS.getGoodsType();
        } else if (Objects.equals(1,addShoppingCartGoodsRequestVo.getIsMonthCard()) || Objects.equals(1,addShoppingCartGoodsRequestVo.getIsB3S1Coupon())){
            goodsType = GoodsTypeEnum.VIRTUAL_GOODS.getGoodsType();
        }

        if (addShoppingCartGoodsRequestVo.getOperationType() != null && addShoppingCartGoodsRequestVo.getOperationType() == 2) {
            goodsType = GoodsTypeEnum.REDUCE_PRICE_GOODS.getGoodsType();
        }
        //月享卡信息
        if (null != addShoppingCartGoodsRequestVo.getMonthCardInfo()){
            cartGoods.setMonthCardInfo(addShoppingCartGoodsRequestVo.getMonthCardInfo());
        }
        if (null != addShoppingCartGoodsRequestVo.getB3S1CouponGoodsInfo()){
            cartGoods.setB3S1CouponGoodsInfo(addShoppingCartGoodsRequestVo.getB3S1CouponGoodsInfo());
        }
        cartGoods.setGoodsType(goodsType);
        cartGoods.setExtra(addShoppingCartGoodsRequestVo.getExtra());
        cartGoods.setSpecialExtra(addShoppingCartGoodsRequestVo.getSpecialExtra());
        cartGoods.setNodeId(addShoppingCartGoodsRequestVo.getNodeId());
        cartGoods.setCategoryName(addShoppingCartGoodsRequestVo.getCategoryName());
        List<CartGoods.ComboxGoods> productComboList = new ArrayList<>();
        List<CartGoods.ComboxGoods> productGroupList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(addShoppingCartGoodsRequestVo.getProductComboList())) {
            for (ComboxGoodsRequestVo vo : addShoppingCartGoodsRequestVo.getProductComboList()) {
                CartGoods.ComboxGoods productCombox = new CartGoods.ComboxGoods();
                productCombox.setGoodsId(vo.getSkuId());
                productCombox.setSkuId(vo.getSkuId());
                productCombox.setSpuId(vo.getSpuId());
                productCombox.setQty(vo.getQty());
                productCombox.setExtra(vo.getExtra());
                productCombox.setSpecialExtra(vo.getSpecialExtra());
                //加料商品集
                if (CollectionUtils.isNotEmpty(vo.getProductMaterialList())) {
                    List<CartGoods.MaterialGoods> comboxMaterialGoodsList = new ArrayList<>();
                    for (MaterialRequestVo materialRequestVo : vo.getProductMaterialList()) {
                        CartGoods.MaterialGoods materialGoods = new CartGoods.MaterialGoods();
                        materialGoods.setSpuId(materialRequestVo.getSpuId());
                        materialGoods.setCustomerCode(materialRequestVo.getCustomerCode());
//                        materialGoods.setGroupId(materialRequestVo.getGroupId());
                        comboxMaterialGoodsList.add(materialGoods);
                    }
                    productCombox.setProductMaterialList(comboxMaterialGoodsList);
                }
                productComboList.add(productCombox);
            }
        }
        if (CollectionUtils.isNotEmpty(addShoppingCartGoodsRequestVo.getProductGroupList())) {
            for (ComboxGoodsRequestVo vo : addShoppingCartGoodsRequestVo.getProductGroupList()) {
                CartGoods.ComboxGoods productCombox = new CartGoods.ComboxGoods();
                productCombox.setGoodsId(vo.getSkuId());
                productCombox.setSkuId(vo.getSkuId());
                productCombox.setSpuId(vo.getSpuId());
                productCombox.setQty(vo.getQty());
                productCombox.setExtra(vo.getExtra());
                productCombox.setSpecialExtra(vo.getSpecialExtra());
                productCombox.setProductGroupId(StringUtils.isEmpty(vo.getProductGroupId()) ? null : Long.parseLong(vo.getProductGroupId()));
                if(StringUtils.isNotEmpty(vo.getEmptyKey())){
                    productCombox.setGoodsId("0");
                    productCombox.setSkuId("0");
                    productCombox.setSpuId("0");
                    productCombox.setCustomerCode(vo.getEmptyKey());
                    productCombox.setName("无");
                    productCombox.setSpuName("无");
                    productCombox.setSkuName("无");
                    productCombox.setFinalPrice(0L);
                    productCombox.setOriginalPrice(0L);
                    productCombox.setOriginalAmount(0L);
                    productCombox.setAmount(0L);
                    productCombox.setQty(1);
                }
                //加料商品集
                if (CollectionUtils.isNotEmpty(vo.getProductMaterialList())) {
                    List<CartGoods.MaterialGoods> comboxMaterialGoodsList = new ArrayList<>();
                    for (MaterialRequestVo materialRequestVo : vo.getProductMaterialList()) {
                        CartGoods.MaterialGoods materialGoods = new CartGoods.MaterialGoods();
                        materialGoods.setSpuId(materialRequestVo.getSpuId());
                        materialGoods.setGroupId(materialRequestVo.getGroupId());
                        materialGoods.setCustomerCode(materialRequestVo.getCustomerCode());
                        comboxMaterialGoodsList.add(materialGoods);
                    }
                    productCombox.setProductMaterialList(comboxMaterialGoodsList);
                }
                productGroupList.add(productCombox);
            }
        }

        //加料商品集
        if (CollectionUtils.isNotEmpty(addShoppingCartGoodsRequestVo.getProductMaterialList())) {
            List<CartGoods.MaterialGoods> materialGoodsList = new ArrayList<>();
            for (MaterialRequestVo materialRequestVo : addShoppingCartGoodsRequestVo.getProductMaterialList()) {
                CartGoods.MaterialGoods materialGoods = new CartGoods.MaterialGoods();
                materialGoods.setSpuId(materialRequestVo.getSpuId());
                materialGoods.setGroupId(materialRequestVo.getGroupId());
                materialGoods.setCustomerCode(materialRequestVo.getCustomerCode());
                materialGoodsList.add(materialGoods);
            }
            cartGoods.setProductMaterialList(materialGoodsList);
        }
        cartGoods.setProductComboList(productComboList);
        cartGoods.setProductGroupList(productGroupList);
        return cartGoods;
    }

    /**
     * 购物车商品check，加购商品不在菜单不check
     */
    private List<CartGoods> checkCartGoods(String partnerId, String storeId, Integer orderType, String menuType,
                                           ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo, List<CartGoods> cartGoodsList, String sessionId) {

        //筛选数量不为0商品 && 非月享卡2.0虚拟商品
        cartGoodsList = cartGoodsList.stream().filter(cartGoods -> cartGoods.getQty() != 0 && !StringUtils.equals("9999",cartGoods.getSkuId())).collect(Collectors.toList());

        //筛选非超值加购活动商品--超值加购活动商品不校验是否在菜单，不调用validateShopProduct
        List<CartGoods> checkGoods = cartGoodsList.stream().filter(cartGoods -> cartGoods.getGoodsType() != GoodsTypeEnum.REDUCE_PRICE_GOODS.getGoodsType()).collect(Collectors.toList());
        //超值加购活动商品
        List<CartGoods> reduceGoods = cartGoodsList.stream().filter(cartGoods -> cartGoods.getGoodsType() == GoodsTypeEnum.REDUCE_PRICE_GOODS.getGoodsType()).collect(Collectors.toList());

        List<CartGoods> temList = new ArrayList<>();
        CartGoods b3S1CartGoods = null;
        for (CartGoods cartGoods : checkGoods) {
            if("9998".equals(cartGoods.getSkuId())) {
                b3S1CartGoods = cartGoods;
            } else {
                temList.add(cartGoods);
            }
        }

        List<CartGoods> allCartGoodsList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(temList)) {
            //当商品全部添加完毕,校验购物车商品(是否合法,上下架,点餐方式,是否在当前菜单中...),并移除非法商品
            CheckCartRequest checkCartRequest = checkShoppingCartSdkForMCoffee(temList, partnerId,
                    storeId, shoppingCartGoodsResponseVo, orderType, sessionId, menuType, shoppingCartBaseService);
            if (checkCartRequest.getShoppingCartGoodsResponseVo() != null) {
                shoppingCartGoodsResponseVo.setToastMsg(checkCartRequest.getShoppingCartGoodsResponseVo().getToastMsg());
                shoppingCartGoodsResponseVo.setChanged(checkCartRequest.getShoppingCartGoodsResponseVo().getChanged());
            }
            allCartGoodsList = JSONArray.parseArray(JSONObject.toJSONString(checkCartRequest.getCartGoodsList()), CartGoods.class);
        }
        if(null != b3S1CartGoods) {
            allCartGoodsList.add(b3S1CartGoods);
        }

        //添加商品为超值加购活动商品
        if (CollectionUtils.isNotEmpty(reduceGoods)) {
            allCartGoodsList.addAll(reduceGoods);
        }

        if (CollectionUtils.isNotEmpty(allCartGoodsList)) {
            int size = allCartGoodsList.size();

            for(int i=0;i<size;i++) {
                //如果是先把月享卡放到最后
                if(Objects.equals(1,allCartGoodsList.get(i).getIsMonthCard())) {
                    CartGoods cartGoods = allCartGoodsList.get(i);
                    if(i != size-1) {
                        allCartGoodsList.remove(i);
                        allCartGoodsList.add(cartGoods);
                        break;
                    }
                }
            }

            for(int i=0;i<size;i++) {
                //如果是餐具商品，则放到最后
                if(allCartGoodsList.get(i).getSkuId().equals(mcCafeTablewareSkuId)) {
                    CartGoods cartGoods = allCartGoodsList.get(i);
                    cartGoods.setIsTableware(true);
                    if(i != size-1) {
                        allCartGoodsList.remove(i);
                        allCartGoodsList.add(cartGoods);
                        break;
                    }
                }
            }
        }

        return allCartGoodsList;
    }


    /**
     * 【去支付使用】购物车商品check，加购商品不在菜单不check
     */
    private CheckCartRequest checkCartGoodsForToPay(String partnerId, String storeId, Integer orderType, String menuType,
                                                    ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo, List<CartGoods> cartGoodsList) {

        //筛选数量不为0商品
        cartGoodsList = cartGoodsList.stream().filter(cartGoods -> cartGoods.getQty() != 0 && !StringUtils.equals("9999",cartGoods.getSkuId())).collect(Collectors.toList());

        //筛选非加购商品--加价购商品不校验是否在菜单，不调用validateShopProduct
        List<CartGoods> checkGoods = cartGoodsList.stream().filter(cartGoods -> cartGoods.getGoodsType() != GoodsTypeEnum.REDUCE_PRICE_GOODS.getGoodsType()).collect(Collectors.toList());
        CheckCartRequest checkCartRequest = null;
        if (CollectionUtils.isNotEmpty(checkGoods)) {
            //当商品全部添加完毕,校验购物车商品(是否合法,上下架,点餐方式,是否在当前菜单中...),并移除非法商品
            checkCartRequest = checkShoppingCartSdkForMCoffee(checkGoods, partnerId,
                    storeId, shoppingCartGoodsResponseVo, orderType, "", menuType, shoppingCartBaseService);
        }
        return checkCartRequest;
    }

    private List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> getCoupon(String couponCode, String activityCode, List<CartGoods> cartGoodsList,String freightCouponCode,String buyMonthlyCard) {

        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = new ArrayList<>();
        if (StringUtils.isNotEmpty(couponCode)) {
            ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon coupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
            coupon.setCode(couponCode);
            coupon.setActivityCode(activityCode);
            coupons.add(coupon);
        }
        if (StringUtils.isNotEmpty(buyMonthlyCard) ) {
            ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon coupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
            coupon.setCode(buyMonthlyCard);
            coupons.add(coupon);
        }
        if (StringUtils.isNotEmpty(freightCouponCode)) {
            ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon coupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
            coupon.setCode(freightCouponCode);
            coupon.setActivityCode(activityCode);
            coupons.add(coupon);
        }

        //购物车商品券
        if (CollectionUtils.isNotEmpty(cartGoodsList)) {
            for (CartGoods cartGoods : cartGoodsList) {
                //购物车已存在商品券
                if (null != cartGoods) {
                    if (StringUtils.isNotEmpty(cartGoods.getCouponCode())) {
                        ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
                        calculationDiscountCoupon.setCode(cartGoods.getCouponCode());
                        coupons.add(calculationDiscountCoupon);
                    }
                    if (null != cartGoods.getMonthCardInfo()
                            && StringUtils.isNotEmpty(cartGoods.getMonthCardInfo().getCardCode())
                            && 1 == cartGoods.getMonthCardInfo().getIsUseMonthCard()) {
                        ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
                        calculationDiscountCoupon.setCode(cartGoods.getMonthCardInfo().getCardCode());
                        coupons.add(calculationDiscountCoupon);
                    }
                    if (null != cartGoods.getB3S1CouponGoodsInfo()
                            && StringUtils.isNotEmpty(cartGoods.getB3S1CouponGoodsInfo().getCardCode())
                            && 1 == cartGoods.getB3S1CouponGoodsInfo().getIsUseB3S1Coupon()) {
                        ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
                        calculationDiscountCoupon.setCode(cartGoods.getB3S1CouponGoodsInfo().getCardCode());
                        coupons.add(calculationDiscountCoupon);
                    }
                    if(null != cartGoods && "9998".equals(cartGoods.getSkuId())) {
                        for (String code : cartGoods.getB3S1CouponGoodsInfo().getCardCodeSet()) {
                            ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
                            calculationDiscountCoupon.setCode(code);
                            coupons.add(calculationDiscountCoupon);
                        }
                    }
                }
            }
        }
        if (CollectionUtils.isNotEmpty(coupons)){
            coupons = coupons.stream().distinct().collect(Collectors.toList());
        }
        return coupons;
    }

    /**
     * 【麦咖啡】调用SDK校验购物车
     *
     * @param oldAllCartGoodsList
     * @param partnerId
     * @param storeId
     * @param shoppingCartGoodsResponseVo
     * @param orderType
     */
    public CheckCartRequest checkShoppingCartSdkForMCoffee(List<CartGoods> oldAllCartGoodsList, String partnerId, String storeId, ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo
            , Integer orderType, String sessionId, String menuType ,ShoppingCartBaseService shoppingCartService) {
        CheckCartRequest checkCartRequest = new CheckCartRequest();
        checkCartRequest.setCartGoodsList(JSONArray.parseArray(JSONObject.toJSONString(oldAllCartGoodsList), com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.class));
        checkCartRequest.setOrderWay(orderType);
        checkCartRequest.setPartnerId(partnerId);
        checkCartRequest.setShoppingCartGoodsResponseVo(JSONObject.parseObject(JSONObject.toJSONString(shoppingCartGoodsResponseVo), com.freemud.sdk.api.assortment.shoppingcart.domain.ShoppingCartGoodsResponseVo.class));
        checkCartRequest.setStoreId(storeId);
        checkCartRequest.setSessionId(sessionId);
        checkCartRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        checkCartRequest.setMenuType(BusinessTypeEnum.getByType(menuType).getCode());
        BaseResponse<CheckCartRequest> baseResponse ;
        baseResponse= checkAllCartGoodsForMCoffee(checkCartRequest);
        if (baseResponse == null) {
            return null;
        }
        return baseResponse.getResult();
    }

    public BaseResponse<CheckCartRequest> checkAllCartGoodsForMCoffee(CheckCartRequest checkCartRequest) {
        try {
            ValidateShopProductRequest validateShopProductRequest = shoppingCartConvertAdapter.getValidateShopProductRequest(checkCartRequest);
            ProductBaseResponse<ValiadShopProductResponse> valiadResponse = productClient.validateShopProductAboutReason(validateShopProductRequest);
            if (valiadResponse == null || !CartResponseConstant.SUCCESS.getCode().equals(valiadResponse.getErrcode().toString()) || valiadResponse.getData()==null) {
                checkCartRequest.getCartGoodsList().clear();
                checkCartRequest.getShoppingCartGoodsResponseVo().setChanged(true);
                checkCartRequest.getShoppingCartGoodsResponseVo().setToastMsg(com.freemud.sdk.api.assortment.shoppingcart.constant.ShoppingCartConstant.SHOPPING_CART_INVALIAD_GOODS);
                return CartResponseUtil.error(valiadResponse.getErrmsg(),checkCartRequest);
            }
            ValiadShopProductResponse validateResult = valiadResponse.getData();
            CartGoodsStates cartGoodsStates = new CartGoodsStates();

            String toastMsg = "";
            //非法商品（商品是否存在、商品是否处于上架状态）自动移除，返回前端提示
            if (CollectionUtils.isNotEmpty(validateResult.getFailureList())){
                List<String> invalidSpu = new ArrayList<>();
                List<String> notFoundSpu = new ArrayList<>();
                List<String> numErrorSpu = new ArrayList<>();
                List<String> changePriceSpu = new ArrayList<>();
                List<String> disableCoupon = new ArrayList<>();
                for (int i = 0; i < validateResult.getFailureList().size(); i++) {
                    checkCartRequest.getShoppingCartGoodsResponseVo().setChanged(true);
                    ValiadShopProductResult validaProduct = validateResult.getFailureList().get(i);
                    for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods cartGoods : checkCartRequest.getCartGoodsList()) {
                        //如果购物车中存在月享卡，则将商品返回的卡券信息替换购物车中的卡券信息
                        replaceMonthCardInfo(validaProduct,cartGoods);
                        if (cartGoods.getSkuId().equals(validaProduct.getSkuId())) {
                            String spuName = null == validaProduct.getProductType() ? cartGoods.getSpuName() : validaProduct.getProductType().getName();
                            String couponName = StringUtils.isNotEmpty(cartGoods.getCouponName()) ? cartGoods.getCouponName() : "";
                            if (PRODUCT_DOWN == validaProduct.getCode()) {
                                invalidSpu.add(spuName);
                                if (StringUtils.isNotEmpty(couponName)){
                                    disableCoupon.add(couponName);
                                }
                                cartGoodsStates.setHasInvalidGoods(true);
                                cartGoods.setCartGoodsUid(null);
                                break;
                            }
                            if (PRODUCT_NOTFOUND == validaProduct.getCode()) {
                                notFoundSpu.add(spuName);
                                if (StringUtils.isNotEmpty(couponName)){
                                    disableCoupon.add(couponName);
                                }
                                cartGoodsStates.setHasInvalidGoods(true);
                                cartGoods.setCartGoodsUid(null);
                                break;
                            }
                            if (111 == validaProduct.getCode() || 112 == validaProduct.getCode()) {
                                numErrorSpu.add(spuName);
                                if (StringUtils.isNotEmpty(couponName)){
                                    disableCoupon.add(couponName);
                                }
                                cartGoodsStates.setHasInvalidGoods(true);
                                cartGoods.setCartGoodsUid(null);
                                break;
                            }
                            if (PRODUCT_PRICE_CHANGE == validaProduct.getCode()) {
                                changePriceSpu.add(spuName);
                                shoppingCartConvertAdapter.updateCartGoodsInfo(cartGoods, validaProduct.getProductType(), validaProduct.getSubProductTypeMap());
                            }
                            if (PRODUCT_GROUP_PRICE_CHANGE == validaProduct.getCode()) {
                                changePriceSpu.add(spuName);
                                shoppingCartConvertAdapter.updateCartGoodsInfo(cartGoods, validaProduct.getProductType(), validaProduct.getSubProductTypeMap());
                            }
                            if (PRODUCT_GROUP_EMPTY == validaProduct.getCode()) {
                                cartGoodsStates.setHasInvalidGoods(true);
                                cartGoods.setCartGoodsUid(null);
                                toastMsg = toastMsg.concat(CART_PRODUCT_GROUP_EMPTY_STATE.replace("$spuName",StringUtils.join(Arrays.asList(spuName),",")));
                                break;
                            }
                        }
                    }
                }

                if (CollectionUtils.isNotEmpty(invalidSpu)){
                    toastMsg = toastMsg.concat(CART_PRODUCT_INVALID_STATE.replace("$spuName",StringUtils.join(invalidSpu,",")));
                }
                if (CollectionUtils.isNotEmpty(notFoundSpu)){
                    toastMsg = toastMsg.concat(CART_PRODUCT_NOT_FOUND.replace("$spuName",StringUtils.join(notFoundSpu,",")));
                }

                if (CollectionUtils.isNotEmpty(changePriceSpu)){
                    toastMsg = toastMsg.concat(CART_PRODUCT_PRICE_CHANGE.replace("$spuName",StringUtils.join(changePriceSpu,",")));
                }
                if (CollectionUtils.isNotEmpty(numErrorSpu)){
                    toastMsg = toastMsg.concat("您选择的【$spuName】不满足购买条件".replace("$spuName",StringUtils.join(numErrorSpu,",")));
                }

                if (CollectionUtils.isNotEmpty(disableCoupon)){
                    toastMsg = toastMsg.concat(COUPON_IS_DISABLE.replace("$couponName",StringUtils.join(disableCoupon,",")));
                }

                checkCartRequest.getShoppingCartGoodsResponseVo().setToastMsg(toastMsg);

                setToastMsgIfNotExist(checkCartRequest.getShoppingCartGoodsResponseVo(), com.freemud.sdk.api.assortment.shoppingcart.constant.ShoppingCartConstant.SHOPPING_CART_GOODS_CHANGE);
                checkCartRequest.getCartGoodsList().removeIf(k ->  StringUtils.isEmpty(k.getCartGoodsUid()));
            }
            for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods cartGoods : checkCartRequest.getCartGoodsList()) {
                // 当goodsId为空或商品是商品券时直接跳过
                if (StringUtils.isEmpty(cartGoods.getGoodsId()) || Objects.equals(cartGoods.getGoodsType(), com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.COUPON_GOODS.getGoodsType())) {
                    continue;
                }
                for (ValiadShopProductResult valiadShopProductResult : validateResult.getSuccessList()){
                    //如果购物车中存在月享卡，则将商品返回的卡券信息替换购物车中的卡券信息
                    replaceMonthCardInfo(valiadShopProductResult,cartGoods);
                    ProductTypeBeanDTO productType = valiadShopProductResult.getProductType();
                    if(ObjectUtils.equals(valiadShopProductResult.getUuid(), cartGoods.getCartGoodsUid())){
                        //多规格商品更新套餐价格为商品返回
                        if(!Objects.equals(cartGoods.getSkuId(),cartGoods.getSpuId())) {
                            cartGoods.setFinalPrice(valiadShopProductResult.getProductType().getFinalPrice());
                            cartGoods.setOriginalPrice(valiadShopProductResult.getProductType().getFinalPrice());
                        }
                        Map<String,ProductTypeBeanDTO> subProductTypeMap = valiadShopProductResult.getSubProductTypeMap();
                        shoppingCartConvertAdapter.updateCartGoodsInfo(cartGoods, productType,subProductTypeMap);
                        break;
                    }
                }
            }
            //校验商品券是否有当前点餐方式
//            cartGoodsStates = updateSpqCartGoodsInfo(checkCartRequest.getCartGoodsList(), checkCartRequest.getOrderWay(), checkCartRequest.getPartnerId(), checkCartRequest.getTrackingNo(), cartGoodsStates
//                    , checkCartRequest.getStoreId());

            // 点餐方式改变商品券发生变动
            if (cartGoodsStates != null && cartGoodsStates.isOrderWayFlag()) {
                setToastMsgIfNotExist(checkCartRequest.getShoppingCartGoodsResponseVo(), com.freemud.sdk.api.assortment.shoppingcart.constant.ShoppingCartConstant.ORDER_WAY_CHANGE);
            }
            //若商品详情赋值有异常，直接移除购物车
            if (checkCartRequest.getCartGoodsList().stream().anyMatch(cart -> StringUtils.isEmpty(cart.getCartGoodsUid()))) {
                checkCartRequest.getCartGoodsList().removeIf(k -> StringUtils.isEmpty(k.getCartGoodsUid()));
                checkCartRequest.getShoppingCartGoodsResponseVo().setChanged(true);
                checkCartRequest.getShoppingCartGoodsResponseVo().setToastMsg(com.freemud.sdk.api.assortment.shoppingcart.constant.ShoppingCartConstant.SHOPPING_CART_INVALIAD_GOODS);
            }
//            if (checkCartRequest.getCartGoodsList().stream().anyMatch(cart -> cart.getGoodsType().equals(GoodsTypeEnum.EXCEPTION_GOODS.getGoodsType()))) {
//                checkCartRequest.getCartGoodsList().removeIf(k -> k.getGoodsType().equals(GoodsTypeEnum.EXCEPTION_GOODS.getGoodsType()));
//                checkCartRequest.getShoppingCartGoodsResponseVo().setChanged(true);
//                checkCartRequest.getShoppingCartGoodsResponseVo().setToastMsg(ShoppingCartConstant.SHOPPING_CART_MATERIAL_ERROR);
//            }
            return CartResponseUtil.success(checkCartRequest);
        } catch (Exception e) {
            ErrorLog.printErrorLog("assortment-shoppingcart-sdk", checkCartRequest.getTrackingNo(), e.getMessage(), "checkAllCartGoods", checkCartRequest, e, Level.ERROR);
            checkCartRequest.getShoppingCartGoodsResponseVo().setChanged(true);
            checkCartRequest.getShoppingCartGoodsResponseVo().setToastMsg(com.freemud.sdk.api.assortment.shoppingcart.constant.ShoppingCartConstant.SHOPPING_CART_INVALIAD_GOODS);
            return CartResponseUtil.error(e.getMessage(),checkCartRequest);
        }
    }

    private void setToastMsgIfNotExist(com.freemud.sdk.api.assortment.shoppingcart.domain.ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, String message) {
        if (StringUtils.isEmpty(shoppingCartGoodsResponseVo.getToastMsg())) {
            shoppingCartGoodsResponseVo.setToastMsg(message);
        }
    }

    public BaseResponse updateGoodsByCard(MCoffeeCardAddVo cardAddVo) {
        // 参数校验
        if (StringUtils.isEmpty(cardAddVo.getShopId())) {
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_SHOP_ID_NOT_EMPTY);
        }
        if (cardAddVo.getQty() != null && cardAddVo.getQty() < 0) {
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_ADD_ERROR);
        }
        String sessionId = cardAddVo.getSessionId();
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(sessionId);
        ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsResponseVo();
        String userId = assortmentCustomerInfoVo.getMemberId();
        String partnerId = cardAddVo.getPartnerId();
        String storeId = cardAddVo.getShopId();
        String appId = cardAddVo.getAppId();
        String spuId = cardAddVo.getSpuId();
        String skuId = StringUtils.isNotBlank(cardAddVo.getSkuId()) ? cardAddVo.getSkuId() : "";
        String goodsId = StringUtils.isEmpty(skuId) ? spuId : skuId;
        String menuType = cardAddVo.getMenuType();
        Integer orderType = cardAddVo.getOrderType();
        String couponCode = cardAddVo.getCouponCode();
        String receiveId = cardAddVo.getReceiveId();
        // 查询购物车缓存
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, null, null, shoppingCartBaseService);

        // 如果购物车商品不为空， 则check购物车中所有商品
        if (CollectionUtils.isNotEmpty(cartGoodsList)) {
            // check购物车中所有商品
//            cartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, cartGoodsList);
            List<CartGoods> temList = new ArrayList<>();
            for (CartGoods goods : cartGoodsList) {
                temList.addAll(checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, Arrays.asList(goods), sessionId));
            }
            cartGoodsList = temList;
            // 重新存储最新购物车
            assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, sessionId, "", shoppingCartBaseService);

            if (StringUtils.isNotEmpty(couponCode) && StringUtils.isNotEmpty(goodsId)) {
                CartGoods couponGoods = cartGoodsList.stream().filter(t -> couponCode.equals(t.getCouponCode())).findFirst().orElse(null);
                CartGoods cartGoods =new CartGoods();
                if (couponGoods !=null) {
                    cartGoods = cartGoodsList.stream().filter(t -> (t.getGoodsId().equals(goodsId) && (!t.getCartGoodsUid().equals(couponGoods.getCartGoodsUid())))).findFirst().orElse(null);
                }else {
                    cartGoods = cartGoodsList.stream().filter(t -> (t.getGoodsId().equals(goodsId))).findFirst().orElse(null);
                }
                if (cartGoods != null) {
                    if (cardAddVo.getIsSelect()) {
                        //修改购物车商品数量
                        UpdateShoppingCartGoodsQtyRequestVo vo = updateCartVo(cartGoods, cardAddVo, false);
                        updateGoodsQty(vo);
                        //添加商品券到购物车
                        MCoffeeAddGoodsRequestVo requestVo = addCartVO(cardAddVo, true);
                        addGoods(requestVo);
                    } else {
                        if (couponGoods != null) {
                            //删除购物车行，因为商品券再购物车始终是一
                            UpdateShoppingCartGoodsQtyRequestVo vo = updateCartVo(cartGoods, cardAddVo, false);
                            updateGoodsQty(vo);
                            if (cartGoods.getQty() >= 1) {
                                //修改购物车商品数量
                                UpdateShoppingCartGoodsQtyRequestVo requestVo = updateCartVo(couponGoods, cardAddVo, true);
                                updateGoodsQty(requestVo);
                            } else {
                                MCoffeeAddGoodsRequestVo requestVo = addCartVO(cardAddVo, false);
                                addGoods(requestVo);
                            }
                        }
                    }
                }else {
                    if (couponGoods != null) {
                        //删除购物车行，因为商品券再购物车始终是一
                        UpdateShoppingCartGoodsQtyRequestVo vo = updateCartVo(couponGoods, cardAddVo, false);
                        updateGoodsQty(vo);
                        MCoffeeAddGoodsRequestVo requestVo = addCartVO(cardAddVo, false);
                        addGoods(requestVo);
                    }
                }
                cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, null, null, shoppingCartBaseService);
            }
        }
        // 当couponCode不为空时，需参与价格计算
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = getCoupon(couponCode, null, cartGoodsList,null,null);

        // 促销活动的优惠金额计算
        calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, null,
                cartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo,null);
        //设置更新响应信息
        ShoppingCartInfoRequestVo shoppingCartInfoRequestVo =new ShoppingCartInfoRequestVo();
        BeanUtil.convertBean(cardAddVo,shoppingCartInfoRequestVo);
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), ShoppingCartConstant.QUERY_INFO, shoppingCartInfoRequestVo);

        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }


    private UpdateShoppingCartGoodsQtyRequestVo updateCartVo(CartGoods cartGoods,MCoffeeCardAddVo cardAddVo,Boolean isAdd){
        UpdateShoppingCartGoodsQtyRequestVo vo = new UpdateShoppingCartGoodsQtyRequestVo();
        vo.setCartGoodsUid(cartGoods.getCartGoodsUid());
        vo.setPartnerId(cardAddVo.getPartnerId());
        if (isAdd){
            vo.setQty(cartGoods.getQty() + 1);
        }else {
            vo.setQty(cartGoods.getQty() - 1);
        }
        vo.setOrderType(cardAddVo.getOrderType());
        vo.setShopId(cardAddVo.getShopId());
        vo.setMenuType(cardAddVo.getMenuType());
        vo.setChannelType(cardAddVo.getChannelType());
        vo.setAppId(cardAddVo.getAppId());
        vo.setSessionId(cardAddVo.getSessionId());
        return vo;
    }

    private MCoffeeAddGoodsRequestVo addCartVO(MCoffeeCardAddVo cardAddVo,Boolean isCoupon){
        MCoffeeAddGoodsRequestVo requestVo = new MCoffeeAddGoodsRequestVo();
        BeanUtil.convertBean(cardAddVo,requestVo);
        requestVo.setQty(1);
        if (isCoupon) {
            requestVo.setCategoryName("DSPQ");
            requestVo.setCouponCode(cardAddVo.getCouponCode());
        }
        return requestVo;
    }

    private String getCouponNameByCode(String couponCode,CustomerInfoVo userInfo,String menuType,String storeId){
        String couponName = "";

        String partnerId = userInfo.getPartnerId();
        GetMemberCouponRequestVo requestVo = new GetMemberCouponRequestVo();
        requestVo.setPartnerId(partnerId);
        requestVo.setCouponCode(couponCode);
        requestVo.setStoreId(storeId);
        GetCouponDetailResponseDto couponDetailResponseDto = couponService.getMemberCoupon(requestVo);

        if (couponDetailResponseDto == null || !couponDetailResponseDto.getResult().equals(ResponseCodeConstant.RESPONSE_SUCCESS_1) || CollectionUtils.isEmpty(couponDetailResponseDto.getDetails())) {
            return couponName;
        }

        if (null != couponDetailResponseDto && CollectionUtils.isNotEmpty(couponDetailResponseDto.getDetails())
                && null != couponDetailResponseDto.getDetails().get(0)){
            couponName = couponDetailResponseDto.getDetails().get(0).getActive().getActiveName();
        }
        return couponName;
    }

    private MCoffeeAddGoodsRequestVo convertBatchAdd2SingleAdd(BatchGoodsInfoVo goodsInfo,
                                                               MCoffeeBatchAddGoodsRequestVo requestVo){
        MCoffeeAddGoodsRequestVo mCoffeeAddGoodsRequestVo = new MCoffeeAddGoodsRequestVo();
        mCoffeeAddGoodsRequestVo.setSessionId(requestVo.getSessionId());
        mCoffeeAddGoodsRequestVo.setPartnerId(requestVo.getPartnerId());
        mCoffeeAddGoodsRequestVo.setAppId(requestVo.getAppId());
        mCoffeeAddGoodsRequestVo.setShopId(requestVo.getShopId());
        mCoffeeAddGoodsRequestVo.setOrderType(requestVo.getOrderType());
        mCoffeeAddGoodsRequestVo.setChannelType(requestVo.getChannelType());
        mCoffeeAddGoodsRequestVo.setSpuId(goodsInfo.getSpuId());
        mCoffeeAddGoodsRequestVo.setSkuId(goodsInfo.getSkuId());
        mCoffeeAddGoodsRequestVo.setVersion(null);
        mCoffeeAddGoodsRequestVo.setNodeId(null);
        mCoffeeAddGoodsRequestVo.setCategoryName(goodsInfo.getCategoryName());
        mCoffeeAddGoodsRequestVo.setExtra(goodsInfo.getExtra());
        mCoffeeAddGoodsRequestVo.setProductComboList(goodsInfo.getProductComboList());
        mCoffeeAddGoodsRequestVo.setProductGroupList(goodsInfo.getProductGroupList());
        mCoffeeAddGoodsRequestVo.setProductMaterialList(goodsInfo.getProductMaterialList());
        mCoffeeAddGoodsRequestVo.setSpecialExtra(goodsInfo.getSpecialExtra());
        mCoffeeAddGoodsRequestVo.setAppType(null);
        mCoffeeAddGoodsRequestVo.setTableNumber(null);
        mCoffeeAddGoodsRequestVo.setQty(goodsInfo.getQty());
        mCoffeeAddGoodsRequestVo.setMenuType(requestVo.getMenuType());
        mCoffeeAddGoodsRequestVo.setReceiveId(requestVo.getReceiveId());
        mCoffeeAddGoodsRequestVo.setOperationType(goodsInfo.getOperationType());
        mCoffeeAddGoodsRequestVo.setCouponType(goodsInfo.getCouponType());
        mCoffeeAddGoodsRequestVo.setCouponThresholdAmount(goodsInfo.getCouponThresholdAmount());
        mCoffeeAddGoodsRequestVo.setIsSunnyCoupon(goodsInfo.getIsSunnyCoupon());
        mCoffeeAddGoodsRequestVo.setCouponCode(goodsInfo.getCouponCode());
        mCoffeeAddGoodsRequestVo.setGroupName(goodsInfo.getGroupName());
        mCoffeeAddGoodsRequestVo.setIsMonthCard(goodsInfo.getIsMonthCard());
        mCoffeeAddGoodsRequestVo.setIsB3S1Coupon(goodsInfo.getIsB3S1Coupon());
        mCoffeeAddGoodsRequestVo.setIsMonthCardGoods(goodsInfo.getIsMonthCardGoods());
        mCoffeeAddGoodsRequestVo.setMonthCardInfo(goodsInfo.getMonthCardInfo());
        return mCoffeeAddGoodsRequestVo;
    }

    private UpdateShoppingCartGoodsQtyRequestVo batchQtyRequestConvert2SingleQtyRequest(GoodsQtyInfo goodsQtyInfo,BatchUpdateGoodsQtyRequestVo requestVo) {
        UpdateShoppingCartGoodsQtyRequestVo singleUpdateRequest = new UpdateShoppingCartGoodsQtyRequestVo();
        singleUpdateRequest.setSessionId(requestVo.getSessionId());
        singleUpdateRequest.setAppId(requestVo.getAppId());
        singleUpdateRequest.setCartGoodsUid(goodsQtyInfo.getCartGoodsUid());
        singleUpdateRequest.setCreateCollageUserId(null);
        singleUpdateRequest.setQty(goodsQtyInfo.getQty());
        singleUpdateRequest.setOldQty(null);
        singleUpdateRequest.setVersion(requestVo.getVersion());
        singleUpdateRequest.setCarVer(requestVo.getCarVer());
        singleUpdateRequest.setMenuType(requestVo.getMenuType());
        singleUpdateRequest.setReceiveId(requestVo.getReceiveId());
        singleUpdateRequest.setPartnerId(requestVo.getPartnerId());
        singleUpdateRequest.setShopId(requestVo.getShopId());
        singleUpdateRequest.setOrderType(requestVo.getOrderType());
        singleUpdateRequest.setChannelType(requestVo.getChannelType());
        return singleUpdateRequest;
    }

    /**
     * 根据商品校验校验接口返回的卡券信息替换前段传递的
     * @param result
     * @param cartGoods
     */
    private void replaceMonthCardInfo(ValiadShopProductResult result,com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods cartGoods){
        if (null == result.getProductType() || CollectionUtils.isEmpty(result.getProductType().getProductBindingCouponTypes())){
            return;
        }
        List<ProductBindingCouponType> productBindingCouponTypes = result.getProductType().getProductBindingCouponTypes();
        if (cartGoods.getIsMonthCard() > 0 && null != cartGoods.getMonthCardInfo() && result.getSkuId().equals(cartGoods.getSkuId())){
            for (ProductBindingCouponType productBindingCouponType : productBindingCouponTypes) {
                cartGoods.getMonthCardInfo().setCardCode(productBindingCouponType.getVirtualCouponCode());
                cartGoods.getMonthCardInfo().setCardNo(productBindingCouponType.getCardId());
                cartGoods.getMonthCardInfo().setType(cartGoods.getMonthCardInfo().getType());
                ApiLog.debug("【月享卡】信息替换成功，cartGoods:{},productInfo:{}",cartGoods.toString(),result.toString());
            }
        }
    }

    /**
     * 种子加购逻辑校验
     *  1.种子券商品券信息与月卡信息一致
     *  2.种子券商品数量不可大于种子券数量
     * @param addShoppingCartGoodsRequestVo
     * @param oldCartGoodsList
     */
    private void seedCouponGoodsValidate(MCoffeeAddGoodsRequestVo addShoppingCartGoodsRequestVo,List<CartGoods> oldCartGoodsList){
        //若加购种子券商品，则券号不可为空
        if (null == addShoppingCartGoodsRequestVo.getMonthCardInfo() || StringUtils.isBlank(addShoppingCartGoodsRequestVo.getMonthCardInfo().getCardCode())){
            throw new ServiceException(ResponseResult.SHOPPING_CART_ADD_ERROR);
        }
    }

    private void seedB3S1CouponGoodsValidate(MCoffeeAddGoodsRequestVo addShoppingCartGoodsRequestVo,List<CartGoods> oldCartGoodsList){
        //若加购种子券商品，则券号不可为空
        if (null == addShoppingCartGoodsRequestVo.getB3S1CouponGoodsInfo() || StringUtils.isBlank(addShoppingCartGoodsRequestVo.getB3S1CouponGoodsInfo().getCardCode())){
            throw new ServiceException(ResponseResult.SHOPPING_CART_ADD_ERROR);
        }
    }

    /**
     * 清除购物车商品使用月卡信息
     * @param cartGoods
     * @param couponCode
     */
    private List<CartGoods> clearMonthCouponInfo(List<CartGoods> cartGoods,String couponCode,String cartGoodsUid){
        for (CartGoods cartGood : cartGoods) {
            if (StringUtils.equals(couponCode,cartGood.getCouponCode())){
                cartGood.setCouponCode(null);
                cartGood.setIsMonthCardGoods(0);
            }
        }
        return cartGoods.stream().filter(t-> !StringUtils.equals("9999",t.getSkuId()) && !t.getCartGoodsUid().equals(cartGoodsUid)).collect(Collectors.toList());
    }

    /**
     * 清除购物车商品使用买3赠1券信息
     * @param couponCode
     */
    private List<CartGoods> clearB3S1CouponInfo(List<CartGoods> cartGoodsList,String couponCode){
        cartGoodsList.removeIf(o -> couponCode.equals(o.getCouponCode()));
        return cartGoodsList;
    }
    /**
     * 清除购物车商品使用买3赠1券信息
     * @param couponCodeList
     */
    private List<CartGoods> clearB3S1CouponInfo(List<CartGoods> cartGoodsList,List<String> couponCodeList){
        cartGoodsList.removeIf(o -> couponCodeList.contains(o.getCouponCode()));
        return cartGoodsList;
    }
}
