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.ProductTypeBeanDTO;
import cn.freemud.entities.dto.product.ValiadShopProductResponse;
import cn.freemud.entities.dto.product.ValiadShopProductResult;
import cn.freemud.entities.dto.product.ValidateShopProductRequest;
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.CouponAvailableReq;
import cn.freemud.service.impl.mcoffee.entity.CouponState;
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.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 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.function.Function;
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.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */

@Slf4j
@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;

    /**
     * 添加商品、超值加购、商品券
     */
    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 threeToOneActivityCode = addShoppingCartGoodsRequestVo.getBuyThreeGiveOneActivityCode();
        String threeToOneCouponCode = addShoppingCartGoodsRequestVo.getBuyThreeGiveOneCouponCode();

        String spuId2 = spuId;
        MCoffeeProductIdsVo vo =new MCoffeeProductIdsVo();
        List<Long> productIds = new ArrayList<>();
        //商品券校验
        if (spuId.startsWith(CommonsConstant.COUPON_PREFIX)) {
            couponCode = spuId.substring(CommonsConstant.COUPON_PREFIX.length());
            vo = validCoupon(partnerId, storeId, spuId, productIds, BusinessTypeEnum.getByType(addShoppingCartGoodsRequestVo.getMenuType()).getCode());
            spuId2 = vo.getSkuId();
            goodsId = vo.getSkuId();
        }

        productIds.add(Long.parseLong(goodsId));
        // 获取添加商品的详细信息
        List<ProductBeanDTO> 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<>();
        }
        //商品券已添加情况校验
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = checkGoodsCoupon(oldCartGoodsList, operationType, couponCode,goodsId, addShoppingCartGoodsRequestVo);
        CartGoods addCartGoods = convent2CartGoods(addShoppingCartGoodsRequestVo, goodsId ,vo);
        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)){
            CustomerInfoVo userLoginInfoDto = getCustomerInfoVo(sessionId);
            couponName = getCouponNameByCode(couponCode,userLoginInfoDto,
                    BusinessTypeEnum.getByType(addShoppingCartGoodsRequestVo.getMenuType()).getCode(),storeId);
            addCartGoods.setCouponName(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);
        }

        if(StringUtils.isNotEmpty(threeToOneCouponCode) && StringUtils.isNotEmpty(threeToOneActivityCode)) {
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, threeToOneCouponCode, shoppingCartBaseService, SaveCouponType.THREE_TO_ONE_COUPON.getCode());
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, threeToOneActivityCode, shoppingCartBaseService, SaveCouponType.THREE_TO_ONE_ACTIVITY_CODE.getCode());
        }

        // 购物车数据更新(保存商品原价)
        List<CartGoods> 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, null);

        // 返回购物车数据
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, newCartGoods, null, ShoppingCartConstant.ADD_AND_UPDATE, null);

        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    private MCoffeeProductIdsVo validCoupon(String partnerId, String storeId, String spuId, List<Long> productIds, String menuType) {
        CheckSpqInfoRequestDto checkSpqInfoRequestDto = new CheckSpqInfoRequestDto(partnerId, storeId, spuId.substring(CommonsConstant.COUPON_PREFIX.length()), menuType);
        CouponService couponService = SDKCommonBaseContextWare.getBean(CouponService.class);
        CheckSpqInfoResponseDto checkSpqInfoResponseDto = couponService.checkSpqInfo(checkSpqInfoRequestDto);
        if (checkSpqInfoResponseDto == null) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_COUPON_NOT_EXIST);
        }
        productIds.add(Long.parseLong(checkSpqInfoResponseDto.getSkuId()));
        String skuId2 = checkSpqInfoResponseDto.getSkuId();
        String spuId2 = checkSpqInfoResponseDto.getSpuId();
        MCoffeeProductIdsVo vo =new MCoffeeProductIdsVo();
        vo.setSkuId(skuId2);
        vo.setSpuId(spuId2);
        return vo;
    }


    private List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> checkGoodsCoupon(List<CartGoods> oldCartGoodsList, Integer operationType, String couponCode, String goodsId, MCoffeeAddGoodsRequestVo 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 (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 (StringUtils.isNotEmpty(couponCode) && couponCode.equals(cartGoods.getCouponCode())) {
                    //使用券的是，如果购物车已经存在这个券，先清除，再添加
                    cartGoods.setQty(0);
                }
                if (StringUtils.isNotEmpty(goodsId) && StringUtils.isNotEmpty(couponCode) && goodsId.equals(cartGoods.getSkuId()) && StringUtils.isBlank(cartGoods.getCouponCode()) && isContinue) {
                    // 如果购物车商品存在商品规格，替换时复制规格信息
                    if (CollectionUtils.isNotEmpty(cartGoods.getSpecialExtra())) {
                        addShoppingCartGoodsRequestVo.setSpecialExtra(cartGoods.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);
            coupons.add(calculationDiscountCoupon);
        }

        return coupons;
    }

    /**
     * 更新商品数量
     */
    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();
        Integer oldQty = updateShoppingCartGoodsQtyRequestVo.getOldQty();

        // 先验证商品是否存在
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, null, null, shoppingCartBaseService);
        CartGoods cartGoods = null;
        for (CartGoods cartGoods_ : cartGoodsList) {
            if (cartGoodsUid.equals(cartGoods_.getCartGoodsUid())) {
                cartGoods = cartGoods_;
                if (oldQty == null ) {
                    cartGoods_.setQty(qty);
                }else {
                    cartGoods_.setQty(cartGoods_.getQty() - (oldQty - qty));
                }
                break;
            }
        }

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

        //商品券行商品数量不可增加
        if (cartGoods.getCouponCode() != null && qty > 1) {
            throw new ServiceException(ResponseResult.NOT_SUPPORTED);
        }

        // 检查购物车商品库存数量
//        checkUpdateStock(partnerId, storeId, menuType, qty, cartGoods);

        // check购物车中所有商品
        cartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, cartGoodsList);

        // 重新存储最新购物车
        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());
        String buyThreeGiveOneCouponCode = assortmentSdkService.getShoppingCartCoupon(partnerId, storeId, userId, shoppingCartBaseService, SaveCouponType.THREE_TO_ONE_COUPON.getCode());
        String buyThreeGiveOneActivityCode = assortmentSdkService.getShoppingCartCoupon(partnerId, storeId, userId, shoppingCartBaseService, SaveCouponType.THREE_TO_ONE_ACTIVITY_CODE.getCode());
        List<CouponTypeVo> couponTypeList = assortmentSdkService.getTypeCartCouponCode(partnerId, storeId, userId, shoppingCartBaseService);

        // 当couponCode不为空时，需参与价格计算
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = getCoupon(couponCode, null, cartGoodsList,freightCouponCode,null,buyThreeGiveOneCouponCode,buyThreeGiveOneActivityCode, couponTypeList);
        // 促销活动的优惠金额计算
        calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, couponCode,
                cartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo,null, null);
        //设置更新响应信息
        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();
        String buyThreeGiveOneCouponCode = shoppingCartInfoRequestVo.getBuyThreeGiveOneCouponCode();
        String buyThreeGiveOneActivityCode = shoppingCartInfoRequestVo.getBuyThreeGiveOneActivityCode();
        List<CouponTypeVo> couponTypeList = shoppingCartInfoRequestVo.getCouponTypeList();

        // 获取购物车商品
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, sessionId, "", shoppingCartBaseService);
        log.info("cartGoodsList: {}",JSONObject.toJSONString(cartGoodsList));
        // 如果购物车商品不为空， 则check购物车中所有商品
        if (CollectionUtils.isNotEmpty(cartGoodsList)) {
            // 合并相同商品数据
            //cartGoodsList = mergeProductList(cartGoodsList);
            // check购物车中所有商品
            cartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, cartGoodsList);
            // 重新存储最新购物车
            assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, sessionId, "", shoppingCartBaseService);
        }

        /**
         * 如果couponCode为空，则从缓存里尝试获取
         * 如果couponCode不为空，则设置到缓存里
         */
        if(StringUtils.isEmpty(couponCode)) {
            couponCode = assortmentSdkService.getShoppingCartCoupon(partnerId, storeId, userId, shoppingCartBaseService, SaveCouponType.COUPON.getCode());
        } else {
            if("remove".equals(couponCode)) {
                couponCode = "";
            }
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, couponCode, shoppingCartBaseService, SaveCouponType.COUPON.getCode());
        }

        if(StringUtils.isEmpty(freightCouponCode)) {
            freightCouponCode = assortmentSdkService.getShoppingCartCoupon(partnerId, storeId, userId, shoppingCartBaseService, SaveCouponType.FREIGHT_COUPON.getCode());
        } else {
            if("remove".equals(freightCouponCode)) {
                freightCouponCode = "";
            }
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, freightCouponCode, shoppingCartBaseService, SaveCouponType.FREIGHT_COUPON.getCode());
        }

        if(StringUtils.isEmpty(buyThreeGiveOneCouponCode) &&  StringUtils.isEmpty(buyThreeGiveOneActivityCode)) {
            buyThreeGiveOneCouponCode = assortmentSdkService.getShoppingCartCoupon(partnerId, storeId, userId, shoppingCartBaseService, SaveCouponType.THREE_TO_ONE_COUPON.getCode());
            buyThreeGiveOneActivityCode = assortmentSdkService.getShoppingCartCoupon(partnerId, storeId, userId, shoppingCartBaseService, SaveCouponType.THREE_TO_ONE_ACTIVITY_CODE.getCode());
        } else {
            if("remove".equals(buyThreeGiveOneCouponCode)) {
                buyThreeGiveOneCouponCode = "";
                buyThreeGiveOneActivityCode = "";
            }
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, buyThreeGiveOneCouponCode, shoppingCartBaseService, SaveCouponType.THREE_TO_ONE_COUPON.getCode());
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, buyThreeGiveOneActivityCode, shoppingCartBaseService, SaveCouponType.THREE_TO_ONE_ACTIVITY_CODE.getCode());
        }

        if (CollectionUtils.isEmpty(couponTypeList)){
            couponTypeList = assortmentSdkService.getTypeCartCouponCode(partnerId, storeId, userId, shoppingCartBaseService);
        }else {
            assortmentSdkService.setTypeCartCouponCode(partnerId, storeId, userId, couponTypeList, shoppingCartBaseService);
        }

        //放到参数里
        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, buyThreeGiveOneCouponCode , buyThreeGiveOneActivityCode, shoppingCartInfoRequestVo.getCouponTypeList());

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

        // 剔除商品加料信息
        if ( CollectionUtils.isNotEmpty(eliminateGoodsList) ) {
            // 获取购物车商品
            List<CartGoods> cartGoodsListOld = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, sessionId, "", shoppingCartBaseService);
            // 如果购物车商品不为空， 则check购物车中所有商品
            if (CollectionUtils.isNotEmpty(cartGoodsListOld)) {
                Map<String, CartGoods> goodsMap = cartGoodsListOld.parallelStream().collect(Collectors.toMap(CartGoods::getCartGoodsUid, Function.identity(), (k1, k2) -> k1));
                for (String uid : eliminateGoodsList) {
                    CartGoods cartGoods = goodsMap.get(uid);
                    cartGoods.setSpecialExtra(null);
                }
                // check购物车中所有商品
                cartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, cartGoodsListOld);
                // 重新存储最新购物车
                assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsListOld, sessionId, "", shoppingCartBaseService);
            }
            // 促销活动的优惠金额计算
            calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, null,
                    cartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo, payCardPrice,  null );
        }

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

        //先出参里的券设置为空，然后如果可用，再放到出参里
        shoppingCartGoodsResponseVo.setCouponCode("");
        shoppingCartGoodsResponseVo.setFreightCouponCode("");
        shoppingCartGoodsResponseVo.setBuyThreeGiveOneActivityCode(buyThreeGiveOneActivityCode);
        shoppingCartGoodsResponseVo.setBuyThreeGiveOneCouponCode("");
        shoppingCartGoodsResponseVo.setCouponTypeList(couponTypeList);
        if(StringUtils.isNotEmpty(couponCode) || StringUtils.isNotEmpty(freightCouponCode) || StringUtils.isNotEmpty(buyThreeGiveOneCouponCode)) {
            String finalCouponCode = couponCode;
            String finalFreightCouponCode = freightCouponCode;
            String finalBuyThreeGiveOneCouponCode = buyThreeGiveOneCouponCode;
            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(o.getActivityCode().equals(finalBuyThreeGiveOneCouponCode)) {
                        shoppingCartGoodsResponseVo.setBuyThreeGiveOneCouponCode(finalBuyThreeGiveOneCouponCode);
                    }
                });
            }
        }
        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());
        }
        if(ObjectUtils.notEqual(shoppingCartGoodsResponseVo.getBuyThreeGiveOneCouponCode(), buyThreeGiveOneCouponCode)) {
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, "", shoppingCartBaseService, SaveCouponType.THREE_TO_ONE_COUPON.getCode());
            assortmentSdkService.setShoppingCartCouponCode(partnerId, storeId, userId, "", shoppingCartBaseService, SaveCouponType.THREE_TO_ONE_ACTIVITY_CODE.getCode());
        }
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    /**
     * 合并购物车相同商品,数量相加
     * @param cartGoodsList
     * @return
     */
    public List<CartGoods> mergeProductList(List<CartGoods> cartGoodsList ){

        if (CollectionUtils.isEmpty(cartGoodsList)){
            return null;
        }

        List<CartGoods> list =new ArrayList<>();
        Map<String, CartGoods> map =new HashMap<>();
        for (CartGoods cartGoods : cartGoodsList) {
            String skuId = cartGoods.getSkuId();
            if (StringUtils.isNotEmpty(cartGoods.getCouponCode())){
                map.put(skuId,cartGoods);
                continue;
            }
            String cartGoodsUid = cartGoods.getCartGoodsUid();
            if (map.containsKey(skuId)){
                CartGoods cartGoods1 = map.get(skuId);
                //判断是否有加料,加料是否相同
                List<CartGoods.MaterialGoods> productMaterialList = cartGoods.getProductMaterialList();
                List<CartGoods.MaterialGoods> productMaterialList1 = cartGoods1.getProductMaterialList();
                if ((CollectionUtils.isNotEmpty(productMaterialList) && CollectionUtils.isNotEmpty(productMaterialList1) && productMaterialList.retainAll(productMaterialList1))
                        || (CollectionUtils.isNotEmpty(productMaterialList) && CollectionUtils.isEmpty(productMaterialList1))
                        || (CollectionUtils.isEmpty(productMaterialList) && CollectionUtils.isNotEmpty(productMaterialList1)) ) {
                    map.put(skuId + cartGoodsUid,cartGoods);
                }else {
                    cartGoods1.setQty(cartGoods1.getQty() + cartGoods.getQty());
                    map.put(skuId,cartGoods1);
                }
            }else {
                map.put(skuId,cartGoods);
            }

        }
        for(String temp:map.keySet()){
            list.add(map.get(temp));
        }
        return list;
    }


    /**
     * 券码用-查询购物车最新信息，计算优惠
     * @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,null,null, null);
        // 促销活动的优惠金额计算
        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, null);
        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();
        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 = 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();
        String buyThreeGiveOneCouponCode = shoppingCartInfoRequestVo.getBuyThreeGiveOneCouponCode();
        String buyThreeGiveOneActivityCode = shoppingCartInfoRequestVo.getBuyThreeGiveOneActivityCode();
        List<CouponTypeVo> couponTypeList = shoppingCartInfoRequestVo.getCouponTypeList();

        // 获取购物车商品
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, null, tableNumber, shoppingCartBaseService);
        log.info("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);
        }
        //恢复套餐商品空键位
//        checkNewCartGoods(allCartGoodsList,2,map);

        // 重新存储最新购物车
        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,buyThreeGiveOneCouponCode,buyThreeGiveOneActivityCode,couponTypeList);

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

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

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

        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);
        // 如果购物车商品不为空， 则check购物车中所有商品
        if (CollectionUtils.isEmpty(cartGoodsList)) {
            return ResponseUtil.success(shoppingCartGoodsResponseVo);
        }

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

        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);
                return ResponseUtil.success(shoppingCartGoodsResponseVo);
            }else {
                // 新门店check购物车中所有商品
                cartGoodsList = checkCartGoods(partnerId, toStoreId, orderType, menuType, shoppingCartGoodsResponseVo, cartGoodsList);
                // 重新存储新门店购物车
                assortmentSdkService.setShoppingCart(partnerId, toStoreId, userId, cartGoodsList, sessionId, "", shoppingCartBaseService);
                //清空商品券商品
                clearCartCouponGoods(partnerId, toStoreId, userId, sessionId, cartGoodsList);
                // 当couponCode不为空时，需参与价格计算
                List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = getCoupon(couponCode, null, cartGoodsList,null,null,null,null,null);

                // 促销活动的优惠金额计算
                calculationService.updateShoppingCartGoodsDiscount(partnerId, toStoreId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, null,
                        cartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo,null, null);
                //设置更新响应信息
                setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), ShoppingCartConstant.QUERY_INFO, shoppingCartInfoRequestVo);
                shoppingCartGoodsResponseVo.setChanged(false);
            }
        }
        // 新门店check购物车中所有商品
        if (requestVo.getOperationType() == ShoppingCartOperationType.CONFIRM.getCode()) {
            // 重新存储新门店购物车
            assortmentSdkService.setShoppingCart(partnerId, toStoreId, userId, cartGoodsList, sessionId, "", shoppingCartBaseService);
            //清空商品券商品
            clearCartCouponGoods(partnerId, toStoreId, userId, sessionId, cartGoodsList);
            // 当couponCode不为空时，需参与价格计算
            List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = getCoupon(couponCode, null, cartGoodsList,null,null,null, null,null);

            // 促销活动的优惠金额计算
            calculationService.updateShoppingCartGoodsDiscount(partnerId, toStoreId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, null,
                    cartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo,null, null);
            //设置更新响应信息
            setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), ShoppingCartConstant.QUERY_INFO, shoppingCartInfoRequestVo);
            shoppingCartGoodsResponseVo.setChanged(false);
        }
        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

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


    /**
     * 再来一单
     */
    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);
        // 如果购物车商品不为空， 则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, 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 userId
     * @param shoppingCartGoodsResponseVo
     */
    public List<CartGoods> updateCartGoodsLegal(String partnerId, String storeId, Integer orderType, String tableNumber, String menuType, String userId,
                                                CartGoods addCartGoods, ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo, List<CartGoods> oldCartGoodsList) {
        List<CartGoods> newCartGoods = new ArrayList<>();
        newCartGoods.addAll(oldCartGoodsList);
        newCartGoods.add(addCartGoods);

        //加购商品校验
        List<CartGoods> allCartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, newCartGoods);

        List<CartGoods> nowCartGoodsList = new ArrayList<>();
        //判断当前商品在购物车是否已存在,存在则数量＋1,不存在商品行 + 1
        allCartGoodsList.forEach(oldCartGoods -> {
            int index;
            if ((index = nowCartGoodsList.indexOf(oldCartGoods)) >= 0) {
                nowCartGoodsList.get(index).setQty(nowCartGoodsList.get(index).getQty() + addCartGoods.getQty());
            } else {
                nowCartGoodsList.add(oldCartGoods);
            }
        });

        // 重新set购物车信息到缓存中
        assortmentSdkService.setShoppingCart(partnerId, storeId, userId, nowCartGoodsList, null, tableNumber, this.shoppingCartBaseService);
        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());
        }

    }


    public static CartGoods convent2CartGoods(MCoffeeAddGoodsRequestVo addShoppingCartGoodsRequestVo, String goodsId,  MCoffeeProductIdsVo mCoffeeProductIdsVo) {
        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.setCouponCode(addShoppingCartGoodsRequestVo.getCouponCode());
        Integer goodsType = StringUtils.isEmpty(skuId) || ObjectUtils.equals(spuId, skuId) ? GoodsTypeEnum.SPU_GOODS.getGoodsType() : GoodsTypeEnum.SKU_GOODS.getGoodsType();
        if (spuId.startsWith(CommonsConstant.COUPON_PREFIX)) {
            goodsType = GoodsTypeEnum.COUPON_GOODS.getGoodsType();
            cartGoods.setSpuId(mCoffeeProductIdsVo.getSpuId());
            cartGoods.setSkuId(goodsId);
            cartGoods.setCouponCode(spuId.substring(CommonsConstant.COUPON_PREFIX.length()));
//            cartGoods.setCartGoodsUid(spuId);
        } else if (CollectionUtils.isNotEmpty(addShoppingCartGoodsRequestVo.getProductComboList()) || CollectionUtils.isNotEmpty(addShoppingCartGoodsRequestVo.getProductGroupList())) {
            goodsType = GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType();
        } else if (CommonsConstant.COUPON_TYPE == addShoppingCartGoodsRequestVo.getCouponType()){
            goodsType = GoodsTypeEnum.ALL_COUPON_GOODS.getGoodsType();
        }
        if (addShoppingCartGoodsRequestVo.getOperationType() != null && addShoppingCartGoodsRequestVo.getOperationType() == 2) {
            goodsType = GoodsTypeEnum.REDUCE_PRICE_GOODS.getGoodsType();
        }
        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());
                        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) {

        //筛选数量不为0商品
        cartGoodsList = cartGoodsList.stream().filter(cartGoods -> cartGoods.getQty() != 0).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> allCartGoodsList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(checkGoods)) {
            //当商品全部添加完毕,校验购物车商品(是否合法,上下架,点餐方式,是否在当前菜单中...),并移除非法商品
            CheckCartRequest checkCartRequest = checkShoppingCartSdkForMCoffee(checkGoods, partnerId,
                    storeId, shoppingCartGoodsResponseVo, orderType, "", 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 (CollectionUtils.isNotEmpty(reduceGoods)) {
            allCartGoodsList.addAll(reduceGoods);
        }
        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).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,
                                                                                            String threeToOneCouponCode, String buyThreeGiveOneActivityCode, List<CouponTypeVo> couponTypeList) {

        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 (StringUtils.isNotEmpty(threeToOneCouponCode)) {
            ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon coupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
            coupon.setCode(threeToOneCouponCode);
            coupon.setPayCardActivityId(buyThreeGiveOneActivityCode);
            coupons.add(coupon);
        }
        if (CollectionUtils.isNotEmpty(couponTypeList)) {
            for (CouponTypeVo couponType: couponTypeList) {
                ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon coupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
                coupon.setCode(couponType.getCode());
                coupons.add(coupon);
            }
        }

        //购物车商品券
        if (CollectionUtils.isNotEmpty(cartGoodsList)) {
            for (CartGoods cartGoods : cartGoodsList) {
                //购物车已存在商品券
                if (StringUtils.isNotBlank(cartGoods.getCouponCode())) {
                    ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
                    calculationDiscountCoupon.setCode(cartGoods.getCouponCode());
                    coupons.add(calculationDiscountCoupon);
                }
            }
        }
        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 tableNumber, 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.setTableNumber(tableNumber);
        checkCartRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        checkCartRequest.setMenuType(BusinessTypeEnum.getByType(menuType).getCode());
        BaseResponse<CheckCartRequest> baseResponse ;
        baseResponse= checkAllCartGoodsForMCoffee(checkCartRequest);
        if (baseResponse == null) {
            return null;
        }
        return baseResponse.getResult();
    }

    private 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> 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()) {
                        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 (PRODUCT_PRICE_CHANGE == validaProduct.getCode()) {
                                changePriceSpu.add(spuName);
                                List<ProductTypeBeanDTO> productList =
                                        validateResult.getFailureList().stream().map(ValiadShopProductResult::getProductType).collect(Collectors.toList());
                                shoppingCartConvertAdapter.updateCartGoodsInfoForMCoffee(cartGoods, productList);
                            }
                            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(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()){
                    ProductTypeBeanDTO productType = valiadShopProductResult.getProductType();
                    if(ObjectUtils.equals(productType.getPid(), cartGoods.getSpuId())){
                        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);
            // 重新存储最新购物车
            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,null, null,null);

        // 促销活动的优惠金额计算
        calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId, null,
                cartGoodsList, coupons, new ArrayList<>(), shoppingCartGoodsResponseVo,null, 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;
    }
}
