package cn.freemud.handle;

import cn.freemud.entities.dto.CheckSpqInfoResponseDto;
import cn.freemud.entities.dto.calculate.CalculationDiscountResult;
import cn.freemud.entities.dto.calculate.Discount;
import cn.freemud.entities.dto.calculate.Goods;
import cn.freemud.entities.vo.CartGoods;
import cn.freemud.entities.vo.ShoppingCartInfoRequestVo;
import cn.freemud.entities.vo.SubtractStockVO;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.enums.GoodsTypeEnum;
import com.freemud.sdk.api.assortment.shoppingcart.constant.CommonsConstant;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

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

/**
 * @author : xh.Z
 * @email : fisherman0510@163.com
 * @Date : 2021/11/18 下午2:42
 * @description : 一点点挪动相同代码 解决代码冗余
 */
@Component
public class PromotionCommonMethodHandle {

    /**
     * 库存扣减加价购商品 要过滤掉没有换购的商品
     *
     * @param stocks                    扣减库存
     * @param shoppingCartInfoRequestVo 购物车请求信息
     * @param addMoneyDiscounts         加价购活动
     * @return 返回应该扣减的加价购商品库存
     */
    public List<SubtractStockVO> filterSendGoodsStocks(List<SubtractStockVO> stocks, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo, List<Discount> addMoneyDiscounts) {
        if (CollectionUtils.isEmpty(stocks) || CollectionUtils.isEmpty(addMoneyDiscounts)) {
            return stocks;
        }
        List<SubtractStockVO> subtractStockVOs = stocks.stream().filter(subtractStockVO -> ActivityTypeEnum.TYPE_81.getCode().equals(subtractStockVO.getActivityType())).collect(Collectors.toList());
        List<SubtractStockVO.SubtractStockGoodsVO> goodsStock = null;
        if (CollectionUtils.isNotEmpty(subtractStockVOs)) {
            SubtractStockVO subtractStockVO = subtractStockVOs.get(0);
            goodsStock = subtractStockVO.getGoodsStock();
        }
        if (null == goodsStock) {
            return stocks;
        }
        Map<String, SubtractStockVO.SubtractStockGoodsVO> mapSubstractStocks = new HashMap<>();
        if (CollectionUtils.isNotEmpty(goodsStock)) {
            mapSubstractStocks = goodsStock.stream().collect(Collectors.toMap(SubtractStockVO.SubtractStockGoodsVO::getGoodsId, Function.identity(), (k1, k2) -> k1));
        }
        //获取加价购商品
        List<ShoppingCartInfoRequestVo.SendGoods> sendGoods = shoppingCartInfoRequestVo.getSendGoods();
        if (CollectionUtils.isNotEmpty(sendGoods)) {
            List<String> needSendGoodsId = sendGoods.stream().map(ShoppingCartInfoRequestVo.SendGoods::getGoodsId).collect(Collectors.toList());
            goodsStock.clear();
            for (String goodId : needSendGoodsId) {
                SubtractStockVO.SubtractStockGoodsVO subtractStockGoodsVO = mapSubstractStocks.get(goodId);
                if (null != mapSubstractStocks.get(goodId)) {
                    goodsStock.add(subtractStockGoodsVO);
                }
            }
        } else {
            return stocks.stream().filter(subtractStockVO -> !ActivityTypeEnum.TYPE_81.getCode().equals(subtractStockVO.getActivityType())).collect(Collectors.toList());
        }
        return stocks;
    }


    /**
     * 新老算价 提取公共代码
     *
     * @param cartGoodsList
     * @param calculationDiscountResult
     */
    public void cartGoodsSetAttributeCommon(List<CartGoods> cartGoodsList,
                                            CalculationDiscountResult calculationDiscountResult) {
        Map<String, CheckSpqInfoResponseDto> validCouponMap = calculationDiscountResult == null ? new HashMap<>() : calculationDiscountResult.getValidCouponMap();
        for (CartGoods cartGoods : cartGoodsList) {
            String couponCode = cartGoods.getCouponCode();
            boolean useCoupon = true; // 优惠券放在coupon字段而不是uuid中
            if (cartGoods.getCartGoodsUid().startsWith(CommonsConstant.COUPON_PREFIX)) {
                couponCode = cartGoods.getCartGoodsUid().substring(CommonsConstant.COUPON_PREFIX.length());
                useCoupon = false;
            }
            List<CartGoods.CartGoodsExtra> extra = cartGoods.getExtra();
            // fisherman bug修复,买m赠n券商品属性未展示问题

            if (CollectionUtils.isNotEmpty(extra)) {
                List<String> specIdList = extra.stream().map(CartGoods.CartGoodsExtra::getAttributeId).collect(Collectors.toList());
                List<String> specNameList = extra.stream().map(CartGoods.CartGoodsExtra::getAttributeName).collect(Collectors.toList());
                cartGoods.setSpecProductId(StringUtils.join(specIdList, "/"));
                cartGoods.setSubName(StringUtils.join(specNameList, "/"));
            }
            if (StringUtils.isNotBlank(couponCode)) {
                // 计算优惠信息时，已将券校验过，放在map中
                if (MapUtils.isNotEmpty(validCouponMap)) {
                    CheckSpqInfoResponseDto checkSpqInfoResponseDto = null;
                    if (useCoupon) {
                        checkSpqInfoResponseDto = validCouponMap.get(couponCode + cartGoods.getSkuId());
                    } else {
                        checkSpqInfoResponseDto = validCouponMap.get(couponCode);
                    }
                    if (checkSpqInfoResponseDto != null) {
                        cartGoods.setOriginalPrice(checkSpqInfoResponseDto.getPrice());
                        cartGoods.setSpuId(checkSpqInfoResponseDto.getSpuId());
                        cartGoods.setSkuId(StringUtils.isEmpty(checkSpqInfoResponseDto.getSkuId()) ? checkSpqInfoResponseDto.getSpuId() : checkSpqInfoResponseDto.getSkuId());
                        cartGoods.setQty(cartGoods.getQty());
                        cartGoods.setCouponCode(checkSpqInfoResponseDto.getCouponCode());
                        cartGoods.setSpuName(checkSpqInfoResponseDto.getSpuName());
                        cartGoods.setSpecProductId(checkSpqInfoResponseDto.getDefaultSpecId());
                        cartGoods.setSubName(checkSpqInfoResponseDto.getDefaultSpecName());
                        cartGoods.setExtra(checkSpqInfoResponseDto.getExtras());
                        if (GoodsTypeEnum.HG_COUPON_GOODS.getGoodsType().equals(cartGoods.getGoodsType())) {
                            Goods discountGoods = null;
                            if (CollectionUtils.isNotEmpty(calculationDiscountResult.getGoods())) {
                                discountGoods = calculationDiscountResult.getGoods()
                                        .stream()
                                        .filter(d -> cartGoods.getCartGoodsUid().equals(d.getCartGoodsUid()))
                                        .findFirst()
                                        .orElse(null);
                            }

                            if (discountGoods != null) {
                                cartGoods.setAmount(discountGoods.getRealAmount());
                            } else {
                                cartGoods.setAmount(checkSpqInfoResponseDto.getPrice() * cartGoods.getQty());
                            }
                        }
                        cartGoods.setOriginalAmount(checkSpqInfoResponseDto.getPrice() * cartGoods.getQty());
                    }
                }
            }
        }
    }
}
