package cn.freemud.service.impl;

import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.activity.ActivityQueryResponseDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.service.ActivityService;
import cn.freemud.service.IPromotionService;
import cn.freemud.utils.WebUtil;
import com.freemud.application.sdk.api.promotioncenter.request.promotion.UnifyActivityRequest;
import com.freemud.application.sdk.api.promotioncenter.service.PromotionSdkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

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

    @Autowired
    private PromotionSdkService promotionSdkService;

    @Autowired
    private ActivityService activityService;

    /**
     * 查询每满减和阶梯满减活动中的第一个，构建提示语，筛选出购物车内的参与满减的商品，计算总的优惠金额
     * @param couponPromotionVO
     * @param activityQueryDto
     * @param calculationDiscountResult
     * @param allCartGoodsList
     * @param shoppingCartGoodsResponseVo
     */
    @Override
    public void updateShoppingCartGoodsDiscount(CouponPromotionVO couponPromotionVO, ActivityQueryDto activityQueryDto, ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult, List<CartGoods> allCartGoodsList, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, UserLoginInfoDto userLoginInfoDto, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        shoppingCartGoodsResponseVo.setActivityTip(new ActivityTip());
        List<ActivityTypeEnum> activityTypeEnums = new LinkedList<>();
        activityTypeEnums.add(ActivityTypeEnum.TYPE_11);
        activityTypeEnums.add(ActivityTypeEnum.TYPE_12);
        //调用促销统一活动查询
        //过滤出参与的满减(目前只有每满减和阶梯满减)
        ActivityQueryResponseDto activityQueryResponseDto = activityService.queryActivityByType(activityQueryDto, activityTypeEnums, null);
        if (activityQueryResponseDto == null) {
            return ;
        }
        List<ActivityResponseDto> activityQueryDtoList = activityQueryResponseDto.getResult();
        if(CollectionUtils.isEmpty(activityQueryDtoList)){
            return;
        }

        PromotionMessageDto promotionMessageDto = new PromotionMessageDto();
        ActivityResponseDto activityResponseDto = activityQueryDtoList.get(0);
        promotionMessageDto.setActivityId(activityResponseDto.getActivityCode());
        promotionMessageDto.setActivityName(activityResponseDto.getActivityName());
        promotionMessageDto.setActivityType(activityResponseDto.getActivityType());
        promotionMessageDto.setPromotionAmount(0L);
        StringBuilder messageBuilder = new StringBuilder();

        //没有加入购物车
        if (calculationDiscountResult == null) {
            // 因为没有促销活动的计算信息，所以没有加入购物车内
            List<BenefitBeanDto> benefitBeanDtos = activityResponseDto.getBenefits();
            BenefitBeanDto benefitBeanDto = benefitBeanDtos.get(0);
            //调用没有加入购物车的提示语的方法
            setMessageNotInShoppingCart(messageBuilder,activityResponseDto,benefitBeanDtos,benefitBeanDto);
        }else{
            //促销返回满减提示语
            List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ActivityPrompt> activityPrompts = calculationDiscountResult.getActivityPrompts();
            List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount> discountList1 = calculationDiscountResult.getDiscounts();
            //构建提示语
            if (CollectionUtils.isNotEmpty(activityPrompts)){
                setMessageSatisfyCart(messageBuilder,activityPrompts,activityResponseDto);
            }else {
                setMessageNoSatisfyCart(messageBuilder,discountList1);
            }
        }

        promotionMessageDto.setPromotionMessage(messageBuilder.toString());
        ActivityTip activityTip = new ActivityTip();
        activityTip.setActivityCode(promotionMessageDto.getActivityId());
        activityTip.setActivityType(promotionMessageDto.getActivityType());
        activityTip.setActivityName(promotionMessageDto.getPromotionMessage());
        shoppingCartGoodsResponseVo.setActivityTip(activityTip);
        if (calculationDiscountResult == null){
            return;
        }

        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount> discountList = calculationDiscountResult.getDiscounts();
        if(CollectionUtils.isEmpty(discountList)){
            return;
        }

        //过滤出参与的满减(目前只有每满减和阶梯满减)
        List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount> fullDiscountsList = discountList
                .stream().filter(discount -> ActivityTypeEnum.TYPE_11.getCode().equals(discount.getType()) || ActivityTypeEnum.TYPE_12.getCode().equals(discount.getType()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(fullDiscountsList)) {
            return;
        }
        //总的满减优惠金额
        long fullDiscount = 0L;
        for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount fullDiscounts : fullDiscountsList) {
            fullDiscount = fullDiscount + (fullDiscounts.getDiscount() == null ? 0 : fullDiscounts.getDiscount());
        }
        //设置到响应中
        shoppingCartGoodsResponseVo.setFullDiscount(fullDiscount);
        shoppingCartGoodsResponseVo.setProducts(allCartGoodsList);
        shoppingCartGoodsResponseVo.setProductsCount(allCartGoodsList.size());
    }

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

    //设置没有加入购物车的提示语
    private void setMessageNotInShoppingCart(StringBuilder messageBuilder, ActivityResponseDto activityResponseDto, List<BenefitBeanDto> benefitBeanDtos, BenefitBeanDto benefitBeanDto){
        if (Objects.equals(ActivityTypeEnum.TYPE_11.getCode(), activityResponseDto.getActivityType())) {
            messageBuilder.append("每满 <span style=\"color:#fa5555\">")
                    .append(WebUtil.formatAmount(benefitBeanDto.getThresholdAmount() * 1.00 / 100))
                    .append("</span> 减 <span style=\"color:#fa5555\">")
                    .append(WebUtil.formatAmount(benefitBeanDto.getDiscountAmount() * 1.00 / 100))
                    .append("</span> ")
                    .append("最高减 <span style=\"color:#fa5555\">")
                    .append(WebUtil.formatAmount(activityResponseDto.getMaxMoney() * 1.00 / 100))
                    .append("</span> 元");
        }
        if (Objects.equals(ActivityTypeEnum.TYPE_12.getCode(), activityResponseDto.getActivityType())) {
            int len = benefitBeanDtos.size();
            // // 购物车中无商品或者存在与满减互斥的活动
            for (int i = len - 1; i >= 0; i--) {
                benefitBeanDto = benefitBeanDtos.get(i);
                messageBuilder.append("满 <span style=\"color:#fa5555\">")
                        .append(WebUtil.formatAmount(benefitBeanDto.getThresholdAmount() * 1.00 / 100))
                        .append("</span> 减 <span style=\"color:#fa5555\">")
                        .append(WebUtil.formatAmount(benefitBeanDto.getDiscountAmount() * 1.00 / 100))
                        .append("</span> 元");
                if (i > 0) messageBuilder.append("，");
            }
        }
    }

    /**
     * 设置加入商品满足购物车时的提示语
     * @param messageBuilder
     * @param activityPrompts
     * @param activityResponseDto
     */
    private void setMessageSatisfyCart(StringBuilder messageBuilder,List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ActivityPrompt> activityPrompts
        ,ActivityResponseDto activityResponseDto){

        ActivityCalculationDiscountResponseDto.CalculationDiscountResult.ActivityPrompt activityPrompt = activityPrompts.get(0);
        if (activityPrompt.getAlreadyDiscountAmount() == null
                || activityPrompt.getAlreadyDiscountAmount() == 0) {
            messageBuilder.append("满 <span style=\"color:#fa5555\">")
                    .append(WebUtil.formatAmount(activityPrompt.getThresholdAmount() * 1.00 / 100))
                    .append("</span> 减 <span style=\"color:#fa5555\">")
                    .append(WebUtil.formatAmount(activityPrompt.getDiscountAmout() * 1.00 / 100))
                    .append("</span> ")
                    .append("还差 <span style=\"color:#fa5555\">")
                    .append(WebUtil.formatAmount((activityPrompt.getThresholdAmount() - activityPrompt.getTotalAmount()) * 1.00 / 100))
                    .append("</span> 元");
        } else {
            Long toDiscountAmout;
            if (Objects.equals(ActivityTypeEnum.TYPE_11.getCode(), activityResponseDto.getActivityType())) {
                toDiscountAmout = activityPrompt.getDiscountAmout() + activityPrompt.getAlreadyDiscountAmount();
            } else {
                toDiscountAmout = activityPrompt.getDiscountAmout();
            }
            messageBuilder.append("已减 <span style=\"color:#fa5555\">")
                    .append(WebUtil.formatAmount(activityPrompt.getAlreadyDiscountAmount() * 1.00 / 100))
                    .append("</span> 元 再买 <span style=\"color:#fa5555\">")
                    .append(WebUtil.formatAmount((activityPrompt.getThresholdAmount() - activityPrompt.getTotalAmount()) * 1.00 / 100))
                    .append("</span> 元减 <span style=\"color:#fa5555\">")
                    .append(WebUtil.formatAmount(toDiscountAmout * 1.00 / 100))
                    .append("</span> 元");
        }
    }

    /**
     * 设置加入商品不满足购物车时的提示语
     * @param messageBuilder
     * @param discountList
     */
    private void setMessageNoSatisfyCart(StringBuilder messageBuilder,List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount> discountList){
        discountList = discountList.parallelStream().filter(k -> (Objects.equals(ActivityTypeEnum.TYPE_11.getCode(), k.getType())
                || Objects.equals(ActivityTypeEnum.TYPE_12.getCode(), k.getType()))).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(discountList)) {
            return;
        }

        messageBuilder.append("已减 <span style=\"color:#fa5555\">")
                .append(WebUtil.formatAmount(discountList.get(0).getDiscount() * 1.00 / 100))
                .append("</span> 元");
    }
}
