package com.bonus.canteen.core.allocation.api;

import cn.hutool.core.date.DateUtil;
import com.bonus.canteen.core.allocation.holiday.service.MktHolidayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
public class AllocHolidayApi {
   private static final Logger log = LoggerFactory.getLogger(AllocHolidayApi.class);
   @Autowired
   @Lazy
   private MktHolidayService mktHolidayService;

   public List<LocalDate> getHolidayList() {
      int currentYear = DateUtil.year(DateUtil.date());
      List<Date> holidayList = this.mktHolidayService.getHolidayList(currentYear);
      List<LocalDate> localDateList = new ArrayList();
      LocalDate today = LocalDate.now();
      Iterator var5 = holidayList.iterator();

      while(true) {
         LocalDate localDate;
         do {
            if (!var5.hasNext()) {
               LocalDate afterMonthToday = today.plusDays(30L);
               if (today.getYear() != afterMonthToday.getYear()) {
                  holidayList = this.mktHolidayService.getHolidayList(currentYear + 1);
                  Iterator var9 = holidayList.iterator();

                  while(var9.hasNext()) {
                     Date date = (Date)var9.next();
                     localDateList.add(date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
                  }
               }

               return localDateList;
            }

            Date date = (Date)var5.next();
            localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
         } while(!localDate.isAfter(today) && !localDate.isEqual(LocalDate.now()));

         localDateList.add(localDate);
      }
   }

   public Integer getHolidayType(LocalDate searchDate) {
      return this.mktHolidayService.getHolidayType(searchDate);
   }

   public LocalDate getWeekdayDeadLine(LocalDate assignDate, Integer days, boolean skipHolidayFlag) {
      log.info("查询日期:{},跳过天数:{},是否跳过节假日:{}", new Object[]{assignDate, days, skipHolidayFlag});
      if (!skipHolidayFlag) {
         return assignDate.plusDays((long)days);
      } else {
         List<LocalDate> holidayList = this.getHolidayList();
         int skipDay = 0;

         while(skipDay < Math.abs(days)) {
            if (days > 0) {
               assignDate = assignDate.plusDays(1L);
            } else {
               assignDate = assignDate.minusDays(1L);
            }

            if (!holidayList.contains(assignDate)) {
               ++skipDay;
            }
         }

         return assignDate;
      }
   }
}
