package cn.freemud.service.impl.mcoffee.calculation;

import cn.freemud.adapter.ShoppingCartConvertAdapter;
import cn.freemud.adapter.ShoppingCartMccafeAdapter;
import cn.freemud.entities.dto.calculate.ActivityCalculationDiscountResponseDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.CartGoods;
import cn.freemud.entities.vo.ShoppingCartGoodsResponseVo;
import cn.freemud.enums.GoodsTypeEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: SetMealCalculation
 * @Package cn.freemud.service.impl.mcoffee.calculation
 * @Description:
 * @author: ping1.wu
 * @date: 2020/8/6 19:10
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
public class SetMealCalculation {

    @Autowired
    private ShoppingCartConvertAdapter shoppingCartConvertAdapter;
    @Autowired
    private ShoppingCartMccafeAdapter shoppingCartMccafeAdapter;

    public void updateShoppingCartGoodsDiscount(ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult, List<CartGoods> cartGoodsList, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo) {

        List<CartGoods> setMealProducts = cartGoodsList.stream().filter(cartGoods -> ObjectUtils.equals(GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType(), cartGoods.getGoodsType())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(setMealProducts)) {
            return;
        }
        // 存储当前享受限时特价折扣的商品数量
        Map<String, Integer> numberMap = new HashMap<>();
        // 当前商品行现价
        Map<String, ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods> goodsMap = calculationDiscountResult.getGoods().parallelStream()
                .collect(Collectors.toMap(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods::getGoodsId, Function.identity(), (k1, k2) -> k1));

        // 设置商品原价与商品现价的初始值
        for (CartGoods cartGoods : cartGoodsList) {
            if(!ObjectUtils.equals(GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType(), cartGoods.getGoodsType())){
                continue;
            }
//            cartGoods.setOriginalAmount(cartGoods.getOriginalPrice() * cartGoods.getQty());
            cartGoods.setPackPrice(cartGoods.getPackPrice() * cartGoods.getQty());

            long materialPrice = 0l;
            //套餐固定商品加料
            if(CollectionUtils.isNotEmpty(cartGoods.getProductComboList())){
                for (CartGoods.ComboxGoods comboxGoods : cartGoods.getProductComboList()){
                    Long comboxmaterialPrice = 0L;
                    if(CollectionUtils.isNotEmpty(comboxGoods.getProductMaterialList())){
                        for (CartGoods.MaterialGoods materialGoods : comboxGoods.getProductMaterialList()){
                            comboxmaterialPrice+= null !=  materialGoods.getFinalPrice() ? materialGoods.getFinalPrice() * cartGoods.getQty() : 0;
                        }
                    }
                    comboxGoods.setAmount((null == comboxGoods.getAmount() ? 0 :
                            comboxGoods.getAmount())+comboxmaterialPrice);
                    materialPrice = materialPrice + comboxmaterialPrice;
                }
            }

            //套餐可选商品加料
            if(CollectionUtils.isNotEmpty(cartGoods.getProductGroupList())){
                for (CartGoods.ComboxGoods comboxGoods : cartGoods.getProductGroupList()){
                    Long productGroupmaterialPrice = 0L;
                    if(CollectionUtils.isNotEmpty(comboxGoods.getProductMaterialList())){
                        for (CartGoods.MaterialGoods materialGoods : comboxGoods.getProductMaterialList()){
                            productGroupmaterialPrice+= null !=  materialGoods.getFinalPrice() ? materialGoods.getFinalPrice() * cartGoods.getQty() : 0;
                        }
                    }
                    comboxGoods.setAmount((null == comboxGoods.getAmount() ? 0 :
                            comboxGoods.getAmount())+productGroupmaterialPrice);
                    materialPrice = materialPrice + productGroupmaterialPrice;
                }
            }

            //如果是商品券商品，不重新计算套餐价格
            if (StringUtils.isEmpty(cartGoods.getCouponCode())
                    || (null !=calculationDiscountResult.getMonthlyEnjoyCardDiscount()
                    && StringUtils.isNotBlank(calculationDiscountResult.getMonthlyEnjoyCardDiscount().getCouponCode())
                    && cartGoods.getCouponCode().equals(calculationDiscountResult.getMonthlyEnjoyCardDiscount().getCouponCode()))) {
                cartGoods.setAmount(cartGoods.getAmount() + materialPrice);
                cartGoods.setOriginalAmount(cartGoods.getOriginalAmount() + materialPrice);
            }

        }

    }


    public void updateShoppingCartGoodsApportion(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult, ShoppingCartGoodsDto shoppingCartGoodsDto) {
        //套餐商品总优惠
        Integer totalDiscountAmount = 0;
        List<ShoppingCartGoodsDto.CartGoodsDetailDto> cartGoodsDetailDtos = shoppingCartGoodsDto.getProducts();
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ApportionGoods> apportionGoods = calculationDiscountResult == null ? new ArrayList<>()
                : calculationDiscountResult.getApportionGoods();
        // key为：goodsId；value以逗号分割：0为goodsId分组对应的数量，value为已计算的折扣金额
        //此map是为了促销除不尽时，拆商品行所用，例如，3份折扣10元
        Map<String, String> duplicateGoodsMap = new HashMap<>();
        shoppingCartGoodsResponseVo.getProducts().stream().filter(product->ObjectUtils.equals(GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType(), product.getGoodsType())).collect(Collectors.groupingBy(CartGoods::getGoodsId, Collectors.counting())).forEach((goodsId, count) -> {
            duplicateGoodsMap.put(goodsId,String.format("%s,0", count));
        });
        // 套餐优惠明细
        for (CartGoods cartGoods : shoppingCartGoodsResponseVo.getProducts()) {
            if (ObjectUtils.equals(GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType(), cartGoods.getGoodsType()) && StringUtils.isBlank(cartGoods.getCouponCode())) {
                // 添加套餐父商品
                ShoppingCartGoodsDto.CartGoodsDetailDto parentCartGoods = shoppingCartMccafeAdapter.convertCartGoods2DetailGoods(cartGoods, apportionGoods,duplicateGoodsMap);
                // 添加套餐固定商品&可选商品: 做均摊
                parentCartGoods.setComboProducts(shoppingCartMccafeAdapter.convertComboxGoods2DetailGoods(cartGoods,parentCartGoods.getTotalDiscountAmount()));
                cartGoodsDetailDtos.add(parentCartGoods);
            }
        }
    }

}
