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.ActivityTypeEnum;
import cn.freemud.enums.OperationTypeEnum;
import cn.freemud.enums.OrderType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.ActivityService;
import cn.freemud.service.impl.AssortmentSdkService;
import cn.freemud.service.impl.FullSubtractionActivityServiceImpl;
import cn.freemud.service.impl.mcoffee.calculation.CalculationServiceImpl;
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.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.ShoppingCartBaseService;
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.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 java.util.stream.Collectors.toList;

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

    /**
     * 添加商品
     *
     * @param addShoppingCartGoodsRequestVo
     * @return
     */
    public BaseResponse addGoods(AddShoppingCartGoodsRequestVo addShoppingCartGoodsRequestVo) {
        // TODO: 2020/7/21 参数校验
        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();

        String spuId2 = spuId;
        List<Long> productIds = new ArrayList<>();
        productIds.add(Long.parseLong(goodsId));
        // TODO: 2020/7/21 获取添加商品的详细信息
        List<ProductBeanDTO> productBeanListSpuClass = assortmentSdkService.getProductsInfoSdk(partnerId, storeId
                , Collections.singletonList(spuId2), menuType, this.shoppingCartBaseService);


        CartGoods addCartGoods = ShoppingCartConvertAdapter.convent2CartGoods(addShoppingCartGoodsRequestVo);
        // TODO: 2020/7/21 查询购物车缓存
        // 注意，围餐和点餐redis数据结构不一样
        List<CartGoods> oldCartGoodsList = assortmentSdkService.getShoppingCart(partnerId, storeId, userId, null, null, shoppingCartBaseService);
        if (CollectionUtils.isEmpty(oldCartGoodsList)) {
            oldCartGoodsList = new ArrayList<>();
        }
        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 = new ArrayList<>();
        newCartGoods.addAll(oldCartGoodsList);
        newCartGoods = checkNewCartGoods(newCartGoods, addCartGoods);

        // TODO: 2020/7/21 购物车数据更新(保存商品原价)
        newCartGoods = updateCartGoodsLegal(partnerId, storeId, orderType, tableNumber, menuType, userId, addCartGoods, shoppingCartGoodsResponseVo, newCartGoods);

        // TODO: 2020/7/21 促销活动等价格计算
        calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId,null,
                newCartGoods, new ArrayList<>(), new ArrayList<>(), shoppingCartGoodsResponseVo);

        // TODO: 2020/7/21 返回购物车数据
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, newCartGoods, null, ShoppingCartConstant.ADD_AND_UPDATE, null);

        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    /**
     * 更新商品数量
     *
     * @param updateShoppingCartGoodsQtyRequestVo
     * @return
     */
    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();
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(updateShoppingCartGoodsQtyRequestVo.getSessionId());
        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购物车中所有商品
        CheckCartRequest checkCartRequest = assortmentSdkService.checkShoppingCartSdk(cartGoodsList, partnerId, storeId, shoppingCartGoodsResponseVo, updateShoppingCartGoodsQtyRequestVo.getOrderType(), "", updateShoppingCartGoodsQtyRequestVo.getMenuType(), shoppingCartBaseService);

        cartGoodsList = JSONArray.parseArray(JSONObject.toJSONString(checkCartRequest.getCartGoodsList()), CartGoods.class);
        // 重新存储最新购物车
        assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, updateShoppingCartGoodsQtyRequestVo.getSessionId(), "", shoppingCartBaseService);

        // 促销活动的优惠金额计算
        calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId,null,
                cartGoodsList, new ArrayList<>(), 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();
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(shoppingCartInfoRequestVo.getSessionId());
        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, null, "", shoppingCartBaseService);
        // 如果购物车商品不为空， 则check购物车中所有商品
        if (CollectionUtils.isNotEmpty(cartGoodsList)) {
            CheckCartRequest checkCartRequest = assortmentSdkService.checkShoppingCartSdk(cartGoodsList, partnerId, storeId, shoppingCartGoodsResponseVo, shoppingCartInfoRequestVo.getOrderType(), "", shoppingCartInfoRequestVo.getMenuType(), shoppingCartBaseService);
            if (checkCartRequest.getShoppingCartGoodsResponseVo() != null) {
                shoppingCartGoodsResponseVo.setChanged(checkCartRequest.getShoppingCartGoodsResponseVo().getChanged());
                shoppingCartGoodsResponseVo.setToastMsg(checkCartRequest.getShoppingCartGoodsResponseVo().getToastMsg());
            }
            cartGoodsList = JSONArray.parseArray(JSONObject.toJSONString(checkCartRequest.getCartGoodsList()), CartGoods.class);
            // 重新存储最新购物车
            assortmentSdkService.setShoppingCart(partnerId, storeId, userId, cartGoodsList, assortmentCustomerInfoVo.getSessionId(), "", this.shoppingCartBaseService);
        }
        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = new ArrayList<>();
        // 当couponCode不为空时，需参与价格计算
        if (StringUtils.isNotEmpty(couponCode)) {
            ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon coupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
            coupon.setCode(couponCode);
            coupon.setActivityCode(activityCode);
            coupons.add(coupon);
        }
        // 促销活动的优惠金额计算
        calculationService.updateShoppingCartGoodsDiscount(partnerId, storeId, userId, appId, orderType, assortmentCustomerInfoVo.isMemberPaid(), menuType, receiveId,null,
                cartGoodsList, new ArrayList<>(), new ArrayList<>(), shoppingCartGoodsResponseVo);
        //设置更新响应信息
        setAddAndUpdateResponse(shoppingCartGoodsResponseVo, cartGoodsList, shoppingCartGoodsResponseVo.getToastMsg(), ShoppingCartConstant.QUERY_INFO, shoppingCartInfoRequestVo);

        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }

    /**
     * 清空购物车
     *
     * @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();
        // 获取用户信息
        CustomerInfoVo assortmentCustomerInfoVo = getCustomerInfoVo(shoppingCartInfoRequestVo.getSessionId());
        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<ShoppingCartInfoRequestVo.SendGoods> sendGoodsList = shoppingCartInfoRequestVo.getSendGoods();

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

        // check购物车中所有商品(商品是否存在，价格变动，券是否支持当前点餐方式)
        CheckCartRequest checkCartRequest = assortmentSdkService.checkShoppingCartSdk(cartGoodsList, partnerId, storeId, shoppingCartGoodsResponseVo,
                shoppingCartInfoRequestVo.getOrderType(), tableNumber, shoppingCartInfoRequestVo.getMenuType() ,shoppingCartBaseService);
        com.freemud.sdk.api.assortment.shoppingcart.domain.ShoppingCartGoodsResponseVo cartGoodsResponseVo = checkCartRequest.getShoppingCartGoodsResponseVo();
        //商品不再售卖状态或价格变动，直接返回报错
        if (cartGoodsResponseVo != null) {
            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());
        }
        cartGoodsList = JSONArray.parseArray(JSONObject.toJSONString(checkCartRequest.getCartGoodsList()), CartGoods.class);

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

        List<ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon> coupons = new ArrayList<>();
        // 当couponCode不为空时，需参与价格计算
        if (StringUtils.isNotEmpty(couponCode)) {
            ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon coupon = new ActivityCalculationDiscountRequestDto.CalculationDiscountCoupon();
            coupon.setCode(couponCode);
            coupon.setActivityCode(activityCode);
            coupons.add(coupon);
        }
        if (CollectionUtils.isNotEmpty(sendGoodsList)) {
            processSendGoods(sendGoodsList, partnerId, storeId , shoppingCartInfoRequestVo.getMenuType() , shoppingCartBaseService);
        } else {
            //组装加价购商品
            if (null != premiumExchangeActivity && CollectionUtils.isNotEmpty(premiumExchangeActivity.getProducts())) {
                List<ShoppingCartInfoRequestVo.SendGoods> sendGoods = premiumExchangeActivity.getProducts().stream().map(product -> {
                    ShoppingCartInfoRequestVo.SendGoods sendGood = new ShoppingCartInfoRequestVo.SendGoods();
                    sendGood.setGoodsId(product.getSkuId());
                    sendGood.setQty(product.getQty());
                    return sendGood;
                }).collect(toList());
                shoppingCartInfoRequestVo.setSendGoods(sendGoods);
            }
        }
        //加价购商品组装
        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);

        shoppingCartGoodsDto.setDeliveryAmount(shoppingCartGoodsResponseVo.getDeliveryAmount());
        shoppingCartGoodsDto.setDiscountDeliveryAmount(shoppingCartGoodsResponseVo.getDiscountDeliveryAmount());
        shoppingCartGoodsDto.setThresholdAmount(shoppingCartGoodsResponseVo.getThresholdAmount());
        shoppingCartGoodsDto.setIsDiscountDelivery(shoppingCartGoodsResponseVo.getIsDiscountDelivery());
        shoppingCartGoodsDto.setDiscountDeliveryActivityCode(shoppingCartGoodsResponseVo.getDiscountDeliveryActivityCode());
        return ResponseUtil.success(shoppingCartGoodsDto);
    }

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

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

    }


    /**
     * 获取购物车商品,添加商品,校验商品合法性,合并商品行,重新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> newCartGoods) {
        //当商品全部添加完毕,校验购物车商品(是否合法,上下架,点餐方式,是否在当前菜单中...),并移除非法商品
        CheckCartRequest checkCartRequest = assortmentSdkService.checkShoppingCartSdk(newCartGoods, partnerId,
                storeId, shoppingCartGoodsResponseVo, orderType, "", menuType, shoppingCartBaseService);
        if (checkCartRequest.getShoppingCartGoodsResponseVo() != null) {
            shoppingCartGoodsResponseVo.setToastMsg(checkCartRequest.getShoppingCartGoodsResponseVo().getToastMsg());
            shoppingCartGoodsResponseVo.setChanged(checkCartRequest.getShoppingCartGoodsResponseVo().getChanged());
        }
        List<CartGoods> allCartGoodsList = JSONArray.parseArray(JSONObject.toJSONString(checkCartRequest.getCartGoodsList()), CartGoods.class);
        // 重新set购物车信息到缓存中
        assortmentSdkService.setShoppingCart(partnerId, storeId, userId, allCartGoodsList, null, tableNumber, this.shoppingCartBaseService);
        return allCartGoodsList;
    }

    /**
     * 组装添加商品和更新商品和查询的响应信息
     * <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();

        boolean isadd = true;
        if (CollectionUtils.isNotEmpty(newCartGoods)) {
            for (CartGoods goods : newCartGoods) {
                if (goods.getSkuId().equals(addCartGoods.getSkuId()) && goods.getSpuId().equals(addCartGoods.getSpuId())) {
                    qty += goods.getQty();
                    goods.setQty(qty);
                    isadd = false;
                    break;
                }
            }
            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());
        cartGoods.setOriginalPrice(productBeanListSpuClass.get(0).getOriginalPrice());
//        cartGoods.setFinalPrice(productBeanListSpuClass.get(0).getFinalPrice());
//        cartGoods.setPackPrice(productBeanListSpuClass.get(0).getPackPrice());
//        if(StringUtils.isBlank(productBeanListSpuClass.get(0).getCustomerCode())){
//            productBeanListSpuClass.get(0).setCustomerCode("12345");
//        }
//        cartGoods.setCustomerCode(productBeanListSpuClass.get(0).getCustomerCode());
//        if(StringUtils.isBlank(productBeanListSpuClass.get(0).getCustomerCode())){
//            throw new ServiceException(ResponseResult.PARAMETER_MISSING,"商品键位编号为空");
//        }
    }

}
