package cn.freemud.service.impl;

import cn.freemud.entities.dto.ActivityCalculationDiscountResponseDto;
import cn.freemud.entities.vo.CartGoods;
import cn.freemud.entities.vo.ShoppingCartGoodsMealResponseVo;
import cn.freemud.enums.ActivityTypeEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

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

@Service
public class TimeSalePromotionForWcService {

    public void updateShoppingCartGoodsDiscount(ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult, List<CartGoods> cartGoodsList, ShoppingCartGoodsMealResponseVo shoppingCartGoodsResponseVo) {
        if (calculationDiscountResult == null || CollectionUtils.isEmpty(calculationDiscountResult.getDiscounts()) || !calculationDiscountResult.getDiscounts().stream().anyMatch(discount -> ActivityTypeEnum.TYPE_2.getCode().equals(discount.getType()))) {
            return;
        }
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods> goodsList = calculationDiscountResult.getGoods();
        if (CollectionUtils.isEmpty(goodsList)) {
            return;
        }
        String toastMsg = null;
        Map<String, ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods> goodsMap = goodsList.parallelStream()
                .collect(Collectors.toMap(ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods::getGoodsId, Function.identity(), (k1, k2) -> k1));
        // 存储当前享受限时特价折扣的商品数量，key:goodsId; value:可享受数量
        Map<String, Integer> numberMap = new HashMap<>();
        for (CartGoods cartGoods : cartGoodsList) {
            ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods goods;
            if ((goods = goodsMap.get(cartGoods.getGoodsId())) == null) {
                continue;
            }
            ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount goodsDiscount = getGoodsDiscount(goods.getDiscounts(), ActivityTypeEnum.TYPE_2);
            if (goodsDiscount == null) {
                continue;
            }
            // 享受限时特价折扣的商品数量
            Integer specialActualGoodsNumber = null;
            // 商品现价
            Long goodsNowPrice = cartGoods.getOriginalPrice() - goodsDiscount.getDiscount() / goodsDiscount.getActualGoodsNumber();
            // numberMap用于暂存当前商品行可享受限时特价折扣的商品数量
            if ((specialActualGoodsNumber = numberMap.get(goods.getGoodsId())) == null) {
                numberMap.put(goods.getGoodsId(), specialActualGoodsNumber=goodsDiscount.getActualGoodsNumber());
            }
            //若可享受数量>=当前商品行的商品数量
            if (specialActualGoodsNumber - cartGoods.getQty() >= 0) {
                cartGoods.setAmount(goodsNowPrice * cartGoods.getQty());
            } else {
                //总价=可享受数量*优惠后单价+（当前商品行的商品数量-可享受数量）*商品原价
                cartGoods.setAmount(specialActualGoodsNumber > 0 ? specialActualGoodsNumber * goodsNowPrice + (cartGoods.getQty() - specialActualGoodsNumber) * cartGoods.getOriginalPrice()
                        : goods.getOriginalPrice() * cartGoods.getQty());
                if (StringUtils.isEmpty(toastMsg)) {
                    toastMsg = "该商品限" + goodsDiscount.getActualGoodsNumber() + "份优惠 超出按照原价计算哦";
                }
            }
            numberMap.put(goods.getGoodsId(), specialActualGoodsNumber - cartGoods.getQty());
        }
        if (StringUtils.isNotBlank(toastMsg)) {
            shoppingCartGoodsResponseVo.setToastMsg(toastMsg);
        }
    }

    /**
     * 获取指定促销类型的GoodsDiscount
     *
     * @param goodsDiscountList
     * @param type
     * @return
     */
    private ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount getGoodsDiscount(List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount> goodsDiscountList, ActivityTypeEnum type) {
        if (CollectionUtils.isEmpty(goodsDiscountList)) {
            return null;
        }
        for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount goodsDiscount : goodsDiscountList) {
            if (Objects.equals(goodsDiscount.getType(), type.getCode())) {
                return goodsDiscount;
            }
        }
        return null;
    }

}
