/**
 * 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.GetMenuResponseDto;
import cn.freemud.entities.dto.activity.ActivityDiscountsDto;
import cn.freemud.entities.dto.calculate.ActivityCalculationDiscountResponseDto;
import cn.freemud.entities.dto.openplatform.WeixinProductRequestDto;
import cn.freemud.entities.dto.product.*;
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.alibaba.fastjson.JSON;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

@Component
public class ShoppingCartConvertAdapter {

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

    @Value("${mccafe.tableware.skuId}")
    private String mcCafeTablewareSkuId;

    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);
        // fisherman 加价购商品类型设置
        cartGoodsDetailDto.setOriginalProductType(getProductsVo.getType());
        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.setOriginalGoodsUid(cartGoods.getOriginalGoodsUid());
        cartGoodsDetailDto.setOriginalProductType(cartGoods.getOriginalProductType());
        cartGoodsDetailDto.setIsSendGoods((cartGoods.getIsSendGoods() !=null && cartGoods.getIsSendGoods()) ? true : false );
        cartGoodsDetailDto.setTaxId(cartGoods.getTaxId());
        cartGoodsDetailDto.setTax(cartGoods.getTax());
        cartGoodsDetailDto.setSpuId(cartGoods.getSpuId());
        cartGoodsDetailDto.setSpuName(cartGoods.getSpuName());
        cartGoodsDetailDto.setSpuForeignName(cartGoods.getSpuForeignName());
        cartGoodsDetailDto.setSkuId(StringUtils.isEmpty(cartGoods.getSkuId()) ? cartGoods.getSpuId() : cartGoods.getSkuId());
        cartGoodsDetailDto.setSkuName(StringUtils.isEmpty(cartGoods.getSkuName()) ? cartGoods.getSpuName() : cartGoods.getSkuName());
        cartGoodsDetailDto.setSkuForeignName(StringUtils.isEmpty(cartGoods.getSkuForeignName()) ? cartGoods.getSpuForeignName() : cartGoods.getSkuForeignName());
        cartGoodsDetailDto.setOriginalPrice(cartGoods.getOriginalPrice());
//        cartGoodsDetailDto.setTotalDiscountAmount(0);
        cartGoodsDetailDto.setUserId(cartGoods.getUserId());
        cartGoodsDetailDto.setOpenId(cartGoods.getOpenId());
        cartGoodsDetailDto.setUserName(cartGoods.getUserName());
        cartGoodsDetailDto.setPhotoUrl(cartGoods.getPhotoUrl());
        cartGoodsDetailDto.setPackPrice(cartGoods.getPackPrice());
        cartGoodsDetailDto.setSalePrice(cartGoods.getOriginalPrice());
        cartGoodsDetailDto.setScore(cartGoods.getScore());
        cartGoodsDetailDto.setPicture(cartGoods.getPic());
        cartGoodsDetailDto.setQty(cartGoods.getQty());
        cartGoodsDetailDto.setActivityType(cartGoods.getActivityType());
        cartGoodsDetailDto.setNodeId(cartGoods.getNodeId());
        cartGoodsDetailDto.setCategoryName(cartGoods.getCategoryName());
        cartGoodsDetailDto.setCustomerCategoryCode(cartGoods.getCustomerCategoryCode());
        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(mcCafeTablewareSkuId.equals(cartGoods.getSkuId())) {
            cartGoodsDetailDto.setIsTableware(1);
        }
        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.setSpuForeignName(materialGoods.getSpuForeignName());
                goods.setOriginalPrice(materialGoods.getOriginalPrice());
                goods.setSalePrice(materialGoods.getFinalPrice());
                goods.setCustomerCode(materialGoods.getCustomerCode());
                goods.setProductCode(materialGoods.getCustomerCode());
                goods.setQty(materialGoods.getQty());
                goods.setTotalDiscountAmount(0);
                goods.setOriginalProductType(materialGoods.getOriginalProductType());
                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.getSpuId());
            cartGoodsDetailDto.setSpuName(comboxGoods.getSpuName());
            cartGoodsDetailDto.setSkuId(comboxGoods.getGoodsId());
            // 设置原始商品价格
            cartGoodsDetailDto.setOriginalProductType(comboxGoods.getOriginalProductType());
            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(null != materialGoods.getOriginalPrice() ? materialGoods.getOriginalPrice() : 0);
                    goods.setSalePrice(materialGoods.getFinalPrice());
                    goods.setQty(cartGoods.getQty());
                    goods.setTotalDiscountAmount(0);
                    goods.setProductCode(materialGoods.getCustomerCode());
                    goods.setCustomerCode(materialGoods.getCustomerCode());
                    goods.setOriginalProductType(materialGoods.getOriginalProductType());
                    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(cartGood.getOriginalPrice());
        cartGoods.setPackPrice(cartGood.getPackPrice());
        cartGoods.setOriginalAmount(cartGood.getOriginalPrice());
        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());
        cartGoods.setClassificationId(cartGood.getClassificationId());
        cartGoods.setClassificationName(cartGood.getClassificationName());
        cartGoods.setActivityType(ActivityTypeEnum.TYPE_61.getCode());
        cartGoods.setUserId(cartGood.getUserId());
        cartGoods.setUserName(cartGood.getUserName());
        cartGoods.setOpenId(cartGood.getOpenId());
        cartGoods.setPhotoUrl(cartGood.getPhotoUrl());
        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.setAddCartTime(System.currentTimeMillis());
        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) || StringUtils.isNotBlank(addShoppingCartGoodsRequestVo.getCouponCode())) {
            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());
        cartGoods.setCustomerCategoryCode(addShoppingCartGoodsRequestVo.getCustomerCategoryCode());
        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());
                materialGoods.setQty(materialRequestVo.getQty() == null ? 1 : materialRequestVo.getQty());
                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<>());
        validateShopProductRequest.setSessionId(checkCartRequest.getSessionId());
        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());
            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)) {
            Map<String, ValidateSkuProductType> map = new HashMap<>();
            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());
                ValidateSkuProductType validateSkuProductTypeExists = map.get(validateSkuProductType.toString());
                if(validateSkuProductTypeExists == null) {
                    result.add(validateSkuProductType);
                    map.put(validateSkuProductType.toString(), validateSkuProductType);
                } else {
                    validateSkuProductTypeExists.setQty(validateSkuProductTypeExists.getQty()+validateSkuProductType.getQty());
                }
            }
        }
        return result;
    }


    /**
     * 更新当前购物车商品行信息
     *
     * @param cartGoods    当前购物车商品行
     * @param productBeans 购物车中所有的productId对应的商品详情
     */
    public void updateCartGoodsInfoForMCoffee(com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods cartGoods, List<ProductTypeBeanDTO> productBeans) {
        try {
            Optional<ProductTypeBeanDTO> firstProduct = productBeans.stream().filter(p -> ObjectUtils.equals(p.getPid(), cartGoods.getSpuId())).findFirst();
            if (!firstProduct.isPresent()) {
                return;
            }
            ProductTypeBeanDTO 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());
            ProductTypeBeanDTO.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) {
                if (null != cartGoods.getOriginalPrice() && cartGoods.getOriginalPrice()>0){
                    newOrigOriginalPrice += cartGoods.getOriginalPrice();
                }else {
                    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, ProductTypeBeanDTO parentProductBean, boolean isComboxGoods) {
        if("0".equals(comboxGoods.getGoodsId())){
            return;
        }
        ProductTypeBeanDTO.ProductComboType productComboType = new ProductTypeBeanDTO.ProductComboType();
        ProductTypeBeanDTO.ProductGroupType.GroupDetailType groupDetailType = new ProductTypeBeanDTO.ProductGroupType.GroupDetailType();
        if (isComboxGoods) {
            productComboType = parentProductBean.getProductComboList().stream().filter(p -> ObjectUtils.equals(comboxGoods.getGoodsId(), p.getProductId())).findFirst().orElse(new ProductTypeBeanDTO.ProductComboType());
        } else {
            Map<String, ProductTypeBeanDTO.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 ? (null != productComboType.getFinalPrice() ? productComboType.getFinalPrice().longValue() : 0L)
                : (null != groupDetailType.getMarkUpPrice() ? groupDetailType.getMarkUpPrice().longValue() : 0L);
        // 设置商品详情
        Map<String, String> attributes = getAttributesNew(comboxGoods.getExtra());
        comboxGoods.setSpuId(comboxGoods.getSpuId());
        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 ? (null != productComboType.getFinalPrice() ? productComboType.getFinalPrice().longValue() : 0L)
                : (null != groupDetailType.getProductFinalPrice() ? groupDetailType.getProductFinalPrice().longValue() : 0L));
        comboxGoods.setOriginalAmount(comboxGoods.getOriginalPrice() * comboxGoods.getQty());
        comboxGoods.setAmount(finalPrice * comboxGoods.getQty());
        comboxGoods.setCustomerCode(isComboxGoods ? (StringUtils.isNotEmpty(productComboType.getCustomerCode()) ? productComboType.getCustomerCode() : "")
                : (StringUtils.isNotEmpty(groupDetailType.getCustomerCode()) ? groupDetailType.getCustomerCode() : ""));
        comboxGoods.setFinalPrice(finalPrice);
        comboxGoods.setWeightType(isComboxGoods ? CommonsConstant.WEIGHT_PRODUCT.equals(productComboType.getWeightType()) : CommonsConstant.WEIGHT_PRODUCT.equals(groupDetailType.getWeightType()));
        comboxGoods.setUnit(isComboxGoods ? (StringUtils.isNotEmpty(productComboType.getUnit()) ? productComboType.getUnit() :"") :
                (StringUtils.isNotEmpty(groupDetailType.getUnit()) ? groupDetailType.getUnit() : ""));
        comboxGoods.setWeight(isComboxGoods ? (null == productComboType.getWeight() ? 0 : productComboType.getWeight()) :
                (null == groupDetailType.getWeight() ? 0:groupDetailType.getWeight()));
        comboxGoods.setTax(isComboxGoods ? (null == productComboType.getTax() ? 0 : productComboType.getTax())
                : (null == groupDetailType.getTax() ? 0 : groupDetailType.getTax()));
        comboxGoods.setTaxId(isComboxGoods ? (StringUtils.isNotEmpty(productComboType.getTaxId()) ? productComboType.getTaxId() : "") :
                (StringUtils.isNotEmpty(groupDetailType.getTaxId()) ? groupDetailType.getTaxId() : ""));

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

    /**
     * 更新套餐固定商品、可选商品信息
     *
     * @param comboxGoods       固定商品或可选商品
     * @param parentProductBean 套餐服商品
     * @param isComboxGoods     是否是固定商品
     * @return
     */
    private void updateComboxGoodsInfoForMCoffeeWithMaterial(com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods comboxGoods, ProductTypeBeanDTO parentProductBean, boolean isComboxGoods, ProductTypeBeanDTO productTypeBeanDTO) {
        if("0".equals(comboxGoods.getGoodsId())){
            return;
        }
        ProductTypeBeanDTO.ProductComboType productComboType = new ProductTypeBeanDTO.ProductComboType();
        ProductTypeBeanDTO.ProductGroupType.GroupDetailType groupDetailType = new ProductTypeBeanDTO.ProductGroupType.GroupDetailType();
        if (isComboxGoods) {
            productComboType = parentProductBean.getProductComboList().stream().filter(p -> ObjectUtils.equals(comboxGoods.getGoodsId(), p.getProductId())).findFirst().orElse(new ProductTypeBeanDTO.ProductComboType());
        } else {
            Map<String, ProductTypeBeanDTO.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 ? (null != productComboType.getFinalPrice() ? productComboType.getFinalPrice().longValue() : 0L)
                : (null != groupDetailType.getMarkUpPrice() ? groupDetailType.getMarkUpPrice().longValue() : 0L);
        // 设置商品详情
        Map<String, String> attributes = getAttributesNew(comboxGoods.getExtra());
        comboxGoods.setSpuId(comboxGoods.getSpuId());
        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 ? (null != productComboType.getFinalPrice() ? productComboType.getFinalPrice().longValue() : 0L)
                : (null != groupDetailType.getProductFinalPrice() ? groupDetailType.getProductFinalPrice().longValue() : 0L));
        comboxGoods.setOriginalAmount(comboxGoods.getOriginalPrice() * comboxGoods.getQty());
        comboxGoods.setAmount(finalPrice * comboxGoods.getQty());
        comboxGoods.setCustomerCode(isComboxGoods ? (StringUtils.isNotEmpty(productComboType.getCustomerCode()) ? productComboType.getCustomerCode() : "")
                : (StringUtils.isNotEmpty(groupDetailType.getCustomerCode()) ? groupDetailType.getCustomerCode() : ""));
        comboxGoods.setFinalPrice(finalPrice);
        comboxGoods.setWeightType(isComboxGoods ? CommonsConstant.WEIGHT_PRODUCT.equals(productComboType.getWeightType()) : CommonsConstant.WEIGHT_PRODUCT.equals(groupDetailType.getWeightType()));
        comboxGoods.setUnit(isComboxGoods ? (StringUtils.isNotEmpty(productComboType.getUnit()) ? productComboType.getUnit() :"") :
                (StringUtils.isNotEmpty(groupDetailType.getUnit()) ? groupDetailType.getUnit() : ""));
        comboxGoods.setWeight(isComboxGoods ? (null == productComboType.getWeight() ? 0 : productComboType.getWeight()) :
                (null == groupDetailType.getWeight() ? 0:groupDetailType.getWeight()));
        comboxGoods.setTax(isComboxGoods ? (null == productComboType.getTax() ? 0 : productComboType.getTax())
                : (null == groupDetailType.getTax() ? 0 : groupDetailType.getTax()));
        comboxGoods.setTaxId(isComboxGoods ? (StringUtils.isNotEmpty(productComboType.getTaxId()) ? productComboType.getTaxId() : "") :
                (StringUtils.isNotEmpty(groupDetailType.getTaxId()) ? groupDetailType.getTaxId() : ""));

        //2020/10/22  套餐内可选商品加料，暂无
        if(CollectionUtils.isNotEmpty(comboxGoods.getProductMaterialList())){
            if(CollectionUtils.isNotEmpty(productTypeBeanDTO.getAdditionalGroupList())) {
                List<ProductTypeBeanDTO.ProductGroupType> productGroupTypes = productTypeBeanDTO.getAdditionalGroupList();
                Map<String, List<ProductTypeBeanDTO.ProductGroupType.GroupDetailType>> productGroupTypeMap = productGroupTypes.stream().collect(
                        Collectors.toMap(ProductTypeBeanDTO.ProductGroupType::getGroupCode,
                                ProductTypeBeanDTO.ProductGroupType::getGroupDetail,
                                (k1,k2) -> k1));
                comboxGoods.getProductMaterialList().stream().forEach(o -> {
                    List<ProductTypeBeanDTO.ProductGroupType.GroupDetailType> list = productGroupTypeMap.get(o.getCustomerCode().split("_")[0]);
                    for(ProductTypeBeanDTO.ProductGroupType.GroupDetailType groupDetailType1 : list) {
                        if (groupDetailType1.getProductId().equals(o.getSpuId())) {
                            o.setAmount(groupDetailType1.getProductFinalPrice().longValue());
                            o.setFinalPrice(groupDetailType1.getProductFinalPrice().longValue());
                            o.setOriginalAmount(groupDetailType1.getProductFinalPrice().longValue());
                            o.setOriginalPrice(groupDetailType1.getProductFinalPrice().longValue());
                            o.setSpuName(groupDetailType1.getProductName());
                            break;
                        }
                    }
                });
            } else {
                comboxGoods.setProductMaterialList(new ArrayList<>());
            }
        }
    }


    /**
     * 更新套餐可选商品加料信息
     */
    private void updateComboxGoodsInfoForMCoffeeProductGroup(com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods comboxGoods, ProductTypeBeanDTO parentProductBean,
                                                             Map<String,ProductTypeBeanDTO> subProductTypeMap,
                                                             boolean isComboxGoods) {
        if("0".equals(comboxGoods.getGoodsId())){
            return;
        }
        ProductTypeBeanDTO.ProductComboType productComboType = new ProductTypeBeanDTO.ProductComboType();
        ProductTypeBeanDTO.ProductGroupType.GroupDetailType groupDetailType = new ProductTypeBeanDTO.ProductGroupType.GroupDetailType();
        if (isComboxGoods) {
            productComboType = parentProductBean.getProductComboList().stream().filter(p -> ObjectUtils.equals(comboxGoods.getGoodsId(), p.getProductId())).findFirst().orElse(new ProductTypeBeanDTO.ProductComboType());
        } else {
            Map<String, ProductTypeBeanDTO.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 ? (null != productComboType.getFinalPrice() ? productComboType.getFinalPrice().longValue() : 0L)
                : (null != groupDetailType.getMarkUpPrice() ? groupDetailType.getMarkUpPrice().longValue() : 0L);
        // 设置商品详情
        Map<String, String> attributes = getAttributesNew(comboxGoods.getExtra());
        comboxGoods.setSpuId(comboxGoods.getSpuId());
        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 ? (null != productComboType.getFinalPrice() ? productComboType.getFinalPrice().longValue() : 0L)
                : (null != groupDetailType.getProductFinalPrice() ? groupDetailType.getProductFinalPrice().longValue() : 0L));
        comboxGoods.setOriginalAmount(comboxGoods.getOriginalPrice() * comboxGoods.getQty());
        comboxGoods.setAmount(finalPrice * comboxGoods.getQty());
        comboxGoods.setCustomerCode(isComboxGoods ? (StringUtils.isNotEmpty(productComboType.getCustomerCode()) ? productComboType.getCustomerCode() : "")
                : (StringUtils.isNotEmpty(groupDetailType.getCustomerCode()) ? groupDetailType.getCustomerCode() : ""));
        comboxGoods.setFinalPrice(finalPrice);
        comboxGoods.setWeightType(isComboxGoods ? CommonsConstant.WEIGHT_PRODUCT.equals(productComboType.getWeightType()) : CommonsConstant.WEIGHT_PRODUCT.equals(groupDetailType.getWeightType()));
        comboxGoods.setUnit(isComboxGoods ? (StringUtils.isNotEmpty(productComboType.getUnit()) ? productComboType.getUnit() :"") :
                (StringUtils.isNotEmpty(groupDetailType.getUnit()) ? groupDetailType.getUnit() : ""));
        comboxGoods.setWeight(isComboxGoods ? (null == productComboType.getWeight() ? 0 : productComboType.getWeight()) :
                (null == groupDetailType.getWeight() ? 0:groupDetailType.getWeight()));
        comboxGoods.setTax(isComboxGoods ? (null == productComboType.getTax() ? 0 : productComboType.getTax())
                : (null == groupDetailType.getTax() ? 0 : groupDetailType.getTax()));
        comboxGoods.setTaxId(isComboxGoods ? (StringUtils.isNotEmpty(productComboType.getTaxId()) ? productComboType.getTaxId() : "") :
                (StringUtils.isNotEmpty(groupDetailType.getTaxId()) ? groupDetailType.getTaxId() : ""));

        //2020/10/22  套餐内可选商品加料，暂无
        if(CollectionUtils.isNotEmpty(comboxGoods.getProductMaterialList())){
            Map<String, ProductTypeBeanDTO.ProductGroupType.GroupDetailType> materialMap = new HashMap<>();
            subProductTypeMap.get(comboxGoods.getSkuId()).getAdditionalGroupList().stream().map(t->t.getGroupDetail()).forEach(group->group.forEach(detailType-> materialMap.put(detailType.getProductId(),detailType)));

            List<ProductTypeBeanDTO.ProductGroupType.GroupDetailType> materialList = new ArrayList<>();
            comboxGoods.getProductMaterialList().stream().forEach(materialGood -> materialList.add(materialMap.get(materialGood.getSpuId())));

            List<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.MaterialGoods> productMaterialList = new ArrayList<>();
            Long materialAmount = 0L;
            if (CollectionUtils.isNotEmpty(materialList)){
                for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.MaterialGoods productMaterial :comboxGoods.getProductMaterialList()) {
                    for (ProductTypeBeanDTO.ProductGroupType.GroupDetailType detailType : materialList) {
//                        productMaterial.setCustomerCode(StringUtils.isNotEmpty(detailType.getCustomerCode()) ? detailType.getCustomerCode() : "");
                        if (Objects.equals(detailType.getProductId(),productMaterial.getSpuId())) {
                            productMaterial.setAmount(null != detailType.getMarkUpPrice() ? detailType.getMarkUpPrice().longValue() : 0);
                            productMaterial.setFinalPrice(null != detailType.getProductFinalPrice() ? detailType.getProductFinalPrice().longValue() : 0);
                            productMaterial.setSpuName(StringUtils.isNotEmpty(detailType.getProductName()) ? detailType.getProductName() : "");
                            productMaterial.setSpuId(StringUtils.isNotEmpty(detailType.getProductId()) ? detailType.getProductId() : "");
                            productMaterial.setOriginalPrice(null != detailType.getProductFinalPrice() ? detailType.getProductFinalPrice().longValue() : 0);
                            productMaterial.setOriginalAmount(null != detailType.getProductFinalPrice() ? detailType.getProductFinalPrice().longValue() * comboxGoods.getQty() : 0);
                            productMaterialList.add(productMaterial);
                            materialAmount += detailType.getProductFinalPrice().longValue() * comboxGoods.getQty();
                        }
                    }
                }
            }
            comboxGoods.setMaterialAmount(materialAmount);
            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, ProductTypeBeanDTO spuProduct) {

        if (CollectionUtils.isEmpty(cartGoods.getProductMaterialList())) {
            return;
        }
        //加料信息为空
        if (CollectionUtils.isEmpty(spuProduct.getAdditionalGroupList())) {
            checkSkuMaterialProductForMccafe(cartGoods,spuProduct);
            return;
        }
        //提取加料信息
        List<String> materialSpu = new ArrayList<>();
        List<ProductTypeBeanDTO.ProductGroupType.GroupDetailType> groupDetail = new ArrayList<>();
        for (ProductTypeBeanDTO.ProductGroupType productGroupType : spuProduct.getAdditionalGroupList()){
            groupDetail.addAll(productGroupType.getGroupDetail());
        }
        HashMap<String, ProductTypeBeanDTO.ProductGroupType.GroupDetailType> materialHash = new HashMap<>();
        for (ProductTypeBeanDTO.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()) {
            ProductTypeBeanDTO.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.setCustomerCode(materialGoods.getCustomerCode());
            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, ProductTypeBeanDTO spuProduct,Map<String,ProductTypeBeanDTO> 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());
            ProductTypeBeanDTO.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()) ){
                            ProductTypeBeanDTO productBeanDTO = subProductTypeMap.get(productCombo.getSpuId());
                            updateComboxGoodsInfoFor(productCombo, productBeanDTO, true);
                        }else {
                            //套餐子商品为单品
                            updateComboxGoodsInfoForMCoffeeWithMaterial(productCombo, spuProduct, true, subProductTypeMap.get(productCombo.getGoodsId()));
                        }
                    }
                }
                //套餐可选商品
                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()) {
                                updateComboxGoodsInfoForMCoffeeProductGroup(productGroup,spuProduct,subProductTypeMap,false);
                            }
                        }
                    }
                }
            }
            //更新当前商品行价格
            Long newOrigOriginalPrice = 0L;
            if (isSetMealProduct) {
                cartGoods.setOriginalPrice(null != spuProduct.getOriginalPrice()? spuProduct.getOriginalPrice() : 0);
                cartGoods.setOriginalAmount(cartGoods.getOriginalPrice()* cartGoods.getQty());
                //咨询商品服务，套餐售价取originalPrice
                cartGoods.setFinalPrice(null != spuProduct.getFinalPrice() ? spuProduct.getFinalPrice() : 0);
                cartGoods.setAmount(cartGoods.getFinalPrice() * cartGoods.getQty());
            } 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()));
            // todo 设置加料
            this.checkMaterialProductForMCoffee(cartGoods, spuProduct);
        } catch (Exception ex) {
            ErrorLog.printErrorLog("updateCartGoodsInfoForMCoffee_Error","updateCartGoodsInfo",JSON.toJSONString(cartGoods),ex);
            cartGoods.setCartGoodsUid(null);
        }
    }


    private void updateComboxGoodsInfoFor(com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.ComboxGoods comboxGoods, ProductTypeBeanDTO productBeanDTO, boolean isComboxGoods) {
        if(CollectionUtils.isEmpty(productBeanDTO.getSkuList())){
             return;
        }
        ProductTypeBeanDTO.SkuProductBean comboxGoodsSkuProductBean = null;
        for (ProductTypeBeanDTO.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<ProductTypeBeanDTO.ProductGroupType.GroupDetailType> groupDetail = new ArrayList<>();
                for (ProductTypeBeanDTO.ProductGroupType productGroupType : productBeanDTO.getAdditionalGroupList()){
                    groupDetail.addAll(productGroupType.getGroupDetail());
                }
                for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.MaterialGoods productMaterial :comboxGoods.getProductMaterialList()){
                    for (ProductTypeBeanDTO.ProductGroupType.GroupDetailType groupDetailType : groupDetail){
                        if(groupDetailType.getProductId().equals(productMaterial.getSpuId())){
                            productMaterial.setSpuId(groupDetailType.getProductId());
                            productMaterial.setAmount(groupDetailType.getProductFinalPrice().longValue());
                            productMaterial.setFinalPrice(groupDetailType.getProductFinalPrice().longValue());
                            productMaterial.setOriginalAmount(groupDetailType.getProductFinalPrice().longValue());
                            productMaterial.setOriginalPrice(groupDetailType.getProductFinalPrice().longValue());
                            productMaterial.setSpuName(groupDetailType.getProductName());
                        }
                    }
                }
            }else {
                if(CollectionUtils.isNotEmpty(comboxGoodsSkuProductBean.getAdditionalGroupList())){
                    List<ProductTypeBeanDTO.ProductGroupType.GroupDetailType> groupDetail = new ArrayList<>();
                    for (ProductTypeBeanDTO.ProductGroupType productGroupType : comboxGoodsSkuProductBean.getAdditionalGroupList()){
                        groupDetail.addAll(productGroupType.getGroupDetail());
                    }
                    for (com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.MaterialGoods productMaterial :comboxGoods.getProductMaterialList()){
                        for (ProductTypeBeanDTO.ProductGroupType.GroupDetailType groupDetailType : groupDetail){
                            if(groupDetailType.getProductId().equals(productMaterial.getSpuId())){
                                productMaterial.setSpuId(groupDetailType.getProductId());
                                productMaterial.setAmount(groupDetailType.getProductFinalPrice().longValue());
                                productMaterial.setFinalPrice(groupDetailType.getProductFinalPrice().longValue());
                                productMaterial.setOriginalAmount(groupDetailType.getProductFinalPrice().longValue());
                                productMaterial.setOriginalPrice(groupDetailType.getProductFinalPrice().longValue());
                                productMaterial.setSpuName(groupDetailType.getProductName());
                            }
                        }
                    }
                }else {
                    //都不存在移除商品
                    comboxGoods.setProductMaterialList(new ArrayList<>());
                }
            }
        }
    }

    /**
     * 多规格商品下添加单规格作为子商品，校验子商品的加料信息
     * @param cartGoods
     * @param spuProduct
     */
    private void checkSkuMaterialProductForMccafe(com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods cartGoods,ProductTypeBeanDTO spuProduct) {
        if (CollectionUtils.isNotEmpty(spuProduct.getSkuList())) {
            spuProduct.getSkuList().stream().filter(sku-> sku.getSkuId().equals(cartGoods.getGoodsId())).collect(Collectors.toList()).forEach(
                    skuProductBean -> {
                        if (CollectionUtils.isNotEmpty(skuProductBean.getAdditionalGroupList())){
                            List<String> materialSpu = new ArrayList<>();
                            HashMap<String, ProductTypeBeanDTO.ProductGroupType.GroupDetailType> materialHash = new HashMap<>();
                            for (ProductTypeBeanDTO.ProductGroupType productGroupType : skuProductBean.getAdditionalGroupList()) {
                                //提取加料信息
                                List<ProductTypeBeanDTO.ProductGroupType.GroupDetailType> groupDetail = new ArrayList<>();
                                groupDetail.addAll(productGroupType.getGroupDetail());

                                for (ProductTypeBeanDTO.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()) {
                                ProductTypeBeanDTO.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.setCustomerCode(materialGoods.getCustomerCode());
                                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);

                        }else{
                            cartGoods.setGoodsType(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.EXCEPTION_GOODS.getGoodsType());
                            cartGoods.setProductMaterialList(new ArrayList<>());
                            return;
                        }
                    }
            );
        }
    }

}
