package cn.freemud.demo.adapter.service;

import cn.freemud.demo.entities.bo.DistributeAdapterBO;
import cn.freemud.demo.entities.bo.goods.CalculationDiscountBO;
import cn.freemud.demo.entities.bo.goods.DistributeBO;
import cn.freemud.demo.entities.bo.goods.SetMessageBO;
import cn.freemud.demo.entities.bo.goods.ShoppingCartGoodsBO;
import cn.freemud.demo.utils.CommonUtils;
import cn.freemud.entities.dto.CheckSpqInfoResponseDto;
import cn.freemud.entities.vo.ActivityClassifyCouponBean;
import cn.freemud.entities.vo.CartGoods;
import cn.freemud.entities.vo.CouponPromotionVO;
import cn.freemud.enums.AvailableCouponQueryFlagEnum;
import cn.freemud.enums.GoodsTypeEnum;
import cn.freemud.service.CouponService;
import cn.freemud.service.impl.AssortmentSdkService;
import com.freemud.sdk.api.assortment.shoppingcart.constant.CommonsConstant;
import com.freemud.sdk.api.assortment.shoppingcart.service.impl.ShoppingCartBaseServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component
public class DistributeAdapter {

    @Autowired
    private AssortmentSdkService assortmentSdkService;

    @Autowired
    private ShoppingCartBaseServiceImpl shoppingCartBaseService;

    @Autowired
    private CouponService couponService;

    public void adapter(DistributeBO calCostBO, SetMessageBO commonSetMessageBO, DistributeAdapterBO bo, CouponPromotionVO couponPromotionVO, int type){

        // 商品券
        ShoppingCartGoodsBO shoppingCartGoodsBO = commonSetMessageBO.getShoppingCartGoodsBO();
        List<CartGoods> cartGoodsList = commonSetMessageBO.getCartGoods();

        CalculationDiscountBO.CalculationDiscountResult discountResult = null;
        if (calCostBO.getCalculationDiscountBO() != null){
            discountResult = calCostBO.getCalculationDiscountBO().getResult();
        }

        if (type == 2){
            if (couponPromotionVO != null && !ObjectUtils.equals(AvailableCouponQueryFlagEnum.NO.getCode(), couponPromotionVO.getAvailableCouponQueryFlag())) {
                List<CartGoods> tmpCartGoods = cartGoodsList.parallelStream().filter(k -> CommonUtils.isProductCoupon(k.getCouponCode(), k.getCartGoodsUid())).collect(Collectors.toList());
                // 是否存在商品券
                boolean hasGoodssCoupon = CollectionUtils.isNotEmpty(tmpCartGoods);

                String chooseCouponCode = "";
                if (StringUtils.isBlank(couponPromotionVO.getUnChooseCouponCode()) && hasGoodssCoupon){
                    chooseCouponCode = tmpCartGoods.get(0).getGoodsId().substring(CommonsConstant.COUPON_PREFIX.length());
                }

                // 构建可用不可用优惠券
                ActivityClassifyCouponBean activityClassifyCouponBean = couponService.availableCoupon(cartGoodsList
                        , couponPromotionVO.getPartnerId()
                        , couponPromotionVO.getUserId()
                        , couponPromotionVO.getStoreId()
                        , couponPromotionVO
                        , hasGoodssCoupon
                        , couponPromotionVO.getOrderType()
                        , 1
                        , bo.getAppId(), bo.getMenuType(), chooseCouponCode
                );
                if (Objects.equals(activityClassifyCouponBean, null)) {
                    // 构建一个空得订单券信息
                    activityClassifyCouponBean = createEmptyActivityCouponBean();
                }
                shoppingCartGoodsBO.setAvailableCoupon(activityClassifyCouponBean);
            } else {
                // 构建一个空得订单券信息
                ActivityClassifyCouponBean activityClassifyCouponBean = createEmptyActivityCouponBean();
                shoppingCartGoodsBO.setAvailableCoupon(activityClassifyCouponBean);
            }
            // 当couponCode不为空时，需计算优惠价格 3代金 31折扣  32商品  33换购券
            // 当couponCode不为空时，需计算优惠价格 3代金 31折扣  32商品  33换购券
            long couponDiscount = 0;
            if (couponPromotionVO != null && StringUtils.isNotEmpty(couponPromotionVO.getCouponCode())
                    && calCostBO.getCalculationDiscountBO() != null && calCostBO.getCalculationDiscountBO().getResult() != null
                    && calCostBO.getCalculationDiscountBO().getResult().getDiscounts() != null) {
                List<Integer> asList = Arrays.asList(3, 31);
                List<CalculationDiscountBO.CalculationDiscountResult.Discount> couponDiscounts = calCostBO.getCalculationDiscountBO().getResult().getDiscounts();
                CalculationDiscountBO.CalculationDiscountResult.Discount first = couponDiscounts.stream().filter(d -> asList.contains(d.getType())).findFirst().orElse(null);
                if (first!=null) couponDiscount = first.getDiscount().longValue();

            }
            shoppingCartGoodsBO.setCouponDiscount(couponDiscount);
        }
        if (type == 1){
            // 用户选择了查询优惠券信息
            ActivityClassifyCouponBean activityClassifyCouponBean = createEmptyActivityCouponBean();
            shoppingCartGoodsBO.setAvailableCoupon(activityClassifyCouponBean);
            // 当couponCode不为空时，需计算优惠价格 3代金 31折扣  32商品  33换购券
            shoppingCartGoodsBO.setCouponDiscount(0L);
        }


        Map<String, CheckSpqInfoResponseDto> validCouponMap = discountResult == null ? new HashMap<>() : discountResult.getValidCouponMap();
        Map<String, List<String>> spqIdToCartUuid = discountResult == null ? new HashMap<>() : discountResult.getSpqIdToCartUuidMap();
        if (MapUtils.isNotEmpty(validCouponMap) && MapUtils.isNotEmpty(spqIdToCartUuid) && discountResult != null){
            List<String> activityCodeList = discountResult.getDiscounts().stream().map(p -> p.getActivityCode()).collect(Collectors.toList());
            for (String couponCode : validCouponMap.keySet()) {
                CheckSpqInfoResponseDto sqpInfo = validCouponMap.get(couponCode);
                if (!activityCodeList.contains(sqpInfo.getCouponCode())){ // 表示商品券不够启用金额
                    List<String> uuidList = spqIdToCartUuid.get(sqpInfo.getCouponCode());
                    if (CollectionUtils.isNotEmpty(uuidList)){
                        List<CartGoods> newCartList = cartGoodsList.stream().filter(p -> !uuidList.contains(p.getCartGoodsUid())).collect(Collectors.toList());
                        assortmentSdkService.setShoppingCart(bo.getPartnerId(), bo.getShopId(), bo.getUserId(), newCartList, null, null, this.shoppingCartBaseService,null);
                        cartGoodsList = newCartList;
                        CheckSpqInfoResponseDto checkSpqInfoResponseDto = validCouponMap.get(couponCode);
                        commonSetMessageBO.setChanged(true);
                        commonSetMessageBO.setToastMsg("当前购物车金额低于【" + checkSpqInfoResponseDto.getCouponName() + "】优惠券起用金额门槛，券已自动移除购物车");
                    }
                }
            }
        }


        //循环购物车商品券
        for (CartGoods cartGoods : cartGoodsList) {
            if (CommonUtils.isProductCoupon(cartGoods.getCouponCode(), cartGoods.getCartGoodsUid())) {
                String couponCode = CommonUtils.getCouponCode(cartGoods.getCouponCode(), cartGoods.getCartGoodsUid());
                // 计算优惠信息时，已将券校验过，放在map中
                if (MapUtils.isNotEmpty(validCouponMap)) {
                    CheckSpqInfoResponseDto checkSpqInfoResponseDto;
                    boolean useCoupon = true; // 优惠券放在coupon字段而不是uuid中
                    if (cartGoods.getCartGoodsUid().startsWith(CommonsConstant.COUPON_PREFIX)){
                        useCoupon = false;
                    }
                    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());
                        List<CartGoods.CartGoodsExtra> extra = cartGoods.getExtra();
                        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, "/"));
                            cartGoods.setExtra(extra);
                        } else {
                            cartGoods.setSpecProductId(checkSpqInfoResponseDto.getDefaultSpecId());
                            cartGoods.setSubName(checkSpqInfoResponseDto.getDefaultSpecName());
                            cartGoods.setExtra(checkSpqInfoResponseDto.getExtras());
                        }
                        if (GoodsTypeEnum.HG_COUPON_GOODS.getGoodsType().equals(cartGoods.getGoodsType())) {
                            CalculationDiscountBO.CalculationDiscountResult.Goods discountGoods = discountResult.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());
                    }
                }
            }
        }

    }


    public ActivityClassifyCouponBean createEmptyActivityCouponBean() {
        ActivityClassifyCouponBean activityClassifyCouponBean = new ActivityClassifyCouponBean();
        activityClassifyCouponBean.setCouponNum(0);
        activityClassifyCouponBean.setDisableCouponNum(0);
        activityClassifyCouponBean.setUsableCouponNum(0);
        activityClassifyCouponBean.setDisableCoupons(Lists.newArrayList());
        activityClassifyCouponBean.setUsableCoupons(Lists.newArrayList());
        return activityClassifyCouponBean;
    }

}
