package com.bonus.canteen.core.marketing.v2.rule.recharge.handler.managecost.extension;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.canteen.core.marketing.v2.rule.recharge.constants.RuleRechargeComputeTypeEnum;
import com.bonus.canteen.core.marketing.v2.rule.recharge.constants.RuleRechargeEnum;
import com.bonus.canteen.core.marketing.v2.rule.recharge.constants.RuleRechargeTypeEnum;
import com.bonus.canteen.core.marketing.v2.rule.recharge.handler.RuleRechargeHandler;
import com.bonus.canteen.core.marketing.v2.rule.recharge.handler.managecost.dto.RechargeCostDTO;
import com.bonus.canteen.core.marketing.v2.rule.recharge.handler.managecost.dto.RechargeCostItemDTO;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

public interface RechargeCostHandlerExtension extends RuleRechargeHandler {
   @Override
   default Integer getRuleType() {
      return RuleRechargeEnum.RULE_MANAGE_COST.getKey();
   }

   @Override
   default void checkRuleInfo(String ruleInfo) {
      RechargeCostDTO rule = (RechargeCostDTO)JSONObject.parseObject(ruleInfo, RechargeCostDTO.class);
      List<RechargeCostItemDTO> items = rule.getItems();
      if (CollUtil.isEmpty(items)) {
         throw new ServiceException("规则配置有误");
      } else {
         List<RechargeCostItemDTO> errorItems = (List)items.stream().filter((e) -> {
            return RuleRechargeComputeTypeEnum.COMPUTE_TYPE_AMOUNT.getKey().equals(e.getComputeType()) && e.getDiscount().compareTo(e.getDoorAmount()) > 0;
         }).collect(Collectors.toList());
         if (CollUtil.isNotEmpty(errorItems)) {
            throw new ServiceException("管理费设置有误");
         } else {
            List<RechargeCostItemDTO> errorDoorAmountItems = (List)items.stream().filter((e) -> {
               return RuleRechargeTypeEnum.RECHARGE_TYPE_CYCLE.getKey().equals(rule.getRechargeType()) && e.getDoorAmount().compareTo(BigDecimal.ZERO) <= 0;
            }).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(errorDoorAmountItems)) {
               throw new ServiceException("管理费门槛金额设置有误");
            }
         }
      }
   }
}
