package com.bonus.canteen.core.marketing.v2.rule.meal.handler.timelimit.extension.impl;

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.toolkit.Wrappers;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.canteen.core.customer.model.CustInfo;
import com.bonus.canteen.core.marketing.v2.mapper.MarketRuleExtMapper;
import com.bonus.canteen.core.marketing.v2.model.MarketRuleExt;
import com.bonus.canteen.core.marketing.v2.rule.meal.handler.timelimit.extension.MealTimeLimitHandlerExtension;
import com.bonus.canteen.core.marketing.vo.MarketRuleVO;
import com.bonus.common.houqin.i18n.I18n;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.invoke.SerializedLambda;
import java.time.LocalTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DefaultMealTimeLimitHandlerImpl implements MealTimeLimitHandlerExtension {
   private static final Logger log = LoggerFactory.getLogger(DefaultMealTimeLimitHandlerImpl.class);
   @Autowired
   private MarketRuleExtMapper marketRuleExtMapper;

   public void handle(CustInfo custInfo, MarketRuleVO ruleInfo) {
      LocalTime now = LocalTime.now();
      List<MarketRuleExt> psnTypeExts = this.marketRuleExtMapper
              .selectList(Wrappers.lambdaQuery(MarketRuleExt.class).eq(MarketRuleExt::getRuleId, ruleInfo.getRuleId()).and((e) -> {
                  e.eq(Objects.nonNull(custInfo.getPsnType())
                 , MarketRuleExt::getPsnType, custInfo.getPsnType()).or(Objects.nonNull(custInfo.getPsnType()))
                 .eq(MarketRuleExt::getPsnType, -1);
      }).le(MarketRuleExt::getStartTime, now).ge(MarketRuleExt::getEndTime, now));
      if (CollUtil.isEmpty(psnTypeExts)) {
         throw new ServiceException(I18n.getMessage("market_meal_error_time", new Object[0]));
      } else {
         List<Long> itemIds = psnTypeExts.stream().map(MarketRuleExt::getItemId).collect(Collectors.toList());
         boolean orgCount = this.marketRuleExtMapper.exists(Wrappers.lambdaQuery(MarketRuleExt.class).eq(MarketRuleExt::getRuleId,
                 ruleInfo.getRuleId()).and((e) -> {e.eq(Objects.nonNull(custInfo.getOrgId()),
            MarketRuleExt::getOrgId, custInfo.getOrgId()).or(Objects.nonNull(custInfo.getOrgId()))
            .eq(MarketRuleExt::getOrgId, -1);
      }).le(MarketRuleExt::getStartTime, now).ge(MarketRuleExt::getEndTime, now).in(MarketRuleExt::getItemId, itemIds));
         if (!orgCount) {
            throw new ServiceException(I18n.getMessage("market_meal_error_time", new Object[0]));
         }
      }
   }

}
