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.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.MCoffeeAddGoodsRequestVo;
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.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;
    @Autowired
    private CouponDiscountCalculation couponDiscountCalculation;

    /**
     * 添加商品
     *
     * @param addShoppingCartGoodsRequestVo
     * @return
     */
    public BaseResponse addGoods(MCoffeeAddGoodsRequestVo 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();
        Integer operationType = addShoppingCartGoodsRequestVo.getOperationType();
        String couponCode = addShoppingCartGoodsRequestVo.getCouponCode();

        String spuId2 = spuId;
        List<Long> productIds = new ArrayList<>();
        productIds.add(Long.parseLong(goodsId));
        CartGoods addCartGoods = convent2CartGoods(addShoppingCartGoodsRequestVo);

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

        // TODO: 2020/7/21 查询购物车缓存
        // 注意，围餐和点餐redis数据结构不一样
        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);
        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);
        }

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

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

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

        return ResponseUtil.success(shoppingCartGoodsResponseVo);
    }


    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) && 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(couponCode);
                    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;
    }

    /**
     * 更新商品数量
     *
     * @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();
        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 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);
        if (CollectionUtils.isEmpty(cartGoodsList)) {
            return ResponseUtil.error(ResponseResult.SHOPPING_CART_ADD_INVAILD);
        }
        // 获取购物车商品-查询用户券-券码校验可用券
        availableCoupon = couponDiscountCalculation.availableCoupon(partnerId, storeId, userId, 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购物车中所有商品(商品是否存在，价格变动，券是否支持当前点餐方式)
//        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);

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

    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> 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.setCouponCode(addCartGoods.getCouponCode());
                    cartGoods.setGoodsType(2);
                    break;
                }
            }
        }

        // 重新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) && StringUtils.isBlank(addCartGoods.getCouponCode())) {
            for (CartGoods goods : newCartGoods) {
                if (goods.getSkuId().equals(addCartGoods.getSkuId()) && goods.getSpuId().equals(addCartGoods.getSpuId()) && StringUtils.isBlank(goods.getCouponCode())) {
                    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());

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

        if(ObjectUtils.equals(GoodsTypeEnum.REDUCE_PRICE_GOODS.getGoodsType(), cartGoods.getGoodsType())){
            cartGoods.setOriginalPrice(productBeanListSpuClass.get(0).getOriginalPrice());
            cartGoods.setFinalPrice(productBeanListSpuClass.get(0).getFinalPrice());
            cartGoods.setPackPrice(productBeanListSpuClass.get(0).getPackPrice());
            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);
        }




    }


    public static CartGoods convent2CartGoods(MCoffeeAddGoodsRequestVo addShoppingCartGoodsRequestVo) {
        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();
        } 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){

        //筛选非加购商品--加价购商品不校验是否在菜单，不调用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(couponCode);
                    coupons.add(calculationDiscountCoupon);
                }
            }
        }
        return coupons;
    }



}
