package com.jeequan.jeepay.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.db.entity.SysLegalDay;
import com.jeequan.jeepay.service.mapper.SysLegalDayMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 法定节假日配置表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2023-09-26
 */
@Service
public class SysLegalDayService extends ServiceImpl<SysLegalDayMapper, SysLegalDay> {

    /**
     * 获取某个日期的（T+N）的结果
     */
     public Date getTnDate(Date currentDate, int dayN) {

         if (dayN <= 0) {
             return currentDate;
         }

         // 大于传入日期的所有假期
         List<SysLegalDay> list = list(SysLegalDay.gw()
                 .ge(SysLegalDay::getDateValue, currentDate)
         );

         if (CollUtil.isEmpty(list)) {
             return DateUtil.offsetDay(currentDate, dayN);
         }

         // 节假日集合
         List<String> holidayList = new ArrayList<>();
         // 工作日集合
         List<String> workdayList = new ArrayList<>();

         for (SysLegalDay sysLegalDay : list) {
             if (SysLegalDay.DATE_TYPE_HOLIDAY.equals(sysLegalDay.getDateType())) {
                 holidayList.add(DateUtil.formatDate(sysLegalDay.getDateValue()));

             }else if (SysLegalDay.DATE_TYPE_WORKDAY.equals(sysLegalDay.getDateType())) {
                 workdayList.add(DateUtil.formatDate(sysLegalDay.getDateValue()));
             }
         }


         // 节假日/周末产生的日期偏移
        int holidayOffset = 0;

         // 循环日期
         for (int i = 1; i < (dayN + holidayOffset + 1); i++) {
            // 日期偏移
             DateTime offsetDay = DateUtil.offsetDay(currentDate, i);
             String offsetDayStr = DateUtil.formatDate(offsetDay);

             // 周末，正常需偏移，如果是工作日，则不计入节假日偏移
             if (DateUtil.isWeekend(offsetDay)) {
                if (!workdayList.contains(offsetDayStr)) {
                    holidayOffset++;
                }
             }
             // 周一到周五，包含节假日，偏移一天；
             else {
                 if (holidayList.contains(offsetDayStr)) {
                     holidayOffset++;
                 }
             }
         }

         return DateUtil.offsetDay(currentDate, dayN + holidayOffset);
     }

}
