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.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: TimeSalePromotionService
 * @Package cn.freemud.service.impl
 * @Description:
 * @author: jiaxin.liu
 * @date: 2019/4/18 10:58
 * @Copyright: 2019 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
public class TimeSalePromotionService implements IPromotionService {


    @Override
    public void updateShoppingCartGoodsDiscount(CouponPromotionVO couponPromotionVO, ActivityQueryDto activityQueryDto, CalculationDiscountResult calculationDiscountResult, List<CartGoods> cartGoodsList, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, UserLoginInfoDto userLoginInfoDto, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        if (calculationDiscountResult == null || CollectionUtils.isEmpty(calculationDiscountResult.getDiscounts()) || !calculationDiscountResult.getDiscounts().stream().anyMatch(discount -> (ActivityTypeEnum.TYPE_2.getCode().equals(discount.getType()) || (ActivityTypeEnum.TYPE_21.getCode().equals(discount.getType())) || ActivityTypeEnum.TYPE_22.getCode().equals(discount.getType())))) {
            return;
        }
        List<Goods> goodsList = calculationDiscountResult.getGoods();
        if (CollectionUtils.isEmpty(goodsList)) {
            return;
        }
        String toastMsg = null;
        Map<String, Goods> goodsMap = goodsList.parallelStream()
                .collect(Collectors.toMap(Goods::getCartGoodsUid, Function.identity(), (k1, k2) -> k1));
        // 存储当前享受限时特价折扣的商品数量，key:goodsId; value:可享受数量
        //Map<String, Integer> numberMap = new HashMap<>();
        List<Integer> discounts = Arrays.asList(ActivityTypeEnum.TYPE_2.getCode(), ActivityTypeEnum.TYPE_21.getCode(), ActivityTypeEnum.TYPE_22.getCode());
        String uid = "";
        for (CartGoods cartGoods : cartGoodsList) {
            Goods goods;
            if ((goods = goodsMap.get(cartGoods.getCartGoodsUid())) == null) {
                continue;
            }
            GoodsDiscount goodsDiscount = getGoodsDiscount(goods.getDiscounts(), discounts);
            if (goodsDiscount == null) {
                continue;
            }
            // 享受限时特价折扣的商品数量
            Integer specialActualGoodsNumber = goodsDiscount.getActualGoodsNumber();
            // 商品现价
            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() + "份优惠 超出按照原价计算哦";
                    uid = goods.getCartGoodsUid();
                }
            }
//            numberMap.put(goods.getGoodsId(), specialActualGoodsNumber - cartGoods.getQty());
        }
        if (StringUtils.isNotBlank(toastMsg)) {
            shoppingCartGoodsResponseVo.setToastMsg(toastMsg);
            shoppingCartGoodsResponseVo.setUid(uid);
        }
    }

    @Override
    public void updateShoppingCartGoodsApportion(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, CalculationDiscountResult calculationDiscountResult, ShoppingCartGoodsDto shoppingCartGoodsDto, CreateOrderVo.PremiumExchangeActivity premiumExchangeActivity, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        if (calculationDiscountResult == null || CollectionUtils.isEmpty(calculationDiscountResult.getDiscounts()) || !calculationDiscountResult.getDiscounts().stream().anyMatch(discount -> (ActivityTypeEnum.TYPE_2.getCode().equals(discount.getType()) || ActivityTypeEnum.TYPE_21.getCode().equals(discount.getType())))) {
            return;
        }
        List<Goods> goodsList = calculationDiscountResult.getGoods();
        if (CollectionUtils.isEmpty(goodsList)) {
            return;
        }
        // 商品实际享受优惠的数量：  key:skuId;  value:实际数量
//        Map<String, Integer> numberMap = new HashMap<>();
        Map<String, Goods> goodsMap = goodsList.parallelStream()
                .collect(Collectors.toMap(Goods::getCartGoodsUid, Function.identity(), (k1, k2) -> k1));

        for (ShoppingCartGoodsDto.CartGoodsDetailDto cartGoods : shoppingCartGoodsDto.getProducts()) {
            Goods goods;
            // 特价商品没有匹配 或 加价购商品 直接跳出循环
            if ((goods = goodsMap.get(cartGoods.getCartGoodsUid())) == null || ObjectUtils.equals(ActivityTypeEnum.TYPE_81.getCode(), cartGoods.getActivityType())) {
                continue;
            }
            GoodsDiscount goodsDiscount = getGoodsDiscount(goods.getDiscounts(), Arrays.asList(ActivityTypeEnum.TYPE_21.getCode(), ActivityTypeEnum.TYPE_2.getCode()));
            if (goodsDiscount == null) {
                continue;
            }

//            if (numberMap.get(cartGoods.getSkuId()) == null) {
//                numberMap.put(cartGoods.getSkuId(), goods.getActualGoodsNumber());
//            }
            Integer actualGoodsNumber = goodsDiscount.getActualGoodsNumber();
            if (actualGoodsNumber > 0) {
//                Long totalDiscountAmount = cartGoods.getQty() > actualGoodsNumber ? goodsDiscount.getDiscount() * actualGoodsNumber / goodsDiscount.getActualGoodsNumber() : goodsDiscount.getDiscount() * cartGoods.getQty() / goodsDiscount.getActualGoodsNumber();
                //Long totalDiscountAmount = cartGoods.getQty() > actualGoodsNumber ? goods.getDiscountAmount() * actualGoodsNumber / goods.getActualGoodsNumber() : goods.getDiscountAmount() * cartGoods.getQty() / goods.getActualGoodsNumber();
                ActivityDiscountsDto activityDiscountsDto = new ActivityDiscountsDto();
                activityDiscountsDto.setActivityCode(goodsDiscount.getActivityCode());
                activityDiscountsDto.setActivityName(goodsDiscount.getActivityName());
                activityDiscountsDto.setActivityType(ActivityTypeEnum.TYPE_2.getCode());
                activityDiscountsDto.setDiscountAmount(goodsDiscount.getDiscount().intValue());
                cartGoods.getActivityDiscountsDtos().add(activityDiscountsDto);
                cartGoods.setTotalDiscountAmount(cartGoods.getTotalDiscountAmount() + goodsDiscount.getDiscount().intValue());
//                numberMap.put(cartGoods.getSkuId(), actualGoodsNumber - cartGoods.getQty());
            } else {
                cartGoods.setTotalDiscountAmount(0);
            }

        }
    }

    /**
     * 获取指定促销类型的GoodsDiscount
     *
     * @param goodsDiscountList
     * @param discounts
     * @return
     */
    private GoodsDiscount getGoodsDiscount(List<GoodsDiscount> goodsDiscountList, List<Integer> discounts) {
        if (CollectionUtils.isEmpty(goodsDiscountList)) {
            return null;
        }
        for (GoodsDiscount goodsDiscount : goodsDiscountList) {
            if (discounts.contains(goodsDiscount.getType())) {
                return goodsDiscount;
            }
        }
        return null;
    }

    /**
     * 获取指定促销类型的ApportionGoods
     *
     * @param cartGoods
     * @param apportionGoodsList
     * @param type
     * @return
     */
    private ApportionGoods getApportionGoods(CartGoods cartGoods, List<ApportionGoods> apportionGoodsList, ActivityTypeEnum type) {
        for (ApportionGoods apportionGoods : apportionGoodsList) {
            if (!StringUtils.equals(apportionGoods.getGoodsId(), cartGoods.getGoodsId())) {
                continue;
            }
            // 特价均摊信息没有促销类型，以此需要使用详情中促销类型
            ApportionDetails apportionDetails = getApportionDetails(apportionGoods.getApportionDetails(), type);
            if (apportionDetails == null) {
                continue;
            }
            return apportionGoods;
        }
        return null;
    }

    /**
     * 获取指定促销类型的ApportionDetails
     *
     * @param apportionDetailsList
     * @param type
     * @return
     */
    private ApportionDetails getApportionDetails(List<ApportionDetails> apportionDetailsList, ActivityTypeEnum type) {
        for (ApportionDetails apportionDetails : apportionDetailsList) {
            if (Objects.equals(apportionDetails.getActivityType(), ActivityTypeEnum.TYPE_2.getCode())) {
                return apportionDetails;
            }
        }
        return null;
    }
}
