package cn.freemud.service.impl.mcoffee;

import cn.freemud.adapter.ActivityAdapter;
import cn.freemud.adapter.ShoppingCartConvertAdapter;
import cn.freemud.base.entity.BaseResponse;
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.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.FullSubtractionActivityServiceImpl;
import cn.freemud.service.impl.mcoffee.calculation.CalculationServiceImpl;
import cn.freemud.service.impl.mcoffee.calculation.CouponDiscountCalculation;
import cn.freemud.service.impl.mcoffee.entity.CopyShoppingCartRequestVo;
import cn.freemud.service.impl.mcoffee.entity.MCoffeeAddGoodsRequestVo;
import cn.freemud.service.impl.mcoffee.entity.SwitchShoppingCartRequestVo;
import cn.freemud.service.thirdparty.CustomerApplicationClient;
import cn.freemud.utils.ResponseUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.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.CommonsConstant;
import com.freemud.sdk.api.assortment.shoppingcart.enums.BusinessTypeEnum;
import com.freemud.sdk.api.assortment.shoppingcart.request.CheckCartRequest;
import com.freemud.sdk.api.assortment.shoppingcart.service.impl.ShoppingCartBaseServiceImpl;
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.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

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

/**
 * 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;

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

        String spuId2 = spuId;
        List<Long> productIds = new ArrayList<>();
        //商品券校验
        if (spuId.startsWith(CommonsConstant.COUPON_PREFIX)) {
            couponCode = spuId.substring(CommonsConstant.COUPON_PREFIX.length());
            spuId2 = validCoupon(partnerId, storeId, spuId, productIds, BusinessTypeEnum.getByType(addShoppingCartGoodsRequestVo.getMenuType()).getCode());
            goodsId = spuId2;
        }
        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);
        CartGoods addCartGoods = convent2CartGoods(addShoppingCartGoodsRequestVo, goodsId);
        setClassificationAndPrice(addCartGoods, productBeanListSpuClass);
        //查询多个商品库存信息
//        Integer checkQty = this.checkSkuQty(oldCartGoodsList, addCartGoods);
//        queryManyGoodsStocks(partnerId, storeId, menuType, productIds, productBeanListSpuClass, skuId, checkQty);

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

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

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

        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    private String validCoupon(String partnerId, String storeId, String spuId, List<Long> productIds, String menuType) {
        String spuId2;
        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()));
        spuId2 = checkSpqInfoResponseDto.getSkuId();
        return spuId2;
    }


    private List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> checkGoodsCoupon(List<CartGoods> oldCartGoodsList, Integer operationType, String couponCode) {
        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)) {
            for (CartGoods cartGoods : oldCartGoodsList) {
                //购物车已存在商品券
                if (StringUtils.isNotBlank(cartGoods.getCouponCode())) {
                    ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon calculationDiscountCoupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
                    calculationDiscountCoupon.setCode(cartGoods.getCouponCode());
                    coupons.add(calculationDiscountCoupon);
                }
                if (couponCode != null && couponCode.equals(cartGoods.getCouponCode())) {
                    throw new ServiceException(ResponseResult.PARAMETER_MISSING, "商品券已添加");
                }
            }
        }
        //新增商品券
        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();

        // 先验证商品是否存在
        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_;
                cartGoods_.setQty(qty);
                break;
            }
        }

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

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

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

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

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

        // 获取购物车商品
        List<CartGoods> cartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, sessionId, "", shoppingCartBaseService);

        // 如果购物车商品不为空， 则check购物车中所有商品
        if (CollectionUtils.isNotEmpty(cartGoodsList)) {
            // check购物车中所有商品
            cartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, cartGoodsList);
            // 重新存储最新购物车
            assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, sessionId, "", shoppingCartBaseService);
        }
        // 当couponCode不为空时，需参与价格计算
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = getCoupon(couponCode, null, cartGoodsList);

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

        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }


    /**
     * 查询购物车可用券
     */
    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 thirdPartyMemberID = "test";
        String unionId = "test";
        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, 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.clear(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();

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

        // check购物车中所有商品
        cartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, cartGoodsList);
        // 重新存储最新购物车
        assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, sessionId, tableNumber, shoppingCartBaseService);

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

        //加价购商品
        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);

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

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

        List<CartGoods> cartGoodsList = getOrderGoods(orderInfo.getResult());
        String storeId = orderInfo.getResult().getStoreId();
        if (orderInfo.getResult().getOrderType() == 3 || orderInfo.getResult().getOrderType() == 4) {
            menuType = "saasdelivery";
            orderType = 2;
        }
        // 如果购物车商品不为空， 则check购物车中所有商品
        if (CollectionUtils.isNotEmpty(cartGoodsList)) {
            // check购物车中所有商品
            cartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, cartGoodsList);
            // 重新存储最新购物车
            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);
        //设置更新响应信息
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), ShoppingCartConstant.ADD_AND_UPDATE, null);

        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    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());
            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));
            }
            cartGoodsList.add(cartGoods);
        }

        return cartGoodsList;
    }


    private CartGoods.ComboxGoods getComboxGoods(CartGoods cartGoods, OrderItemResp orderItemResp) {
        CartGoods.ComboxGoods comboxGoods = new CartGoods.ComboxGoods();
        comboxGoods.setSkuId(orderItemResp.getProductId());
        comboxGoods.setGoodsId(orderItemResp.getProductId());
        comboxGoods.setQty(orderItemResp.getProductQuantity());
        comboxGoods.setOriginalPrice(orderItemResp.getProductPrice().longValue());
        comboxGoods.setFinalPrice(orderItemResp.getSalePrice().longValue());
        if (!"".equals(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);
        }
        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);
        }
//        comboxGoods.setWeight(orderItemResp.getWeight());
//        productBean.setCustomerCode(orderItemResp.getThirdProductId());
//        productBean.setProductCode(orderItemResp.getProductCode());
//        productBean.setNumber(orderItemResp.getProductQuantity());
//        productBean.setOpid(orderItemResp.getProductSeq() == null ? null : orderItemResp.getProductSeq().toString());
//        productBean.setSequence(orderItemResp.getProductSeq() == null ? 0 : orderItemResp.getProductSeq());
//        productBean.setOrderId(orderItemResp.getOrderCode());
//        comboxGoods.setProductId(orderItemResp.getProductId());
//        productBean.setParentProductId("");
//        productBean.setPicture(orderItemResp.getProductPicUrl());
//        productBean.setPrice(orderItemResp.getProductPrice().longValue());
//        productBean.setSalePrice(orderItemResp.getSalePrice().longValue());
//        productBean.setProductName(orderItemResp.getProductName());
//        productBean.setSpecification(orderItemResp.getProductSpec());
//        productBean.setSpecificationName(orderItemResp.getProductSpecName());
//        productBean.setProductSharePrice(orderItemResp.getProductSharePrice());
//        productBean.setSettlementPrice(orderItemResp.getSettlementPrice().longValue());
//        productBean.setUnit(orderItemResp.getProductUnit());


//
//        // 套餐
//        productBean.setParentProductId(orderItemResp.getParentProductId());
//        productBean.setProductType(orderItemResp.getProductType());
//        productBean.setId(orderItemResp.getId());

        return comboxGoods;
    }


    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 = checkNewCartGoods(newCartGoods, addCartGoods);
        //加购商品校验
        List<CartGoods> allCartGoodsList = checkCartGoods(partnerId, storeId, orderType, menuType, shoppingCartGoodsResponseVo, newCartGoods);

        //添加商品为商品券时，商品校验接口券号未设置，设置商品券号
//        if (StringUtils.isNotBlank(addCartGoods.getCouponCode())) {
//            for (CartGoods cartGoods : allCartGoodsList) {
//                if (cartGoods.getGoodsId().equals(addCartGoods.getGoodsId()) && cartGoods.getCouponCode() == null) {
//                    cartGoods.setCouponCode(addCartGoods.getCouponCode());
//                    cartGoods.setGoodsType(2);
//                    break;
//                }
//            }
//        }


        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 List<CartGoods> checkNewCartGoods(List<CartGoods> newCartGoods, CartGoods addCartGoods) {
        Integer qty = addCartGoods.getQty() == null ? 0 : addCartGoods.getQty();

        if (StringUtils.isNotBlank(addCartGoods.getCouponCode())) {
            newCartGoods.add(addCartGoods);
            return newCartGoods;
        }

        boolean isadd = true;
        if (CollectionUtils.isNotEmpty(newCartGoods)) {
            for (CartGoods goods : newCartGoods) {
                if (goods.getSkuId().equals(addCartGoods.getSkuId()) && goods.getSpuId().equals(addCartGoods.getSpuId())) {
                    if (goods.getProductGroupList() != null && addCartGoods.getProductGroupList() != null && goods.getProductGroupList().size() == addCartGoods.getProductGroupList().size()) {

                    }
                }
            }
            if (isadd) {
                newCartGoods.add(addCartGoods);
            }
        } else {
            newCartGoods.add(addCartGoods);
        }
        return newCartGoods;
    }


    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.PARAMETER_MISSING, "商品键位编号为空");
        }

        //超值加购商品赋值
        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) {
        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(goodsId);
            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();
        }
        if (addShoppingCartGoodsRequestVo.getOperationType() != null && addShoppingCartGoodsRequestVo.getOperationType() == 2) {
            goodsType = GoodsTypeEnum.REDUCE_PRICE_GOODS.getGoodsType();
        }
        cartGoods.setGoodsType(goodsType);
        cartGoods.setExtra(addShoppingCartGoodsRequestVo.getExtra());
        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.setQty(vo.getQty());
                productCombox.setExtra(vo.getExtra());
                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.setQty(vo.getQty());
                productCombox.setExtra(vo.getExtra());
                productCombox.setProductGroupId(StringUtils.isEmpty(vo.getProductGroupId()) ? null : Long.parseLong(vo.getProductGroupId()));
                productGroupList.add(productCombox);
            }
        }
        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 = assortmentSdkService.checkShoppingCartSdk(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;
    }


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

        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 (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;
    }


}
