/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: ShoppingCartAdapter
 * @Package cn.freemud.adapter
 * @Description:
 * @author: ping.wu
 * @date: 2018/5/26 17:42
 * @version V1.0
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
package cn.freemud.adapter;

import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.activity.ActivityDiscountsDto;
import cn.freemud.entities.dto.openplatform.WeixinProductRequestDto;
import cn.freemud.entities.dto.product.ProductAttributeValueType;
import cn.freemud.entities.dto.product.ValidateShopProductRequest;
import cn.freemud.entities.dto.product.ValidateShopProductType;
import cn.freemud.entities.dto.product.ValidateSkuProductType;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.enums.GoodsTypeEnum;
import cn.freemud.enums.ProductType;
import cn.freemud.utils.BeanUtil;
import com.freemud.application.sdk.api.log.ErrorLog;
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.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

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

@Component
public class ShoppingCartConvertAdapter {

    private static final String ATTRIBUTEID = "attributeId";
    private static final String ATTRIBUTENAME = "attributeName";

    public ShoppingCartGoodsDto.CartGoodsDetailDto getCartGoodsDetailDto(CreateOrderVo.PremiumExchangeActivity.Product product, GetProductsVo getProductsVo, String goodsId, ActivityCalculationDiscountResponseDto.CalculationDiscountResult.SendActivity.SendGoods sendGoods) {
        ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto = new ShoppingCartGoodsDto.CartGoodsDetailDto();
        cartGoodsDetailDto.setOriginalPrice(getProductsVo.getFinalPrice());
        int totalDiscountAmount = product.getQty() * (getProductsVo.getFinalPrice().intValue() - sendGoods.getNowPrice().intValue());
        cartGoodsDetailDto.setTotalDiscountAmount(totalDiscountAmount);
        cartGoodsDetailDto.setSpuId(product.getSpuId());
        cartGoodsDetailDto.setSkuId(goodsId);
        cartGoodsDetailDto.setQty(product.getQty());
        cartGoodsDetailDto.setSpuName(getProductsVo != null ? getProductsVo.getSpuName() : "");
        cartGoodsDetailDto.setSkuName(product.getSkuName());
        cartGoodsDetailDto.setPicture(getProductsVo != null ? getProductsVo.getSpuPicture() : "");
        cartGoodsDetailDto.setActivityType(ActivityTypeEnum.TYPE_81.getCode());
        cartGoodsDetailDto.setClassificationId(getProductsVo.getCategory());
        cartGoodsDetailDto.setClassificationName(getProductsVo.getCategoryName());
        List<ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra> cartGoodsExtraList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(product.getAttributes())) {
            for (CreateOrderVo.PremiumExchangeActivity.Product.Attribute attribute : product.getAttributes()) {
                ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra cartGoodsExtra = new ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra();
                cartGoodsExtra.setAttributeId(attribute.getAttributeId());
                cartGoodsExtra.setAttributeName(attribute.getAttributeValue());
                cartGoodsExtraList.add(cartGoodsExtra);
            }
        }
        cartGoodsDetailDto.setExtraList(cartGoodsExtraList);
        return cartGoodsDetailDto;
    }

    /**
     * @param cartGoods
     * @return
     */
    public List<ShoppingCartGoodsDto.CartGoodsDetailDto> convertCartGoods2DetailGoodsList(CartGoods cartGoods, List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods> apportionGoodsList, Map<String, String> duplicateGoodsMap) {
        List<ShoppingCartGoodsDto.CartGoodsDetailDto> cartGoodsDetailDtos = new ArrayList<>();
        if (GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType().equals(cartGoods.getGoodsType())) {
            return cartGoodsDetailDtos;
        } else {
            cartGoodsDetailDtos.add(convertCartGoods2DetailGoods(cartGoods, apportionGoodsList, duplicateGoodsMap));
        }
        return cartGoodsDetailDtos;
    }

    /**
     * @param cartGoods
     * @return
     */
    public ShoppingCartGoodsDto.CartGoodsDetailDto convertCartGoods2DetailGoods(CartGoods cartGoods, List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods> apportionGoodsList, Map<String, String> duplicateGoodsMap) {
        // 设置基础信息
        ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto = new ShoppingCartGoodsDto.CartGoodsDetailDto();
        cartGoodsDetailDto.setCartGoodsUid(cartGoods.getCartGoodsUid());
        cartGoodsDetailDto.setTaxId(cartGoods.getTaxId());
        cartGoodsDetailDto.setTax(cartGoods.getTax());
        cartGoodsDetailDto.setSpuId(cartGoods.getSpuId());
        cartGoodsDetailDto.setSpuName(cartGoods.getSpuName());
        cartGoodsDetailDto.setSkuId(StringUtils.isEmpty(cartGoods.getSkuId()) ? cartGoods.getSpuId() : cartGoods.getSkuId());
        cartGoodsDetailDto.setSkuName(StringUtils.isEmpty(cartGoods.getSkuName()) ? cartGoods.getSpuName() : cartGoods.getSkuName());
        cartGoodsDetailDto.setOriginalPrice(cartGoods.getOriginalPrice());
//        cartGoodsDetailDto.setTotalDiscountAmount(0);
        cartGoodsDetailDto.setSalePrice(cartGoods.getOriginalPrice());
        cartGoodsDetailDto.setPicture(cartGoods.getPic());
        cartGoodsDetailDto.setQty(cartGoods.getQty());
        cartGoodsDetailDto.setActivityType(cartGoods.getActivityType());
        cartGoodsDetailDto.setNodeId(cartGoods.getNodeId());
        cartGoodsDetailDto.setCategoryName(cartGoods.getCategoryName());
        cartGoodsDetailDto.setCouponCode(cartGoods.getCouponCode());
        cartGoodsDetailDto.setStockLimit(cartGoods.isStockLimit());
        cartGoodsDetailDto.setProductCode(cartGoods.getCustomerCode());
        cartGoodsDetailDto.setCustomerCode(cartGoods.getCustomerCode());
        cartGoodsDetailDto.setWeight(cartGoods.getWeight());
        cartGoodsDetailDto.setUnit(cartGoods.getUnit());
        cartGoodsDetailDto.setActivityDiscountsDtos(new ArrayList<>());
        cartGoodsDetailDto.setTotalDiscountAmount(0);
        cartGoodsDetailDto.setSpecialExtra(cartGoods.getSpecialExtra());
        cartGoodsDetailDto.setClassificationId(cartGoods.getClassificationId());
        cartGoodsDetailDto.setClassificationName(cartGoods.getClassificationName());
        if (GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType().equals(cartGoods.getGoodsType())) {
            cartGoodsDetailDto.setProductType(ProductType.SETMEAL.getCode());
        } else if (cartGoods.isWeightType()) {
            cartGoodsDetailDto.setProductType(ProductType.WEIGHT_PRODUCT.getCode());
        }
        //小料
        if (CollectionUtils.isNotEmpty(cartGoods.getProductMaterialList())) {
            List<ShoppingCartGoodsDto.CartGoodsDetailDto.MaterialGoods> materialList = new ArrayList<>(0);
            for (CartGoods.MaterialGoods materialGoods : cartGoods.getProductMaterialList()) {
                ShoppingCartGoodsDto.CartGoodsDetailDto.MaterialGoods goods = new ShoppingCartGoodsDto.CartGoodsDetailDto.MaterialGoods();
                goods.setSpuId(materialGoods.getSpuId());
                goods.setSpuName(materialGoods.getSpuName());
                goods.setOriginalPrice(materialGoods.getOriginalPrice());
                goods.setSalePrice(materialGoods.getFinalPrice());
                goods.setQty(cartGoods.getQty());
                goods.setTotalDiscountAmount(0);
                materialList.add(goods);
            }
            cartGoodsDetailDto.setMaterialList(materialList);
        }
        // 设置总优惠&售价
        List<ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra> cartGoodsExtras = BeanUtil.convertBeans(cartGoods.getExtra(), ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra::new);
        cartGoodsDetailDto.setExtraList(cartGoodsExtras);
        //61: 单品买M赠N  \  62:买赠  \ 6:买M赠N
        if (ObjectUtils.equals(ActivityTypeEnum.TYPE_61.getCode(), cartGoods.getActivityType()) || ObjectUtils.equals(ActivityTypeEnum.TYPE_6.getCode(), cartGoods.getActivityType())
                || ObjectUtils.equals(ActivityTypeEnum.TYPE_62.getCode(), cartGoods.getActivityType())) {
            cartGoodsDetailDto.setTotalDiscountAmount(cartGoods.getOriginalAmount().intValue() - cartGoods.getAmount().intValue());
        } else {
            List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods> collect = apportionGoodsList.stream().filter(a -> ObjectUtils.equals(cartGoods.getCartGoodsUid(), a.getCartGoodsUid())).collect(Collectors.toList());
            //List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods> collect = apportionGoodsList.stream().filter(a -> ObjectUtils.equals(cartGoods.getSkuId(), a.getGoodsId()) || ObjectUtils.equals(cartGoods.getSpuId(), a.getGoodsId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                setTotalDiscountAndSalePrice(collect, cartGoodsDetailDto, duplicateGoodsMap);
                // 设置商品行，优惠活动均摊
                setActivityDiscounts(collect, cartGoodsDetailDto, duplicateGoodsMap);
            }
        }
        return cartGoodsDetailDto;
    }

    private void setActivityDiscounts(List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods> apportionGoodsList, ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto, Map<String, String> duplicateGoodsMap) {
        List<ActivityDiscountsDto> activityDiscountsDtoList = new ArrayList<>();
        int goodsTotalQty = apportionGoodsList.stream().mapToInt(apportionGoods -> apportionGoods.getGoodsQuantity()).sum();
        for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods apportionGoods : apportionGoodsList) {
            /**
             * 1. 商品券：cartGoodsDetailDto.couponCode非空，保留ApportionGoods#ApportionDetails#apportionType中32的
             * 2. 普通商品：cartGoodsDetailDto.couponCode空，去掉32的
             */
            List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods.ApportionDetails> apportionDetails = apportionGoods.getApportionDetails().stream().filter(detail -> !detail.getActivityType().equals(ActivityTypeEnum.TYPE_32.getCode())
                    && !detail.getActivityType().equals(ActivityTypeEnum.TYPE_104.getCode()) && !detail.getActivityType().equals(ActivityTypeEnum.TYPE_2.getCode()) && !detail.getActivityType().equals(ActivityTypeEnum.TYPE_21.getCode())).collect(Collectors.toList());
            for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods.ApportionDetails detail : apportionDetails) {
                List<ActivityDiscountsDto> currentDiscount = activityDiscountsDtoList.stream().filter(discount -> ObjectUtils.equals(discount.getActivityCode(), detail.getActivityCode())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(currentDiscount)) {
                    currentDiscount.get(0).setDiscountAmount(currentDiscount.get(0).getDiscountAmount() + detail.getActivityApportionAmount().intValue() * apportionGoods.getGoodsQuantity() * cartGoodsDetailDto.getQty() / goodsTotalQty);
                } else {
                    ActivityDiscountsDto activityDiscountsDto = new ActivityDiscountsDto();
                    activityDiscountsDto.setActivityCode(detail.getActivityCode());
                    activityDiscountsDto.setActivityName(detail.getActivityName());
                    activityDiscountsDto.setActivityType(detail.getActivityType());
                    activityDiscountsDto.setDiscountAmount(detail.getActivityApportionAmount().intValue() * apportionGoods.getGoodsQuantity() * cartGoodsDetailDto.getQty() / goodsTotalQty);
                    activityDiscountsDtoList.add(activityDiscountsDto);
                }
            }
        }
        cartGoodsDetailDto.setActivityDiscountsDtos(activityDiscountsDtoList);
    }

    /**
     *  活动级别的促销均摊
     * 获取当前商品的售后价格
     *
     * @param apportionGoodsList 促销均摊列表
     * @param cartGoodsDetailDto 当前商品行
     * @param duplicateGoodsMap 当前商品行  此map是为了促销除不尽时，拆商品行所用，例如，3份折扣10元
     * key为：goodsId；value以逗号分割：0为goodsId分组对应的数量，value为已计算的折扣金额
     *
     */
    private void setTotalDiscountAndSalePrice(List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods> apportionGoodsList, ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto, Map<String, String> duplicateGoodsMap) {
        Long originalPrice = cartGoodsDetailDto.getOriginalPrice();
        Long discountPrice = 0L;
        int goodsTotalQty = apportionGoodsList.stream().mapToInt(apportionGoods -> apportionGoods.getGoodsQuantity()).sum();
        for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods apportionGoods : apportionGoodsList) {
            //折扣=所有折扣和*百分比（当前行商品数量/购物车总商品数量）
            discountPrice += apportionGoods.getApportionDetails().stream().filter(d -> ObjectUtils.notEqual(ActivityTypeEnum.TYPE_32.getCode(), d.getActivityType())
                    && ObjectUtils.notEqual(ActivityTypeEnum.TYPE_104.getCode(), d.getActivityType()) //X件Y折
                    && ObjectUtils.notEqual(ActivityTypeEnum.TYPE_2.getCode(), d.getActivityType()) //单品特价
                    && ObjectUtils.notEqual(ActivityTypeEnum.TYPE_21.getCode(), d.getActivityType())//单品折扣
            ).mapToLong(t -> t.getActivityApportionAmount() * apportionGoods.getGoodsQuantity()).sum() * cartGoodsDetailDto.getQty() / goodsTotalQty;
        }
        String currentGoodsIdMap = duplicateGoodsMap.get(cartGoodsDetailDto.getCartGoodsUid());
        if (currentGoodsIdMap != null) {
            String[] value = currentGoodsIdMap.split(",");
            //不是最后一行商品，折扣为discountPrice
            if (Integer.parseInt(value[0]) > 1) {
                int totalDiscountPrice = Integer.parseInt(value[1]) + discountPrice.intValue();
                int index = Integer.parseInt(value[0]) - 1;
                duplicateGoodsMap.put(cartGoodsDetailDto.getCartGoodsUid(), String.format("%s,%s", index, totalDiscountPrice));
            } else {
                //最后一行
                Long totalDiscountAmount = 0L;
                for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods apportionGoods : apportionGoodsList) {
                    totalDiscountAmount += apportionGoods.getApportionDetails().stream().filter(d -> ObjectUtils.notEqual(ActivityTypeEnum.TYPE_32.getCode(), d.getActivityType())
                            && ObjectUtils.notEqual(ActivityTypeEnum.TYPE_104.getCode(), d.getActivityType())
                            && ObjectUtils.notEqual(ActivityTypeEnum.TYPE_2.getCode(), d.getActivityType())
                            && ObjectUtils.notEqual(ActivityTypeEnum.TYPE_21.getCode(), d.getActivityType())
                    ).mapToLong(t -> t.getActivityApportionAmount() * apportionGoods.getGoodsQuantity()).sum();
                }
                //折扣为：总折扣金额-已折扣金额
                discountPrice = totalDiscountAmount - Integer.parseInt(value[1]);
            }
        }
        cartGoodsDetailDto.setTotalDiscountAmount(discountPrice.intValue());
        cartGoodsDetailDto.setSalePrice(originalPrice - discountPrice / cartGoodsDetailDto.getQty());
    }

    /**
     * @param cartGoods
     * @return
     */
    public List<ShoppingCartGoodsDto.CartGoodsDetailDto> convertComboxGoods2DetailGoods(CartGoods cartGoods,Integer totalDiscountAmount) {
        List<ShoppingCartGoodsDto.CartGoodsDetailDto> cartGoodsDetailDtos = new ArrayList<>();
        cartGoodsDetailDtos.addAll(getComboxGoods2DetailGoods(cartGoods, cartGoods.getProductComboList(), true,totalDiscountAmount));
        cartGoodsDetailDtos.addAll(getComboxGoods2DetailGoods(cartGoods, cartGoods.getProductGroupList(), false,totalDiscountAmount));
        return cartGoodsDetailDtos;
    }


    /**
     * @param cartGoods
     * @return
     */
    public List<ShoppingCartGoodsDto.CartGoodsDetailDto> getComboxGoods2DetailGoods(CartGoods cartGoods, List<CartGoods.ComboxGoods> comboxGoodsList, boolean isFixed,Integer totalDiscountAmount) {
        List<ShoppingCartGoodsDto.CartGoodsDetailDto> cartGoodsDetailDtos = new ArrayList<>();
        if (CollectionUtils.isEmpty(comboxGoodsList)) {
            return cartGoodsDetailDtos;
        }
        int size = comboxGoodsList.size();
        //当前套餐(固定搭配)总优惠=原总价-现总价-可选商品优惠价
        Long discountAmount = totalDiscountAmount -
                cartGoods.getProductGroupList().stream().mapToLong(product -> (product.getOriginalPrice() - product.getFinalPrice()) * product.getQty()).sum() * cartGoods.getQty();
        // 当前套餐（固定搭配）总原价
        Long totalOriginalPrice = cartGoods.getProductComboList().stream().mapToLong(cart -> cart.getQty() * cart.getOriginalPrice()).sum() * cartGoods.getQty();
        Integer tempDiscount = 0;
        for (CartGoods.ComboxGoods comboxGoods : comboxGoodsList) {
            ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto = new ShoppingCartGoodsDto.CartGoodsDetailDto();
            cartGoodsDetailDto.setTaxId(cartGoods.getTaxId());
            cartGoodsDetailDto.setTax(cartGoods.getTax());
            cartGoodsDetailDto.setSpuId(comboxGoods.getGoodsId());
            cartGoodsDetailDto.setSpuName(comboxGoods.getSpuName());
            cartGoodsDetailDto.setSkuId(comboxGoods.getGoodsId());
            cartGoodsDetailDto.setSkuName(StringUtils.isEmpty(comboxGoods.getSkuName()) ? comboxGoods.getSpuName() : comboxGoods.getSkuName());
            cartGoodsDetailDto.setOriginalPrice(comboxGoods.getOriginalPrice());
            cartGoodsDetailDto.setPicture(comboxGoods.getPic());
            int qty = comboxGoods.getQty() * cartGoods.getQty();
            cartGoodsDetailDto.setQty(qty);
            cartGoodsDetailDto.setProductType(comboxGoods.isWeightType() ? ProductType.WEIGHT_PRODUCT.getCode() : ProductType.SETMEAL.getCode());
            cartGoodsDetailDto.setParentProductId(cartGoods.getGoodsId());
            cartGoodsDetailDto.setIsFixedProduct(isFixed);
            cartGoodsDetailDto.setStockLimit(cartGoods.isStockLimit());
            cartGoodsDetailDto.setCustomerCode(comboxGoods.getCustomerCode());
            cartGoodsDetailDto.setWeight(comboxGoods.getWeight());
            cartGoodsDetailDto.setUnit(comboxGoods.getUnit());
            List<ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra> cartGoodsExtras = BeanUtil.convertBeans(comboxGoods.getExtra(), ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra::new);
            cartGoodsDetailDto.setExtraList(cartGoodsExtras);
            cartGoodsDetailDto.setSpecialExtra(comboxGoods.getSpecialExtra());
            //小料
            if (CollectionUtils.isNotEmpty(comboxGoods.getProductMaterialList())) {
                List<ShoppingCartGoodsDto.CartGoodsDetailDto.MaterialGoods> materialList = new ArrayList<>(0);
                for (CartGoods.MaterialGoods materialGoods : comboxGoods.getProductMaterialList()) {
                    ShoppingCartGoodsDto.CartGoodsDetailDto.MaterialGoods goods = new ShoppingCartGoodsDto.CartGoodsDetailDto.MaterialGoods();
                    goods.setSpuId(materialGoods.getSpuId());
                    goods.setSpuName(materialGoods.getSpuName());
                    goods.setOriginalPrice(materialGoods.getOriginalPrice());
                    goods.setSalePrice(materialGoods.getFinalPrice());
                    goods.setQty(cartGoods.getQty());
                    goods.setTotalDiscountAmount(0);
                    materialList.add(goods);
                }
                cartGoodsDetailDto.setMaterialList(materialList);
            }
            //获取当前套餐固定商品的均摊价格
            if (isFixed) {
                if (size-- == 1) {
                    cartGoodsDetailDto.setTotalDiscountAmount(discountAmount.intValue() - tempDiscount);
                } else {
                    Long currentDiscountAmount = (qty * comboxGoods.getOriginalPrice() * discountAmount) / totalOriginalPrice;
                    cartGoodsDetailDto.setTotalDiscountAmount(currentDiscountAmount.intValue());
                    tempDiscount += currentDiscountAmount.intValue();
                }
            } else {
                cartGoodsDetailDto.setTotalDiscountAmount((comboxGoods.getOriginalPrice().intValue() - comboxGoods.getFinalPrice().intValue()) * comboxGoods.getQty() * cartGoods.getQty());
            }
            cartGoodsDetailDtos.add(cartGoodsDetailDto);
        }
        return cartGoodsDetailDtos;
    }


    public WeixinProductRequestDto convent2WeixinProductRequestDto(AddGoodsByWeixinCardRequestVo request) {
        WeixinProductRequestDto requestDto = new WeixinProductRequestDto();
        requestDto.setPartnerId(request.getPartnerId());
        requestDto.setCardId(request.getCardId());
        requestDto.setAppId(request.getAppId());
        requestDto.setEncryptCode(request.getEncryptCode());
        return requestDto;
    }

    public AddShoppingCartGoodsRequestVo convent2AddshoppingCartGoods(AddGoodsByWeixinCardRequestVo request, GetProductsVo getProductsVo) {
        AddShoppingCartGoodsRequestVo cartGoodsRequestVo = new AddShoppingCartGoodsRequestVo();
        cartGoodsRequestVo.setSessionId(request.getSessionId());
        cartGoodsRequestVo.setPartnerId(request.getPartnerId());
        cartGoodsRequestVo.setShopId(request.getShopId());
        cartGoodsRequestVo.setAppId(request.getAppId());
        cartGoodsRequestVo.setSpuId(request.getEncryptCode());
        // cartGoodsRequestVo.setSkuId(getProductsVo.getSkuId());
        List<GetMenuResponseDto.DataBean.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean.ProductAttributeGroupListBean> productAttributeGroupList = getProductsVo.getProductAttributeGroupList();
        if (productAttributeGroupList != null && productAttributeGroupList.size() > 0) {
            List<CartGoods.CartGoodsExtra> cartGoodsExtraList = new ArrayList<>();
            for (GetMenuResponseDto.DataBean.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean.ProductAttributeGroupListBean productAttributeList : productAttributeGroupList) {
                CartGoods.CartGoodsExtra goodsExtra = new CartGoods.CartGoodsExtra();
                goodsExtra.setAttributeId(productAttributeList.getAttributeValues().get(0).getAttributeId());
                goodsExtra.setAttributeName(productAttributeList.getAttributeValues().get(0).getAttributeValue());
                cartGoodsExtraList.add(goodsExtra);
            }
            cartGoodsRequestVo.setExtra(cartGoodsExtraList);
        }
        return cartGoodsRequestVo;
    }

    public CartGoods convent2CartGoods(CartGoods cartGood, Long nowPirce) {
        CartGoods cartGoods = new CartGoods();
        cartGoods.setCartGoodsUid(cartGood.getCartGoodsUid());
        cartGoods.setGoodsId(cartGood.getGoodsId());
        cartGoods.setGoodsType(cartGood.getGoodsType());
        cartGoods.setSpuId(cartGood.getSpuId());
        cartGoods.setSkuId(cartGood.getSkuId());
        cartGoods.setSpecProductId(cartGood.getSpecProductId());
        cartGoods.setOriginalPrice(nowPirce);
        cartGoods.setPackPrice(cartGood.getPackPrice());
        cartGoods.setOriginalAmount(nowPirce);
        cartGoods.setAmount(0L);
        cartGoods.setName(cartGood.getName());
        cartGoods.setSpuName(cartGood.getSpuName());
        cartGoods.setSubName(cartGood.getSubName());
        cartGoods.setNodeId(cartGood.getNodeId());
        cartGoods.setCategoryName(cartGood.getCategoryName());
        List<CartGoods.CartGoodsExtra> extra = Lists.newArrayList();
        List<CartGoods.CartGoodsExtra> cartGoodsExtras = cartGood.getExtra();
        if (CollectionUtils.isNotEmpty(cartGoodsExtras)) {
            cartGoodsExtras.forEach(cartGoodsExtra -> {
                CartGoods.CartGoodsExtra goodsExtra = new CartGoods.CartGoodsExtra();
                goodsExtra.setAttributeId(cartGoodsExtra.getAttributeId());
                goodsExtra.setAttributeName(cartGoodsExtra.getAttributeName());
                extra.add(goodsExtra);
            });
        }
        cartGoods.setExtra(extra);
        cartGoods.setPic(cartGood.getPic());
        cartGoods.setCreateTimeMili(cartGood.getCreateTimeMili());
        cartGoods.setSkuName(cartGood.getSkuName());
        cartGoods.setSkuName(cartGood.getSkuName());
        cartGood.setClassificationId(cartGood.getClassificationId());
        cartGood.setClassificationName(cartGood.getClassificationName());
        cartGoods.setActivityType(ActivityTypeEnum.TYPE_61.getCode());
        return cartGoods;
    }

    public static CartGoods convent2CartGoods(AddShoppingCartGoodsRequestVo 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();
        }
        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<>();
        List<CartGoods.MaterialGoods> materialGoodsList = 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);
            }
        }
        //加料商品集
        if (CollectionUtils.isNotEmpty(addShoppingCartGoodsRequestVo.getProductMaterialList())) {
            for (MaterialRequestVo materialRequestVo : addShoppingCartGoodsRequestVo.getProductMaterialList()) {
                CartGoods.MaterialGoods materialGoods = new CartGoods.MaterialGoods();
                materialGoods.setSpuId(materialRequestVo.getSpuId());
                materialGoodsList.add(materialGoods);
            }
        }
        cartGoods.setProductComboList(productComboList);
        cartGoods.setProductGroupList(productGroupList);
        cartGoods.setProductMaterialList(materialGoodsList);
        return cartGoods;
    }

    /**
     * 设置统计分类编码和统计分类名称
     *
     * @param cartGoods
     * @param productBeanListSpuClass
     */
    public static void setClassification(CartGoods cartGoods, List<ProductBeanDTO> productBeanListSpuClass) {
        cartGoods.setClassificationId(productBeanListSpuClass.get(0).getCategory());
        cartGoods.setClassificationName(productBeanListSpuClass.get(0).getCategoryName());
    }

    /**
     * 设置统计分类编码和统计分类名称
     *
     * @param cartGoods
     * @param getProductsVo
     */
    public static void setClassification(CartGoods cartGoods, GetProductsVo getProductsVo) {
        cartGoods.setClassificationId(getProductsVo.getCategory());
        cartGoods.setClassificationName(getProductsVo.getCategoryName());
    }

    /**
     * 兼容 skuId 不传转null 导致库存校验 NullPointerException
     *
     * @param addShoppingCartGoodsRequestVo
     */
    public static void convent2SkuId(AddShoppingCartGoodsRequestVo addShoppingCartGoodsRequestVo) {
        String skuId = StringUtils.isNotBlank(addShoppingCartGoodsRequestVo.getSkuId()) ? addShoppingCartGoodsRequestVo.getSkuId() : "";
        addShoppingCartGoodsRequestVo.setSkuId(skuId);
    }

    public String jointPk(String a, String b) {
        StringBuffer stringBuffer = new StringBuffer();
        return stringBuffer.append(a).append(b).toString();
    }


    public ValidateShopProductRequest getValidateShopProductRequest(CheckCartRequest checkCartRequest) {
        ValidateShopProductRequest validateShopProductRequest = new ValidateShopProductRequest();
        validateShopProductRequest.setChannel(checkCartRequest.getMenuType());
        validateShopProductRequest.setPartnerId(checkCartRequest.getPartnerId());
        validateShopProductRequest.setStoreId(checkCartRequest.getStoreId());
        validateShopProductRequest.setProductTypeList(new ArrayList<>());
        for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods cartGoods : checkCartRequest.getCartGoodsList()) {
            // 过滤非商品券商品
            if (cartGoods.getCartGoodsUid().startsWith(CommonsConstant.COUPON_PREFIX)) {
                continue;
            }
            ValidateShopProductType productType = new ValidateShopProductType();
            productType.setSpuId(cartGoods.getSpuId());
            // 多规格商品券
            productType.setSkuId((ObjectUtils.equals(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.SKU_GOODS.getGoodsType(), cartGoods.getGoodsType())
                    || ObjectUtils.equals(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.COUPON_GOODS.getGoodsType(), cartGoods.getGoodsType())
                    || ObjectUtils.equals(GoodsTypeEnum.ALL_COUPON_GOODS.getGoodsType(), cartGoods.getGoodsType()))
                    ? cartGoods.getSkuId() : cartGoods.getSpuId());
            // 应产品要求
            // 普通商品，取商品的finalePrice(普通商品售价);套餐商品，取originalPrice(套餐价格)
            productType.setPrice(cartGoods.getFinalPrice() == null ? 0 : cartGoods.getFinalPrice().intValue());
            productType.setValidatePrice(productType.getPrice() == 0 ? 0 : 1);
            productType.setValidateAttribute(1);
            productType.setValidateStatuses(Arrays.asList(2));
            productType.setUuid(cartGoods.getCartGoodsUid());
            //属性
            productType.setAttributeList(getAttributes(cartGoods.getExtra()));
            //可选搭配&固定搭配
            productType.setComboProductTypeList(getValidateSkuProductType(cartGoods.getProductComboList()));
            productType.setProductGroupTypeList(getValidateSkuProductType(cartGoods.getProductGroupList()));
            productType.setMemberDiscount(cartGoods.getMemberDiscount());
            validateShopProductRequest.getProductTypeList().add(productType);
        }
        return validateShopProductRequest;
    }

    public List<ProductAttributeValueType> getAttributes(List<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.CartGoodsExtra> extra) {
        List<ProductAttributeValueType> attributeValueTypes = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(extra)) {
            for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.CartGoodsExtra cartGoodsExtra : extra) {
                ProductAttributeValueType productAttributeValueType = new ProductAttributeValueType();
                productAttributeValueType.setAttributeId(cartGoodsExtra.getAttributeId());
                productAttributeValueType.setAttributeValue(cartGoodsExtra.getAttributeName());
                attributeValueTypes.add(productAttributeValueType);
            }
        }
        return attributeValueTypes;
    }

    public List<ValidateSkuProductType> getValidateSkuProductType(List<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods> productComboList) {
        List<ValidateSkuProductType> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(productComboList)) {
            for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods comboxGoods : productComboList) {
                if("0".equals(comboxGoods.getGoodsId())){
                    continue;
                }
                ValidateSkuProductType validateSkuProductType = new ValidateSkuProductType();
                validateSkuProductType.setProductId(StringUtils.isNotEmpty(comboxGoods.getSpuId()) ? comboxGoods.getSpuId() : comboxGoods.getSkuId());
                validateSkuProductType.setSkuId(comboxGoods.getSkuId());
                validateSkuProductType.setPrice(comboxGoods.getOriginalPrice() == null ? 0 : comboxGoods.getOriginalPrice().intValue());
                validateSkuProductType.setMarkUpPrice(comboxGoods.getFinalPrice() == null ? 0 : comboxGoods.getFinalPrice().intValue());
                validateSkuProductType.setQty(comboxGoods.getQty());
                validateSkuProductType.setAttributeList(getAttributes(comboxGoods.getExtra()));
                validateSkuProductType.setProductGroupId(comboxGoods.getProductGroupId());
                result.add(validateSkuProductType);
            }
        }
        return result;
    }


    /**
     * 更新当前购物车商品行信息
     *
     * @param cartGoods    当前购物车商品行
     * @param productBeans 购物车中所有的productId对应的商品详情
     */
    public void updateCartGoodsInfoForMCoffee(com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods cartGoods, List<ProductBeanDTO> productBeans) {
        try {
            Optional<ProductBeanDTO> firstProduct = productBeans.stream().filter(p -> ObjectUtils.equals(p.getPid(), cartGoods.getSpuId())).findFirst();
            if (!firstProduct.isPresent()) {
                return;
            }
            ProductBeanDTO spuProduct = firstProduct.get();
            //是否是sku商品
            boolean isSkuProduct = ObjectUtils.equals(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.SKU_GOODS.getGoodsType(), cartGoods.getGoodsType());
            // 如果是套餐商品，更新套餐内固定商品&可选商品的详细信息
            boolean isSetMealProduct = ObjectUtils.equals(com.freemud.sdk.api.assortment.shoppingcart.constant.ProductType.SetMeal.getCode(), spuProduct.getType()) || ObjectUtils.equals(com.freemud.sdk.api.assortment.shoppingcart.constant.ProductType.IncreasedPackage.getCode(), spuProduct.getType());
            ProductBeanDTO.SkuProductBean skuProduct = isSkuProduct ? spuProduct.getSkuList().stream().filter(p -> ObjectUtils.equals(cartGoods.getSkuId(), p.getSkuId())).findFirst().get() : null;

            Map<String, String> attributes = getAttributesNew(cartGoods.getExtra());
            if(!"早餐啡常搭".equals(cartGoods.getName()) && !"早餐啡常搭".equals(cartGoods.getSkuName()) && !"早餐啡常搭".equals(cartGoods.getSpuName())
                    && !"啡常搭".equals(cartGoods.getName()) && !"啡常搭".equals(cartGoods.getSkuName()) && !"啡常搭".equals(cartGoods.getSpuName())) {
                cartGoods.setName(spuProduct.getName());
                cartGoods.setSpuName(spuProduct.getName());
                cartGoods.setSkuName(isSkuProduct ? skuProduct.getProductName() : spuProduct.getName());
            }
            cartGoods.setSpecProductId(attributes.get(ATTRIBUTEID));
            cartGoods.setPic(spuProduct.getPicture());
            cartGoods.setPackPrice(isSkuProduct ? skuProduct.getPackPrice() : spuProduct.getPackPrice());
            cartGoods.setStockLimit(isSkuProduct ? ObjectUtils.equals(1, skuProduct.getStockLimit()) : ObjectUtils.equals(1, spuProduct.getStockLimit()));
            cartGoods.setCustomerCode(isSkuProduct ? skuProduct.getCustomerCode() : spuProduct.getCustomerCode());
            cartGoods.setRiseSell(isSkuProduct ? skuProduct.getRiseSell() : spuProduct.getRiseSell());
            cartGoods.setMemberDiscount(spuProduct.getMemberDiscountResult());
            cartGoods.setClassificationId(spuProduct.getCategory());
            cartGoods.setClassificationName(spuProduct.getCategoryName());
            cartGoods.setTax(spuProduct.getTax());
            cartGoods.setTaxId(spuProduct.getTaxId());
            String skuSpecName = "";
            if (isSkuProduct && CollectionUtils.isNotEmpty(skuProduct.getSkuSpecValues())) {
                List<String> skuSpecValus = skuProduct.getSkuSpecValues().stream().map(p -> p.getSpecValue()).collect(Collectors.toList());
                skuSpecName = StringUtils.join(skuSpecValus, "/");
            }
            String attributeName = attributes.get(ATTRIBUTENAME) == null ? "" : attributes.get(ATTRIBUTENAME);
            //购物车小标题
            cartGoods.setSubName(StringUtils.isNotEmpty(skuSpecName) && StringUtils.isNotEmpty(attributeName) ?
                    skuSpecName + "/" + attributeName : skuSpecName + attributeName);
            if (isSetMealProduct) {
                //套餐固定商品
                if (CollectionUtils.isNotEmpty(cartGoods.getProductComboList())) {
                    for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods productCombo : cartGoods.getProductComboList()){
                        //套餐子商品多规格商品
                        if(productCombo.getSpuId() == null && !productCombo.getSkuId().equals(productCombo.getSpuId()) ){
                            updateComboxGoodsInfoForMCoffee(productCombo, spuProduct, true);
                        }else {
                            //套餐子商品为单品
                            updateComboxGoodsInfoForMCoffee(productCombo, spuProduct, true);
                        }
                    }
                }
                //套餐可选商品
                if (CollectionUtils.isNotEmpty(cartGoods.getProductGroupList())) {
                    for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods comboxGoods : cartGoods.getProductComboList()){
                        //套餐子商品多规格商品
                        if(comboxGoods.getSpuId() == null && !comboxGoods.getSkuId().equals(comboxGoods.getSpuId()) ){
                            for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods productGroup : cartGoods.getProductGroupList()) {
                                updateComboxGoodsInfoForMCoffee(productGroup, spuProduct, false);
                            }
                        }else {
                            for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods productGroup : cartGoods.getProductGroupList()) {
                                updateComboxGoodsInfoForMCoffee(productGroup, spuProduct, false);
                            }
                        }
                    }
                }
            }
            //更新当前商品行价格
            Long newOrigOriginalPrice = 0L;
            if (isSetMealProduct) {
                newOrigOriginalPrice += cartGoods.getProductComboList().stream().mapToLong(t -> t.getOriginalAmount()).sum();
                newOrigOriginalPrice += cartGoods.getProductGroupList().stream().mapToLong(t -> t.getOriginalAmount()).sum();
            } else {
                newOrigOriginalPrice = isSkuProduct ? skuProduct.getFinalPrice() : spuProduct.getFinalPrice();
            }
            cartGoods.setOriginalPrice(newOrigOriginalPrice);
            cartGoods.setOriginalAmount(newOrigOriginalPrice * cartGoods.getQty());
            cartGoods.setAmount(newOrigOriginalPrice * cartGoods.getQty());
            //咨询商品服务，套餐售价取originalPrice
            cartGoods.setFinalPrice(isSetMealProduct ? spuProduct.getOriginalPrice() : isSkuProduct ? skuProduct.getFinalPrice() : spuProduct.getFinalPrice());
            cartGoods.setWeight(isSkuProduct ? skuProduct.getWeight() : spuProduct.getWeight());
            cartGoods.setUnit(isSkuProduct ? skuProduct.getUnit() : spuProduct.getUnit());
            cartGoods.setWeightType(CommonsConstant.WEIGHT_PRODUCT.equals(spuProduct.getWeightType()));
            cartGoods.setMaterialAmount(0L);
            cartGoods.setOriginalMaterialAmount(0L);
            // todo 设置加料
            this.checkMaterialProductForMCoffee(cartGoods, spuProduct);

        } catch (Exception ex) {
            ErrorLog.infoConvertJson(this.getClass(), "updateCartGoodsInfoForMCoffee_Error", ex);
            cartGoods.setCartGoodsUid(null);
        }
    }

    /**
     * 更新套餐固定商品、可选商品信息
     *
     * @param comboxGoods       固定商品或可选商品
     * @param parentProductBean 套餐服商品
     * @param isComboxGoods     是否是固定商品
     * @return
     */
    private void updateComboxGoodsInfoForMCoffee(com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods comboxGoods, ProductBeanDTO parentProductBean, boolean isComboxGoods) {
        if("0".equals(comboxGoods.getGoodsId())){
            return;
        }
        ProductBeanDTO.ProductComboType productComboType = new ProductBeanDTO.ProductComboType();
        ProductBeanDTO.ProductGroupType.GroupDetailType groupDetailType = new ProductBeanDTO.ProductGroupType.GroupDetailType();
        if (isComboxGoods) {
            productComboType = parentProductBean.getProductComboList().stream().filter(p -> ObjectUtils.equals(comboxGoods.getGoodsId(), p.getProductId())).findFirst().orElse(new ProductBeanDTO.ProductComboType());
        } else {
            Map<String, ProductBeanDTO.ProductGroupType.GroupDetailType> map = new HashMap<>();
            parentProductBean.getProductGroupList().stream().map(t -> t.getGroupDetail()).forEach(group -> group.forEach(detailType -> map.put(detailType.getProductId(), detailType)));
            groupDetailType = map.get(comboxGoods.getGoodsId());
        }

        // 若是固定商品则取商品详情的FinalPrice，若是可选商品则取MarkUpPrice
        Long finalPrice = isComboxGoods ? productComboType.getFinalPrice().longValue() : groupDetailType.getMarkUpPrice().longValue();
        // 设置商品详情
        Map<String, String> attributes = getAttributesNew(comboxGoods.getExtra());
        comboxGoods.setName(isComboxGoods ? productComboType.getProductName() : groupDetailType.getProductName());
        comboxGoods.setSpuName(comboxGoods.getName());
        comboxGoods.setSpecProductId(attributes.get(ATTRIBUTEID));
        comboxGoods.setSubName(attributes.get(ATTRIBUTENAME));
        comboxGoods.setPic(isComboxGoods ? productComboType.getPicture() : groupDetailType.getPicture());
        comboxGoods.setOriginalPrice(isComboxGoods ? productComboType.getFinalPrice().longValue() : groupDetailType.getProductFinalPrice().longValue());
        comboxGoods.setOriginalAmount(comboxGoods.getOriginalPrice() * comboxGoods.getQty());
        comboxGoods.setAmount(finalPrice * comboxGoods.getQty());
        comboxGoods.setCustomerCode(isComboxGoods ? productComboType.getCustomerCode() : groupDetailType.getCustomerCode());
        comboxGoods.setFinalPrice(finalPrice);
        comboxGoods.setWeightType(isComboxGoods ? CommonsConstant.WEIGHT_PRODUCT.equals(productComboType.getWeightType()) : CommonsConstant.WEIGHT_PRODUCT.equals(groupDetailType.getWeightType()));
        comboxGoods.setUnit(isComboxGoods ? productComboType.getUnit() : groupDetailType.getUnit());
        comboxGoods.setWeight(isComboxGoods ? productComboType.getWeight() : groupDetailType.getWeight());
        comboxGoods.setTax(isComboxGoods ? productComboType.getTax() : groupDetailType.getTax());
        comboxGoods.setTaxId(isComboxGoods ? productComboType.getTaxId() : groupDetailType.getTaxId());

        // TODO: 2020/10/22  套餐内可选商品加料，暂无
        if(CollectionUtils.isNotEmpty(comboxGoods.getProductMaterialList())){
            List<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.MaterialGoods> productMaterialList = new ArrayList<>();
            com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.MaterialGoods materialGoods = new com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.MaterialGoods();
            productMaterialList.add(materialGoods);
            comboxGoods.setProductMaterialList(productMaterialList);
        }
    }

    private Map<String, String> getAttributesNew(List<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.CartGoodsExtra> extra) {
        if (CollectionUtils.isEmpty(extra)) {
            return new HashMap<>();
        }
        List<String> attributeIds = extra.stream().map(com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.CartGoodsExtra::getAttributeId).collect(Collectors.toList());
        List<String> attributeNames = extra.stream().map(com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.CartGoodsExtra::getAttributeName).collect(Collectors.toList());
        Map<String, String> result = new HashMap<>();
        result.put(ATTRIBUTEID, StringUtils.join(attributeIds, "/"));
        result.put(ATTRIBUTENAME, StringUtils.join(attributeNames, "/"));
        return result;
    }

    private void checkMaterialProductForMCoffee(com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods cartGoods, ProductBeanDTO spuProduct) {

        if (CollectionUtils.isEmpty(cartGoods.getProductMaterialList())) return;
        //加料信息为空
        if (CollectionUtils.isEmpty(spuProduct.getAdditionalGroupList())) {
            cartGoods.setGoodsType(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.EXCEPTION_GOODS.getGoodsType());
            cartGoods.setProductMaterialList(new ArrayList<>());
            return;
        }
        //提取加料信息
        List<String> materialSpu = new ArrayList<>();
        List<ProductBeanDTO.ProductGroupType.GroupDetailType> groupDetail = new ArrayList<>();
        for (ProductBeanDTO.ProductGroupType productGroupType : spuProduct.getAdditionalGroupList()){
            groupDetail.addAll(productGroupType.getGroupDetail());
        }
        HashMap<String, ProductBeanDTO.ProductGroupType.GroupDetailType> materialHash = new HashMap<>();
        for (ProductBeanDTO.ProductGroupType.GroupDetailType groupDetailType : groupDetail) {
            materialHash.put(groupDetailType.getProductId(), groupDetailType);
            materialSpu.add(groupDetailType.getProductId());
        }
        //加车小料和商品小料没有交集则提示商品信息有异常
        if(CollectionUtils.isEmpty(cartGoods.getProductMaterialList().stream().filter(e->materialSpu.contains(e.getSpuId())).collect(Collectors.toList()))) {
            cartGoods.setGoodsType(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.EXCEPTION_GOODS.getGoodsType());
            cartGoods.setProductMaterialList(new ArrayList<>());
            return;
        }
        ArrayList<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.MaterialGoods> materialGoodsList = new ArrayList<>();
        Long materialAmount = 0L;
        Long originalMaterAmount = 0L;
        String materialSubName = cartGoods.getSubName();
        for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.MaterialGoods materialGoods : cartGoods.getProductMaterialList()) {
            ProductBeanDTO.ProductGroupType.GroupDetailType detail = materialHash.get(materialGoods.getSpuId());
            if (detail == null) continue;
            com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.MaterialGoods material = new com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.MaterialGoods();
            material.setSpuName(detail.getProductName());
            material.setSpuId(detail.getProductId());
            //行单价 \ 行总价
            material.setFinalPrice(detail.getProductFinalPrice().longValue());
            material.setAmount(detail.getProductFinalPrice().longValue() * cartGoods.getQty());
            //原行单价*数量
            material.setOriginalAmount(detail.getProductFinalPrice().longValue() * cartGoods.getQty());
            material.setOriginalPrice(detail.getProductFinalPrice().longValue());
            material.setKeyWord(materialGoods.getKeyWord());
            materialGoodsList.add(material);
            materialAmount += detail.getProductFinalPrice().longValue() * cartGoods.getQty();
            originalMaterAmount += detail.getProductFinalPrice().longValue() * cartGoods.getQty();
            ;
            materialSubName = materialSubName + "/" + detail.getProductName();
        }
        //设置购物车行记录
        cartGoods.setProductMaterialList(materialGoodsList);
        //加料行记录现价总价
        cartGoods.setMaterialAmount(materialAmount);
        //加料行记录原价总价
        cartGoods.setOriginalMaterialAmount(originalMaterAmount);
    }


    public void updateCartGoodsInfo(com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods cartGoods, ProductBeanDTO spuProduct,Map<String,ProductBeanDTO> subProductTypeMap) {
        try {
            //是否是sku商品
            boolean isSkuProduct = ObjectUtils.equals(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.SKU_GOODS.getGoodsType(), cartGoods.getGoodsType())
                                        || !ObjectUtils.equals(cartGoods.getSpuId(),cartGoods.getSkuId());
            // 如果是套餐商品，更新套餐内固定商品&可选商品的详细信息
            boolean isSetMealProduct = ObjectUtils.equals(com.freemud.sdk.api.assortment.shoppingcart.constant.ProductType.SetMeal.getCode(), spuProduct.getType()) || ObjectUtils.equals(com.freemud.sdk.api.assortment.shoppingcart.constant.ProductType.IncreasedPackage.getCode(), spuProduct.getType());
            ProductBeanDTO.SkuProductBean skuProduct = isSkuProduct ? spuProduct.getSkuList().stream().filter(p -> ObjectUtils.equals(cartGoods.getSkuId(), p.getSkuId())).findFirst().get() : null;

            Map<String, String> attributes = getAttributesNew(cartGoods.getExtra());
            if(!"早餐啡常搭".equals(cartGoods.getName()) && !"早餐啡常搭".equals(cartGoods.getSkuName()) && !"早餐啡常搭".equals(cartGoods.getSpuName())
                    && !"啡常搭".equals(cartGoods.getName()) && !"啡常搭".equals(cartGoods.getSkuName()) && !"啡常搭".equals(cartGoods.getSpuName())) {
                cartGoods.setName(spuProduct.getName());
                cartGoods.setSpuName(spuProduct.getName());
                cartGoods.setSkuName(isSkuProduct ? skuProduct.getProductName() : spuProduct.getName());
            }
            cartGoods.setSpecProductId(attributes.get(ATTRIBUTEID));
            cartGoods.setPic(spuProduct.getPicture());
            cartGoods.setPackPrice(isSkuProduct ? skuProduct.getPackPrice() : spuProduct.getPackPrice());
            cartGoods.setStockLimit(isSkuProduct ? ObjectUtils.equals(1, skuProduct.getStockLimit()) : ObjectUtils.equals(1, spuProduct.getStockLimit()));
            cartGoods.setCustomerCode(isSkuProduct ? skuProduct.getCustomerCode() : spuProduct.getCustomerCode());
            cartGoods.setRiseSell(isSkuProduct ? skuProduct.getRiseSell() : spuProduct.getRiseSell());
            cartGoods.setMemberDiscount(spuProduct.getMemberDiscountResult());
            cartGoods.setClassificationId(spuProduct.getCategory());
            cartGoods.setClassificationName(spuProduct.getCategoryName());
            cartGoods.setTax(spuProduct.getTax());
            cartGoods.setTaxId(spuProduct.getTaxId());
            String skuSpecName = "";
            if (isSkuProduct && CollectionUtils.isNotEmpty(skuProduct.getSkuSpecValues())) {
                List<String> skuSpecValus = skuProduct.getSkuSpecValues().stream().map(p -> p.getSpecValue()).collect(Collectors.toList());
                skuSpecName = StringUtils.join(skuSpecValus, "/");
            }
            String attributeName = attributes.get(ATTRIBUTENAME) == null ? "" : attributes.get(ATTRIBUTENAME);
            //购物车小标题
            cartGoods.setSubName(StringUtils.isNotEmpty(skuSpecName) && StringUtils.isNotEmpty(attributeName) ?
                    skuSpecName + "/" + attributeName : skuSpecName + attributeName);
            if (isSetMealProduct) {
                //套餐固定商品
                if (CollectionUtils.isNotEmpty(cartGoods.getProductComboList())) {
                    for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods productCombo : cartGoods.getProductComboList()){
                        //套餐子商品多规格商品
                        if(productCombo.getSpuId() != null && !productCombo.getSkuId().equals(productCombo.getSpuId()) ){
                            ProductBeanDTO productBeanDTO = subProductTypeMap.get(productCombo.getSpuId());
                            updateComboxGoodsInfoFor(productCombo, productBeanDTO, true);
                        }else {
                            //套餐子商品为单品
                            updateComboxGoodsInfoForMCoffee(productCombo, spuProduct, true);
                        }
                    }
                }
                //套餐可选商品
                if (CollectionUtils.isNotEmpty(cartGoods.getProductGroupList())) {
                    for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods comboxGoods : cartGoods.getProductGroupList()){
                        //套餐子商品多规格商品
                        if(comboxGoods.getSpuId() != null && !comboxGoods.getSkuId().equals(comboxGoods.getSpuId()) ){
                            for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods productGroup : cartGoods.getProductGroupList()) {
                                updateComboxGoodsInfoForMCoffee(productGroup, spuProduct, false);
                            }
                        }else {
                            for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods productGroup : cartGoods.getProductGroupList()) {
                                updateComboxGoodsInfoForMCoffee(productGroup, spuProduct, false);
                            }
                        }
                    }
                }
            }
            //更新当前商品行价格
            Long newOrigOriginalPrice = 0L;
            if (isSetMealProduct) {
                Long comboxGoodsOriginalPrice = cartGoods.getProductComboList().stream().mapToLong(t -> t.getOriginalAmount()).sum();
                Long groupGoodsOriginalPrice = cartGoods.getProductGroupList().stream().mapToLong(t -> t.getOriginalAmount()).sum();
                Long comboxGoodsFinalPrice = cartGoods.getProductComboList().stream().mapToLong(t -> t.getFinalPrice()).sum();
                Long groupGoodsFinalPrice = cartGoods.getProductGroupList().stream().mapToLong(t -> t.getFinalPrice()).sum();
                cartGoods.setOriginalPrice(comboxGoodsOriginalPrice);
                cartGoods.setOriginalAmount((comboxGoodsOriginalPrice+groupGoodsOriginalPrice)* cartGoods.getQty());
                cartGoods.setAmount((comboxGoodsFinalPrice+groupGoodsFinalPrice) * cartGoods.getQty());
                //咨询商品服务，套餐售价取originalPrice
                cartGoods.setFinalPrice(comboxGoodsFinalPrice);
            } else {
                newOrigOriginalPrice = isSkuProduct ? skuProduct.getFinalPrice() : spuProduct.getFinalPrice();
                cartGoods.setOriginalPrice(newOrigOriginalPrice);
                cartGoods.setOriginalAmount(newOrigOriginalPrice * cartGoods.getQty());
                cartGoods.setAmount(newOrigOriginalPrice * cartGoods.getQty());
                //咨询商品服务，套餐售价取originalPrice
                cartGoods.setFinalPrice(isSkuProduct ? skuProduct.getFinalPrice() : spuProduct.getFinalPrice());
            }
            cartGoods.setWeight(isSkuProduct ? skuProduct.getWeight() : spuProduct.getWeight());
            cartGoods.setUnit(isSkuProduct ? skuProduct.getUnit() : spuProduct.getUnit());
            cartGoods.setWeightType(CommonsConstant.WEIGHT_PRODUCT.equals(spuProduct.getWeightType()));
            cartGoods.setMaterialAmount(0L);
            cartGoods.setOriginalMaterialAmount(0L);
            // todo 设置加料
            this.checkMaterialProductForMCoffee(cartGoods, spuProduct);

        } catch (Exception ex) {
            ErrorLog.infoConvertJson(this.getClass(), "updateCartGoodsInfoForMCoffee_Error", ex);
            cartGoods.setCartGoodsUid(null);
        }
    }


    private void updateComboxGoodsInfoFor(com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods comboxGoods, ProductBeanDTO productBeanDTO, boolean isComboxGoods) {
        if(CollectionUtils.isEmpty(productBeanDTO.getSkuList())){
             return;
        }
        ProductBeanDTO.SkuProductBean comboxGoodsSkuProductBean = null;
        for (ProductBeanDTO.SkuProductBean skuProductBean : productBeanDTO.getSkuList()){
            if(comboxGoods.getSkuId().equals(skuProductBean.getSkuId())){
                comboxGoodsSkuProductBean = skuProductBean;
                break;
            }
        }
        if(comboxGoodsSkuProductBean == null){
            return;
        }
        // 若是固定商品则取商品详情的FinalPrice，若是可选商品则取MarkUpPrice
        Long finalPrice = comboxGoodsSkuProductBean.getFinalPrice();
        // 设置商品详情
        Map<String, String> attributes = getAttributesNew(comboxGoods.getExtra());
        comboxGoods.setName(comboxGoodsSkuProductBean.getProductName());
        comboxGoods.setSpuName(productBeanDTO.getName());
        comboxGoods.setSkuName(comboxGoodsSkuProductBean.getProductName());
        comboxGoods.setSpecProductId(attributes.get(ATTRIBUTEID));
        comboxGoods.setSubName(attributes.get(ATTRIBUTENAME));
        comboxGoods.setPic(productBeanDTO.getPicture());
        comboxGoods.setOriginalPrice(comboxGoodsSkuProductBean.getOriginalPrice());
        comboxGoods.setOriginalAmount(comboxGoods.getOriginalPrice() * comboxGoods.getQty());
        comboxGoods.setAmount(finalPrice * comboxGoods.getQty());
        comboxGoods.setCustomerCode(comboxGoodsSkuProductBean.getCustomerCode());
        comboxGoods.setFinalPrice(finalPrice);
        comboxGoods.setWeightType(CommonsConstant.WEIGHT_PRODUCT.equals(productBeanDTO.getWeightType()));
        comboxGoods.setUnit(comboxGoodsSkuProductBean.getUnit());
        comboxGoods.setWeight(comboxGoodsSkuProductBean.getWeight());
        comboxGoods.setTax(comboxGoodsSkuProductBean.getTax());
        comboxGoods.setTaxId(comboxGoodsSkuProductBean.getTaxId());
        //套餐内商品加料
        if(CollectionUtils.isNotEmpty(comboxGoods.getProductMaterialList())){
            if (CollectionUtils.isNotEmpty(productBeanDTO.getAdditionalGroupList())) {
                List<ProductBeanDTO.ProductGroupType.GroupDetailType> groupDetail = new ArrayList<>();
                for (ProductBeanDTO.ProductGroupType productGroupType : productBeanDTO.getAdditionalGroupList()){
                    groupDetail.addAll(productGroupType.getGroupDetail());
                }
                for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.MaterialGoods productMaterial :comboxGoods.getProductMaterialList()){
                    for (ProductBeanDTO.ProductGroupType.GroupDetailType groupDetailType : groupDetail){
                        if(groupDetailType.getProductId().equals(productMaterial.getSpuId())){
                            productMaterial.setSpuId(groupDetailType.getProductId());
                            productMaterial.setAmount(groupDetailType.getProductPrice().longValue());
                            productMaterial.setFinalPrice(groupDetailType.getProductFinalPrice().longValue());
                            productMaterial.setOriginalAmount(groupDetailType.getProductPrice().longValue());
                            productMaterial.setOriginalPrice(groupDetailType.getProductPrice().longValue());
                            productMaterial.setSpuName(groupDetailType.getProductName());
                            productMaterial.setKeyWord(productMaterial.getKeyWord());
                        }
                    }
                }
            }
        }
    }

}