/**
 * 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.activity.ActivityDiscountsDto;
import cn.freemud.entities.dto.calculate.ApportionDetails;
import cn.freemud.entities.dto.calculate.ApportionGoods;
import cn.freemud.entities.dto.calculate.SendGoods;
import cn.freemud.entities.dto.openplatform.WeixinProductRequestDto;
import cn.freemud.entities.dto.product.*;
import cn.freemud.entities.dto.product.info.*;
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 cn.freemud.utils.LogUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.CartResponseConstant;
import com.freemud.sdk.api.assortment.shoppingcart.constant.CommonsConstant;
import com.freemud.sdk.api.assortment.shoppingcart.exception.ServiceException;
import com.freemud.sdk.api.assortment.shoppingcart.util.ShoppingSdkLogUtil;
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";
    private static final String ATTRIBUTEFOREIGNNAME = "attributeForeignName";

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

    public ShoppingCartGoodsDto.CartGoodsDetailDto getCartGoodsDetailDto(CreateOrderVo.PremiumExchangeActivity.Product product, GetProductsVo getProductsVo, String goodsId, 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.setLinkedId(getProductsVo.getLinkedId());
        cartGoodsDetailDto.setProductType(sendGoods.getProductType());
        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());
        cartGoodsDetailDto.setStockLimit(ObjectUtils.equals(1, getProductsVo.getStockLimit()));
        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<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<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.setLinkedId(cartGoods.getLinkedId());
        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.setCouponCode(cartGoods.getCouponCode());
        cartGoodsDetailDto.setStockLimit(cartGoods.isStockLimit());
        cartGoodsDetailDto.setStockMode(cartGoods.getStockMode());
        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.getProductComboList()) && GoodsTypeEnum.COUPON_GOODS.getGoodsType().equals(cartGoods.getGoodsType())) {
            cartGoodsDetailDto.setProductType(ProductType.SETMEAL.getCode());
            List<ShoppingCartGoodsDto.CartGoodsDetailDto> comboProducts = new ArrayList<>(0);

            for (CartGoods.ComboxGoods comboxGoods : cartGoods.getProductComboList()) {
                ShoppingCartGoodsDto.CartGoodsDetailDto comboProduct = new ShoppingCartGoodsDto.CartGoodsDetailDto();
                comboProduct.setTaxId(cartGoods.getTaxId());
                comboProduct.setTax(cartGoods.getTax());
                comboProduct.setSpuId(comboxGoods.getSpuId());
                comboProduct.setSpuName(comboxGoods.getSpuName());
                comboProduct.setSkuId(comboxGoods.getGoodsId());
                // fisherman 设置套餐商品 POS编码
                comboProduct.setLinkedId(comboxGoods.getLinkedId());
                // 设置原始商品类型
                comboProduct.setOriginalProductType(comboxGoods.getOriginalProductType());
                comboProduct.setSkuName(StringUtils.isEmpty(comboxGoods.getSkuName()) ? comboxGoods.getSpuName() : comboxGoods.getSkuName());
                comboProduct.setOriginalPrice(comboxGoods.getOriginalPrice());
                comboProduct.setPicture(comboxGoods.getPic());
                int qty = comboxGoods.getQty() * cartGoods.getQty();
                comboProduct.setQty(qty);
                comboProduct.setProductType(comboxGoods.isWeightType() ? ProductType.WEIGHT_PRODUCT.getCode() : ProductType.SETMEAL.getCode());
                comboProduct.setParentProductId(cartGoods.getGoodsId());
                comboProduct.setIsFixedProduct(true);
                comboProduct.setStockLimit(comboxGoods.isStockLimit());
                comboProduct.setCustomerCode(comboxGoods.getCustomerCode());
                comboProduct.setWeight(comboxGoods.getWeight());
                comboProduct.setUnit(comboxGoods.getUnit());
                List<ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra> cartGoodsExtras = BeanUtil.convertBeans(comboxGoods.getExtra(), ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra::new);
                comboProduct.setExtraList(cartGoodsExtras);
                comboProduct.setSpecialExtra(comboxGoods.getSpecialExtra());
                comboProducts.add(comboProduct);
            }
            cartGoodsDetailDto.setComboProducts(comboProducts);
        }
        //小料
        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<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<ApportionGoods> apportionGoodsList, ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto, Map<String, String> duplicateGoodsMap) {
        List<ActivityDiscountsDto> activityDiscountsDtoList = new ArrayList<>();
        int goodsTotalQty = apportionGoodsList.stream().mapToInt(apportionGoods -> apportionGoods.getGoodsQuantity()).sum();
        for (ApportionGoods apportionGoods : apportionGoodsList) {
            /**
             * 1. 商品券：cartGoodsDetailDto.couponCode非空，保留ApportionGoods#ApportionDetails#apportionType中32的
             * 2. 普通商品：cartGoodsDetailDto.couponCode空，去掉32的
             */
            List<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 (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<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 (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 (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.setLinkedId(comboxGoods.getLinkedId());
            // 设置原始商品价格
            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(comboxGoods.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<ProductAttributeGroupListBean> productAttributeGroupList = getProductsVo.getProductAttributeGroupList();
        if (productAttributeGroupList != null && productAttributeGroupList.size() > 0) {
            List<CartGoods.CartGoodsExtra> cartGoodsExtraList = new ArrayList<>();
            for (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());
        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<>());
        for (CartGoods cartGoods : checkCartRequest.getCartGoodsList()) {
            // 过滤非商品券商品
            if (cartGoods.getCartGoodsUid().startsWith(CommonsConstant.COUPON_PREFIX) || StringUtils.isNotBlank(cartGoods.getCouponCode())) {
                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());
            //fisherman 这里 商品服务校验需要商品原价, 不是购物车的 finalPrice
            productType.setPrice(cartGoods.getOriginalPrice() == null ? 0 : cartGoods.getOriginalPrice().intValue());
            if (Objects.equals(cartGoods.getGoodsType(), GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType())) {
                // 套餐会出现商品组的情况,会导致 商品服务校验失败,商品服务不需要商品组的价格  坑B  所以只能取 套餐商品原价格
                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<CartGoods.CartGoodsExtra> extra) {
        List<ProductAttributeValueType> attributeValueTypes = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(extra)) {
            for (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<CartGoods.ComboxGoods> productComboList) {
        List<ValidateSkuProductType> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(productComboList)) {
            Map<String, ValidateSkuProductType> map = new HashMap<>();
            for (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;
    }

    /**
     * 只维护 套餐券的 model 和 库存限制
     * @param cartGoods
     * @param productBeans
     */
    public void updateStockModelAndStockLimit(CartGoods cartGoods, List<ProductTypeBeanDTO> productBeans) {
        try {
//            LogUtil.info("fisherman 套餐券",JSON.toJSON(cartGoods),JSON.toJSONString(productBeans));
            Optional<ProductTypeBeanDTO> firstProduct = productBeans.stream().filter(p -> ObjectUtils.equals(p.getPid(), cartGoods.getSpuId())).findFirst();
            if (!firstProduct.isPresent()) {
                return;
            }
            ProductTypeBeanDTO spuProduct = firstProduct.get();
            boolean isSkuProduct = ObjectUtils.equals(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.SKU_GOODS.getGoodsType(), cartGoods.getGoodsType());
            SkuProductBean skuProduct = isSkuProduct ? spuProduct.getSkuList().stream().filter(p -> ObjectUtils.equals(cartGoods.getSkuId(), p.getSkuId())).findFirst().orElse(null): null;
            if(isSkuProduct && skuProduct == null){//特殊场景前端传一个skuid非spuid下多规格商品
                throw new ServiceException(CartResponseConstant.FAIL);
            }
            cartGoods.setStockLimit(isSkuProduct ? ObjectUtils.equals(1, skuProduct.getStockLimit()) : ObjectUtils.equals(1, spuProduct.getStockLimit()));
            cartGoods.setStockMode(spuProduct.getStockMode());
        } catch (Exception ex) {
            ShoppingSdkLogUtil.errorLog("updateCartGoodsInfoNew_Error cartGoods:{},productBeans:{}", ex, JSONObject.toJSONString(cartGoods), JSONObject.toJSONString(productBeans));
            cartGoods.setCartGoodsUid(null);
        }
    }

    /**
     * 更新当前购物车商品行信息
     *
     * @param cartGoods    当前购物车商品行
     * @param productBeans 购物车中所有的productId对应的商品详情
     */
    public void updateCartGoodsInfoNew(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();
            // fisherman 添加原有商品服务的商品类型 -> 后续只为存表B端使用, 暂无其他地方有逻辑判断 20210810
            cartGoods.setOriginalProductType(spuProduct.getType());
            //是否是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());
            SkuProductBean skuProduct = isSkuProduct ? spuProduct.getSkuList().stream().filter(p -> ObjectUtils.equals(cartGoods.getSkuId(), p.getSkuId())).findFirst().orElse(null): null;
            if(isSkuProduct && skuProduct == null){//特殊场景前端传一个skuid非spuid下多规格商品
                throw new ServiceException(CartResponseConstant.FAIL);
            }
            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.setForeignName(spuProduct.getForeignName());
                cartGoods.setSpuName(spuProduct.getName());
                cartGoods.setSpuForeignName(spuProduct.getForeignName());
                cartGoods.setSkuName(isSkuProduct ? skuProduct.getProductName() : spuProduct.getName());
                cartGoods.setSkuForeignName(isSkuProduct ? skuProduct.getForeignProductName() : spuProduct.getForeignName());

            }
            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.setStockMode(spuProduct.getStockMode());
            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.setClassificationForeignName(spuProduct.getCategoryName());

            cartGoods.setTax(spuProduct.getTax());
            cartGoods.setTaxId(spuProduct.getTaxId());
            // fisherman  订C，“POS编码”让凌顶那边去匹配商品  透传到订单上 保存到 orders_item 表的 extinfo里面
            cartGoods.setLinkedId(isSkuProduct ? skuProduct.getLinkedCode() : spuProduct.getLinkedId());
            cartGoods.setSingleOrder(spuProduct.getSingleOrder());
            String skuSpecName = "";
            String skuForeignSpecName = "";
            if (isSkuProduct && CollectionUtils.isNotEmpty(skuProduct.getSkuSpecValues())) {
                List<String> skuSpecValus = skuProduct.getSkuSpecValues().stream().map(p -> p.getSpecValue()).collect(Collectors.toList());
                skuSpecName = StringUtils.join(skuSpecValus, "/");
            }
            if (isSkuProduct && CollectionUtils.isNotEmpty(skuProduct.getSkuSpecValues())) {
                List<String> skuSpecValus = skuProduct.getSkuSpecValues().stream().map(p -> p.getForeignSpecValue()).collect(Collectors.toList());
                skuForeignSpecName = StringUtils.join(skuSpecValus, "/");
            }
            String attributeName = attributes.get(ATTRIBUTENAME) == null ? "" : attributes.get(ATTRIBUTENAME);
            String attributeForeignName = attributes.get(ATTRIBUTEFOREIGNNAME) == null ? "" : attributes.get(ATTRIBUTEFOREIGNNAME);
            //购物车小标题
            cartGoods.setSubName(StringUtils.isNotEmpty(skuSpecName) && StringUtils.isNotEmpty(attributeName) ?
                    skuSpecName + "/" + attributeName : skuSpecName + attributeName);
            //购物车英文小标题
            cartGoods.setSubForeignName(StringUtils.isNotEmpty(skuForeignSpecName) && StringUtils.isNotEmpty(attributeForeignName) ?
                    skuForeignSpecName + "/" + attributeForeignName : skuForeignSpecName + attributeForeignName);


            if (isSetMealProduct) {
                if (CollectionUtils.isNotEmpty(cartGoods.getProductComboList())) {
                    for (CartGoods.ComboxGoods productCombo : cartGoods.getProductComboList()) {
                        updateComboxGoodsInfoNew(productCombo, spuProduct, true);
                    }
                }
                if (CollectionUtils.isNotEmpty(cartGoods.getProductGroupList())) {
                    for (CartGoods.ComboxGoods productGroup : cartGoods.getProductGroupList()) {
                        updateComboxGoodsInfoNew(productGroup, spuProduct, false);
                    }
                }
                cartGoods.setGoodsType(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType());
            }
            //更新当前商品行价格
            Long newOrigOriginalPrice = 0L;
            if (isSetMealProduct) {
                newOrigOriginalPrice += cartGoods.getProductComboList().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.checkMaterialProduct(cartGoods, spuProduct);

        } catch (Exception ex) {
            ShoppingSdkLogUtil.errorLog( "updateCartGoodsInfoNew_Error cartGoods:{},productBeans:{}", ex, JSONObject.toJSONString(cartGoods),JSONObject.toJSONString(productBeans));
            cartGoods.setCartGoodsUid(null);
        }
    }



    /**
     * 更新当前购物车商品行信息
     *
     * @param cartGoods    当前购物车商品行
     * @param productBeans 购物车中所有的productId对应的商品详情
     */
    public void updateCartGoodsInfoForMCoffee(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());
            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 (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 (CartGoods.ComboxGoods comboxGoods : cartGoods.getProductComboList()){
                        //套餐子商品多规格商品
                        if(comboxGoods.getSpuId() == null && !comboxGoods.getSkuId().equals(comboxGoods.getSpuId()) ){
                            for (CartGoods.ComboxGoods productGroup : cartGoods.getProductGroupList()) {
                                updateComboxGoodsInfoForMCoffee(productGroup, spuProduct, false);
                            }
                        }else {
                            for (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);
            ErrorLog.errorConvertJson(this.getClass(),"updateCartGoodsInfoForMCoffee_Error", ex);
            cartGoods.setCartGoodsUid(null);
        }
    }

    /**
     * 更新套餐固定商品、可选商品信息
     *
     * @param comboxGoods       固定商品或可选商品
     * @param parentProductBean 套餐服商品
     * @param isComboxGoods     是否是固定商品
     * @return
     */
    private void updateComboxGoodsInfoForMCoffee(CartGoods.ComboxGoods comboxGoods, ProductTypeBeanDTO parentProductBean, boolean isComboxGoods) {
        if("0".equals(comboxGoods.getGoodsId())){
            return;
        }
        ProductComboType productComboType = new ProductComboType();
        GroupDetailType groupDetailType = new GroupDetailType();
        if (isComboxGoods) {
            productComboType = parentProductBean.getProductComboList().stream().filter(p -> ObjectUtils.equals(comboxGoods.getGoodsId(), p.getProductId())).findFirst().orElse(new ProductComboType());
        } else {
            Map<String, 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<CartGoods.MaterialGoods> productMaterialList = new ArrayList<>();
            CartGoods.MaterialGoods materialGoods = new CartGoods.MaterialGoods();
            productMaterialList.add(materialGoods);
            comboxGoods.setProductMaterialList(productMaterialList);
        }
    }

    /**
     * 更新套餐固定商品、可选商品信息
     *
     * @param comboxGoods       固定商品或可选商品
     * @param parentProductBean 套餐服商品
     * @param isComboxGoods     是否是固定商品
     * @return
     */
    private void updateComboxGoodsInfoForMCoffeeWithMaterial(CartGoods.ComboxGoods comboxGoods, ProductTypeBeanDTO parentProductBean, boolean isComboxGoods, ProductTypeBeanDTO productTypeBeanDTO) {
        if("0".equals(comboxGoods.getGoodsId())){
            return;
        }
        ProductComboType productComboType = new ProductComboType();
        GroupDetailType groupDetailType = new GroupDetailType();
        if (isComboxGoods) {
            productComboType = parentProductBean.getProductComboList().stream().filter(p -> ObjectUtils.equals(comboxGoods.getGoodsId(), p.getProductId())).findFirst().orElse(new ProductComboType());
        } else {
            Map<String, 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<ProductGroupType> productGroupTypes = productTypeBeanDTO.getAdditionalGroupList();
                Map<String, List<GroupDetailType>> productGroupTypeMap = productGroupTypes.stream().collect(
                        Collectors.toMap(ProductGroupType::getGroupCode,ProductGroupType::getGroupDetail,(k1,k2) -> k1));
                comboxGoods.getProductMaterialList().stream().forEach(o -> {
                    List<GroupDetailType> list = productGroupTypeMap.get(o.getCustomerCode().split("_")[0]);
                    for(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(CartGoods.ComboxGoods comboxGoods, ProductTypeBeanDTO parentProductBean,
                                                             Map<String,ProductTypeBeanDTO> subProductTypeMap,
                                                             boolean isComboxGoods) {
        if("0".equals(comboxGoods.getGoodsId())){
            return;
        }
        ProductComboType productComboType = new ProductComboType();
        GroupDetailType groupDetailType = new GroupDetailType();
        if (isComboxGoods) {
            productComboType = parentProductBean.getProductComboList().stream().filter(p -> ObjectUtils.equals(comboxGoods.getGoodsId(), p.getProductId())).findFirst().orElse(new ProductComboType());
        } else {
            Map<String, 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, 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<GroupDetailType> materialList = new ArrayList<>();
            comboxGoods.getProductMaterialList().stream().forEach(materialGood -> materialList.add(materialMap.get(materialGood.getSpuId())));

            List<CartGoods.MaterialGoods> productMaterialList = new ArrayList<>();
            Long materialAmount = 0L;
            if (CollectionUtils.isNotEmpty(materialList)){
                for (CartGoods.MaterialGoods productMaterial :comboxGoods.getProductMaterialList()) {
                    for (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<CartGoods.CartGoodsExtra> extra) {
        if (CollectionUtils.isEmpty(extra)) {
            return new HashMap<>();
        }
        List<String> attributeIds = extra.stream().map(CartGoods.CartGoodsExtra::getAttributeId).collect(Collectors.toList());
        List<String> attributeNames = extra.stream().map(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(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<GroupDetailType> groupDetail = new ArrayList<>();
        for (ProductGroupType productGroupType : spuProduct.getAdditionalGroupList()){
            groupDetail.addAll(productGroupType.getGroupDetail());
        }
        HashMap<String, GroupDetailType> materialHash = new HashMap<>();
        for (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<CartGoods.MaterialGoods> materialGoodsList = new ArrayList<>();
        Long materialAmount = 0L;
        Long originalMaterAmount = 0L;
        String materialSubName = cartGoods.getSubName();
        for (CartGoods.MaterialGoods materialGoods : cartGoods.getProductMaterialList()) {
            GroupDetailType detail = materialHash.get(materialGoods.getSpuId());
            if (detail == null) {
                continue;
            }
            CartGoods.MaterialGoods material = new 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(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());
            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 (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 (CartGoods.ComboxGoods comboxGoods : cartGoods.getProductGroupList()){
                        //套餐子商品多规格商品
                        if(comboxGoods.getSpuId() != null && !comboxGoods.getSkuId().equals(comboxGoods.getSpuId()) ){
                            for (CartGoods.ComboxGoods productGroup : cartGoods.getProductGroupList()) {
                                updateComboxGoodsInfoForMCoffee(productGroup, spuProduct, false);
                            }
                        }else {
                            for (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(CartGoods.ComboxGoods comboxGoods, ProductTypeBeanDTO productBeanDTO, boolean isComboxGoods) {
        if(CollectionUtils.isEmpty(productBeanDTO.getSkuList())){
             return;
        }
        SkuProductBean comboxGoodsSkuProductBean = null;
        for (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<GroupDetailType> groupDetail = new ArrayList<>();
                for (ProductGroupType productGroupType : productBeanDTO.getAdditionalGroupList()){
                    groupDetail.addAll(productGroupType.getGroupDetail());
                }
                for (CartGoods.MaterialGoods productMaterial :comboxGoods.getProductMaterialList()){
                    for (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<GroupDetailType> groupDetail = new ArrayList<>();
                    for (ProductGroupType productGroupType : comboxGoodsSkuProductBean.getAdditionalGroupList()){
                        groupDetail.addAll(productGroupType.getGroupDetail());
                    }
                    for (CartGoods.MaterialGoods productMaterial :comboxGoods.getProductMaterialList()){
                        for (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(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, GroupDetailType> materialHash = new HashMap<>();
                            for (ProductGroupType productGroupType : skuProductBean.getAdditionalGroupList()) {
                                //提取加料信息
                                List<GroupDetailType> groupDetail = new ArrayList<>();
                                groupDetail.addAll(productGroupType.getGroupDetail());

                                for (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<CartGoods.MaterialGoods> materialGoodsList = new ArrayList<>();
                            Long materialAmount = 0L;
                            Long originalMaterAmount = 0L;
                            String materialSubName = cartGoods.getSubName();
                            for (CartGoods.MaterialGoods materialGoods : cartGoods.getProductMaterialList()) {
                                GroupDetailType detail = materialHash.get(materialGoods.getSpuId());
                                if (detail == null) continue;
                                CartGoods.MaterialGoods material = new 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;
                        }
                    }
            );
        }
    }


    /**
     * 更新套餐固定商品、可选商品信息
     *
     * @param comboxGoods       固定商品或可选商品
     * @param parentProductBean 套餐服商品
     * @param isComboxGoods     是否是固定商品
     * @return
     */
    private void updateComboxGoodsInfoNew(CartGoods.ComboxGoods comboxGoods, ProductTypeBeanDTO parentProductBean, boolean isComboxGoods) {

        ProductComboType productComboType = new ProductComboType();
        GroupDetailType groupDetailType = new GroupDetailType();
        if (isComboxGoods) {
            productComboType = parentProductBean.getProductComboList().stream().filter(p -> ObjectUtils.equals(comboxGoods.getGoodsId(), p.getProductId())).findFirst().orElse(new ProductComboType());
            comboxGoods.setLinkedId(productComboType.getLinkedId());
            comboxGoods.setStockLimit(Objects.equals(1,productComboType.getStockLimit()));
        } else {
            Map<String, 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());
            comboxGoods.setLinkedId(groupDetailType.getLinkedId());
            comboxGoods.setStockLimit(Objects.equals(1,groupDetailType.getStockLimit()));
        }

        // 若是固定商品则取商品详情的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.setForeignName(isComboxGoods ? productComboType.getForeignProductName() : groupDetailType.getForeignProductName());
        comboxGoods.setSpuName(comboxGoods.getName());
        // 组合商品类型存放
        comboxGoods.setOriginalProductType(isComboxGoods ? productComboType.getProductType() : groupDetailType.getProductType());
        comboxGoods.setSpuForeignName(comboxGoods.getForeignName());
        comboxGoods.setSpecProductId(attributes.get(ATTRIBUTEID));
        comboxGoods.setSubName(attributes.get(ATTRIBUTENAME));
        comboxGoods.setSubForeignName(attributes.get(ATTRIBUTEFOREIGNNAME));

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

    /**
     * 单独处理加料及标识小料信息是否有变化
     *
     * @param cartGoods
     * @param spuProduct
     */
    private void checkMaterialProduct(CartGoods cartGoods, ProductTypeBeanDTO spuProduct) {

        if (CollectionUtils.isEmpty(cartGoods.getProductMaterialList())) return;
        SkuProductBean skuProductBean = null;
        boolean isSkuProduct = ObjectUtils.equals(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.SKU_GOODS.getGoodsType(), cartGoods.getGoodsType());
        if (isSkuProduct){
            if (CollectionUtils.isEmpty(spuProduct.getSkuList())){
                cartGoods.setGoodsType(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.EXCEPTION_GOODS.getGoodsType());
                cartGoods.setProductMaterialList(new ArrayList<>());
                return;
            } else {
                skuProductBean = spuProduct.getSkuList().stream().filter(p -> p.getSkuId().equals(cartGoods.getSkuId())).findFirst().orElse(null);
                if (skuProductBean == null || CollectionUtils.isEmpty(skuProductBean.getAdditionalGroupList())){
                    cartGoods.setGoodsType(com.freemud.sdk.api.assortment.shoppingcart.constant.GoodsTypeEnum.EXCEPTION_GOODS.getGoodsType());
                    cartGoods.setProductMaterialList(new ArrayList<>());
                    return;
                }
            }
        } else {
            //加料信息为空
            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<>();
        HashMap<String, GroupDetailType> materialHash = new HashMap<>();
        if (isSkuProduct){
            List<ProductGroupType> groupList = skuProductBean.getAdditionalGroupList();
            for (ProductGroupType groupDetail : groupList) {
                for (GroupDetailType groupDetailType : groupDetail.getGroupDetail()) {
                    materialHash.put(groupDetailType.getProductId(), groupDetailType);
                    materialSpu.add(groupDetailType.getProductId());
                }
            }
        } else {
            List<ProductGroupType> groupList = spuProduct.getAdditionalGroupList();
            for (ProductGroupType groupDetail : groupList){
                for (GroupDetailType groupDetailType : groupDetail.getGroupDetail()) {
                    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<CartGoods.MaterialGoods> materialGoodsList = new ArrayList<>();
        Long materialAmount = 0L;
        Long originalMaterAmount = 0L;
        String materialSubName = cartGoods.getSubName();
        for (CartGoods.MaterialGoods materialGoods : cartGoods.getProductMaterialList()) {
            GroupDetailType detail = materialHash.get(materialGoods.getSpuId());
            if (detail == null) continue;
            CartGoods.MaterialGoods material = new CartGoods.MaterialGoods();
            material.setQty(materialGoods.getQty());
            material.setSpuName(detail.getProductName());
            material.setSpuForeignName(detail.getForeignProductName());
            material.setSpuId(detail.getProductId());
            //fisherman 小料商品设置原始商品类型
            material.setOriginalProductType(detail.getProductType());
            //行单价 \ 行总价
            material.setFinalPrice(detail.getProductFinalPrice().longValue());
            material.setAmount(detail.getProductFinalPrice().longValue() * materialGoods.getQty() * cartGoods.getQty());
            //原行单价*数量
            material.setOriginalAmount(detail.getProductFinalPrice().longValue() * materialGoods.getQty() * cartGoods.getQty());
            material.setOriginalPrice(detail.getProductFinalPrice().longValue());
            material.setCustomerCode(detail.getCustomerCode());
            materialGoodsList.add(material);
            materialAmount += detail.getProductFinalPrice().longValue() * materialGoods.getQty() * cartGoods.getQty();
            originalMaterAmount += detail.getProductFinalPrice().longValue() * materialGoods.getQty() * cartGoods.getQty();
            ;
            materialSubName = materialSubName + "/" + detail.getProductName();
        }
        //设置购物车行记录
        cartGoods.setProductMaterialList(materialGoodsList);
        //加料行记录现价总价
        cartGoods.setMaterialAmount(materialAmount);
        //加料行记录原价总价
        cartGoods.setOriginalMaterialAmount(originalMaterAmount);
        //cartGoods.setOriginalAmount(cartGoods.getOriginalAmount() + originalMaterAmount);
        //cartGoods.setSubName(StringUtils.strip(materialSubName, "/"));
    }

}
