package com.bonus.core.marketing.v2.constants;

import cn.hutool.core.collection.CollUtil;
import com.bonus.core.marketing.util.EnumUtil;
import com.bonus.core.marketing.util.ICommonEnum;
import com.bonus.core.marketing.v2.rule.param.RuleRangeParam;
import com.bonus.core.marketing.v2.vo.MarketRuleDetailVO;

import java.time.LocalTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public enum MarketEffectTimeEnum implements ICommonEnum {
   TIME_NO_LIMIT(1, "不限") {
      public boolean exec(RuleRangeParam param, MarketRuleDetailVO detail) {
         return true;
      }
   },
   TIME_LIMIT(2, "指定日期") {
      public boolean exec(RuleRangeParam param, MarketRuleDetailVO detail) {
         return param.getTradeDate().compareTo(detail.getEffectBeginTime()) >= 0 && param.getTradeDate().compareTo(detail.getEffectEndTime()) <= 0;
      }
   },
   TIME_PERIOD_LIMIT(3, "指定时间") {
      public boolean exec(RuleRangeParam param, MarketRuleDetailVO detail) {
         List<String> timeValues = detail.getEffectTimeValue();
         if (CollUtil.isEmpty(timeValues)) {
            return true;
         } else {
            LocalTime time = param.getOrderTime().toLocalTime();
            Optional<String> optional = timeValues.stream().filter((t) -> {
               String[] split = t.split("~");
               LocalTime beginTime = LocalTime.parse(split[0]);
               LocalTime endTime = LocalTime.parse(split[1]);
               return time.compareTo(beginTime) >= 0 && time.compareTo(endTime) <= 0;
            }).findFirst();
            return optional.isPresent();
         }
      }
   };

   private final Integer key;
   private final String value;

   public abstract boolean exec(RuleRangeParam param, MarketRuleDetailVO detail);

   public static boolean operate(RuleRangeParam param, MarketRuleDetailVO detail) {
      MarketEffectTimeEnum timeEnum = (MarketEffectTimeEnum) EnumUtil.getEnumByKey(MarketEffectTimeEnum.class, detail.getEffectTimeType());
      return !Objects.isNull(timeEnum) && timeEnum.exec(param, detail);
   }

   @Override
   public Integer getKey() {
      return this.key;
   }

   @Override
   public String getValue() {
      return this.value;
   }

   private MarketEffectTimeEnum(final Integer key, final String value) {
      this.key = key;
      this.value = value;
   }

   // $FF: synthetic method
   private static MarketEffectTimeEnum[] $values() {
      return new MarketEffectTimeEnum[]{TIME_NO_LIMIT, TIME_LIMIT, TIME_PERIOD_LIMIT};
   }
}
