package cn.freemud.service.impl;

import cn.freemud.entities.dto.UserLoginInfoDto;
import cn.freemud.entities.dto.activity.ActivityDiscountsDto;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.calculate.*;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.service.IPromotionService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

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

/**
 * @author Clover.z
 * @Date 2021/8/18
 * @Desc 满M件N折活动优惠计算
 */
@Service("FullMCountNFoldPromotionService")
public class FullMCountNFoldPromotionService implements IPromotionService {

    @Override
    public void updateShoppingCartGoodsDiscount(CouponPromotionVO couponPromotionVO, ActivityQueryDto activityQueryDto, CalculationDiscountResult calculationDiscountResult, List<CartGoods> cartGoodsList, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, UserLoginInfoDto userLoginInfoDto, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        if (! assertHasDiscount(calculationDiscountResult)) return;

        // 转换一下结构，方便匹配购物车商品的活动信息
        Map<String, Goods> map = calculationDiscountResult.getGoods().stream()
                .collect(Collectors.toMap(Goods::getCartGoodsUid, Function.identity(), (k1, k2) -> k1));
        // 匹配购物车行，设置优惠价格
        cartGoodsList.forEach(cartGoods -> {
            Goods discountGoods = map.get(cartGoods.getCartGoodsUid());
            if (null != discountGoods && CollectionUtils.isNotEmpty(discountGoods.getDiscounts())) {
                GoodsDiscount discount = getDiscount(discountGoods.getDiscounts());
                Long originPrice = cartGoods.getFinalPrice() * cartGoods.getQty();
                cartGoods.setAmount(originPrice - discount.getDiscount());
                cartGoods.setActivityNumber(discount.getActualGoodsNumber());
            }
        });
    }

    @Override
    public void updateShoppingCartGoodsApportion(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, CalculationDiscountResult calculationDiscountResult, ShoppingCartGoodsDto shoppingCartGoodsDto, CreateOrderVo.PremiumExchangeActivity premiumExchangeActivity, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        if (! assertHasDiscount(calculationDiscountResult)) return;

        // 转换一下结构，方便匹配购物车商品的活动信息
        Map<String, Goods> map = calculationDiscountResult.getGoods().stream()
                .collect(Collectors.toMap(Goods::getCartGoodsUid, Function.identity(), (k1, k2) -> k1));

        for (ShoppingCartGoodsDto.CartGoodsDetailDto cartGoods : shoppingCartGoodsDto.getProducts()) {
            Goods discountGoods = map.get(cartGoods.getCartGoodsUid());
            if (null != discountGoods && CollectionUtils.isNotEmpty(discountGoods.getDiscounts())) {
                GoodsDiscount discount = getDiscount(discountGoods.getDiscounts());

                ActivityDiscountsDto activityDiscountsDto = new ActivityDiscountsDto();
                activityDiscountsDto.setActivityCode(discount.getActivityCode());
                activityDiscountsDto.setActivityName(discount.getActivityName());
                activityDiscountsDto.setActivityType(ActivityTypeEnum.TYPE_83.getCode());
                activityDiscountsDto.setDiscountAmount(discount.getDiscount().intValue());
                cartGoods.getActivityDiscountsDtos().add(activityDiscountsDto);
                cartGoods.setTotalDiscountAmount(cartGoods.getTotalDiscountAmount() + discount.getDiscount().intValue());
            }
        }
    }

    /**
     * 判断是否符合优惠
     * @param calculationDiscountResult
     * @return
     */
    private boolean assertHasDiscount(CalculationDiscountResult calculationDiscountResult) {
        if (calculationDiscountResult == null || CollectionUtils.isEmpty(calculationDiscountResult.getDiscounts()))
            return false;

        List<Discount> discountList
                = calculationDiscountResult.getDiscounts().stream().filter(discount -> ActivityTypeEnum.TYPE_83.getCode().equals(discount.getType())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(discountList))
            return false;

        return true;
    }


    /**
     * 返回商品参与的满M件N折的活动信息
     * @param goodsDiscounts
     * @return
     */
    private GoodsDiscount getDiscount(List<GoodsDiscount> goodsDiscounts) {
        for (GoodsDiscount discount : goodsDiscounts) {
            if (ActivityTypeEnum.TYPE_83.getCode().equals(discount.getType())) {
                return discount;
            }
        }
        return null;
    }
}
