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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.core.marketing.v2.constants.MarketRangeTypeEnum;
import com.bonus.core.marketing.v2.mapper.MarketRuleRangeMapper;
import com.bonus.core.marketing.v2.model.MarketRuleRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import cn.hutool.core.text.CharSequenceUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class MarketRuleRangeService extends ServiceImpl<MarketRuleRangeMapper, MarketRuleRange> {
   private static final Logger log = LoggerFactory.getLogger(MarketRuleRangeService.class);

   public List<MarketRuleRange> getRangeByRuleId(Long ruleId) {
      return Optional.ofNullable(this.list(Wrappers.<MarketRuleRange>lambdaQuery()
        .eq(MarketRuleRange::getRuleId, ruleId))).orElseGet(ArrayList::new);
   }

   public List filterRangeDetailByType(List<MarketRuleRange> rangeList, MarketRangeTypeEnum rangeType) {
      Function<MarketRuleRange, Object> func1 = null;
      switch (rangeType) {
         case RANGE_DEVICE:
            func1 = MarketRuleRange::getCustomSn;
            break;
         case RANGE_MEALTIME:
            func1 = MarketRuleRange::getMealtimeType;
            break;
         case RANGE_ORGANIZATION:
            func1 = MarketRuleRange::getOrgId;
            break;
         case RANGE_PERSON:
            func1 = MarketRuleRange::getPsnType;
            break;
         case RANGE_AGE:
            func1 = MarketRuleRange::getAgeType;
            break;
         case RANGE_PAY_CHANNEL:
            func1 = MarketRuleRange::getPayChannel;
            break;
         default:
            break;
      }

      if (Objects.isNull(func1)) {
         throw new ServiceException("【消费规则】范围类型错误");
      } else {
         return (List)rangeList.stream().filter((e) -> {
            return Objects.equals(e.getRangeType(), rangeType.getKey());
         }).map(func1).filter((e) -> {
            return !CharSequenceUtil.equals(e.toString(), "-1");
         }).collect(Collectors.toList());
      }
   }

}
