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

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.common.houqin.constant.LeConstants;
import com.bonus.canteen.core.marketing.v2.mapper.MarketRuleRecordMapper;
import com.bonus.canteen.core.marketing.v2.model.MarketRuleRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;


@Service
public class MarketRuleRecordService extends ServiceImpl<MarketRuleRecordMapper, MarketRuleRecord> {
   private static final Logger log = LoggerFactory.getLogger(MarketRuleRecordService.class);

   public void disableRecord(List<Long> tradeIds) {
      if (!CollUtil.isEmpty(tradeIds)) {
         this.update(Wrappers.lambdaUpdate(MarketRuleRecord.class)
                 .in(MarketRuleRecord::getTradeId, tradeIds).set(MarketRuleRecord::getEffectFlag, LeConstants.COMMON_NO));
      }
   }

   public List<MarketRuleRecord> getRuleRecordByRule(Long custId, LocalDate beginDate, LocalDate endDate, List<Integer> mealtimeTypeList, List<Long> ruleIds) {
      return this.getRuleRecordByRuleByEffectFlag(custId, beginDate, endDate, mealtimeTypeList, ruleIds, LeConstants.COMMON_YES);
   }

   public List<MarketRuleRecord> getRuleRecordByRuleByEffectFlag(Long custId, LocalDate beginDate, LocalDate endDate, List<Integer> mealtimeTypeList, List<Long> ruleIds, Integer effectFlag) {
      List<Integer> mealtimes = CollUtil.isEmpty(mealtimeTypeList) ? null : (List)mealtimeTypeList.stream().filter(Objects::nonNull).collect(Collectors.toList());
      return Optional.ofNullable(this.list(Wrappers.lambdaQuery(MarketRuleRecord.class).eq(MarketRuleRecord::getCustId, custId).in(CollUtil.isNotEmpty(ruleIds), MarketRuleRecord::getRuleId, ruleIds).eq(Objects.nonNull(effectFlag), MarketRuleRecord::getEffectFlag, effectFlag).between(Objects.nonNull(beginDate) && Objects.nonNull(endDate), MarketRuleRecord::getTradeDate, beginDate, endDate).in(CollUtil.isNotEmpty(mealtimes), MarketRuleRecord::getMealtimeType, mealtimes))).orElse(CollUtil.newArrayList(new MarketRuleRecord[0]));
   }
}
