package cn.freemud.service.impl;

import cn.freemud.entities.dto.ActivityResponseDto;
import cn.freemud.entities.dto.BenefitBeanDto;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.activity.ActivityQueryResponseDto;
import cn.freemud.entities.dto.promotion.*;
import cn.freemud.entities.vo.ActivityTip;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.service.ActivityService;
import cn.freemud.service.IPromotionService;
import cn.freemud.utils.WebUtil;
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;

@Service
public class FullPromotionService implements IPromotionService {

    @Autowired
    private ActivityService activityService;

    @Override
    public void updateDiscountApportion(ShoppingCartGoodsResponse shoppingCartGoodsResponse, OrderBeanRequest request, CalculationDiscountResultDto calculationDiscountResult, CouponPromotionDto couponPromotionDto, ActivityQueryDto activityQueryDto) {
        this.buildActivityTip(shoppingCartGoodsResponse, calculationDiscountResult, activityQueryDto);

        List<CalculationGoodsActivityDto> discountList = (calculationDiscountResult == null || calculationDiscountResult.getDiscounts() == null) ? new ArrayList<>() : calculationDiscountResult.getDiscounts();
        if(CollectionUtils.isEmpty(discountList)){
            return;
        }
        //过滤出参与的满减(目前只有每满减和阶梯满减)
        List<CalculationGoodsActivityDto> 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 (CalculationGoodsActivityDto fullDiscounts : fullDiscountsList) {
            fullDiscount = fullDiscount + (fullDiscounts.getDiscount() == null ? 0 : fullDiscounts.getDiscount());
        }
        shoppingCartGoodsResponse.setFullDiscount(fullDiscount);
    }

    private void buildActivityTip(ShoppingCartGoodsResponse shoppingCartGoodsResponse, CalculationDiscountResultDto calculationDiscountResult, ActivityQueryDto activityQueryDto) {
        shoppingCartGoodsResponse.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 ;
        }
        ActivityResponseDto activityResponseDto = activityQueryDtoList.get(0);
        //促销返回满减提示语
        StringBuilder messageBuilder = new StringBuilder();
        List<CalculationActivityPromptDto> activityPrompts = calculationDiscountResult.getActivityPrompts();
        List<CalculationGoodsActivityDto> discountList1 = calculationDiscountResult.getDiscounts();

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

        ActivityTip activityTip = new ActivityTip();
        activityTip.setActivityCode(activityResponseDto.getActivityCode());
        activityTip.setActivityType(activityResponseDto.getActivityType());
        activityTip.setActivityName(messageBuilder.toString());
        shoppingCartGoodsResponse.setActivityTip(activityTip);
    }

    //设置没有加入购物车的提示语
    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, j = 0; i >= 0 && j < 2; i--, j++) {
                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> 元");
            }
        }
    }

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

        CalculationActivityPromptDto 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 {
            Integer 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<CalculationGoodsActivityDto> 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> 元");
    }
}
