package com.emergency.avenue.common.core.util;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

import static java.time.temporal.TemporalAdjusters.nextOrSame;

/**
 * @author lixingxing
 * @data 2023/6/9 16:32
 **/
public class HalfHourCalculator {

	public static LocalDateTime hourCalculator(String inputTime) {
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime time = LocalDateTime.parse(inputTime, formatter);

		// 排除节假日、周六日和每天下午6点到第二天上午9点
		while (isHoliday(time.toLocalDate()) || isWeekend(time.getDayOfWeek())
				|| isOfftime1(time.toLocalTime())
				|| isOfftime2(time.toLocalTime())) {
			time = time.plusMinutes(30); // 时间加 30 分钟
		}

		// 计算半小时后的时间
		LocalDateTime halfHourLater = time.plusMinutes(30);

		// 输出结果，格式为 yyyy-MM-dd HH:mm:ss
		System.out.println("Half hour later: " + halfHourLater.format(formatter));
		return halfHourLater;
	}

	public static void main(String[] args) {
		// 输入待计算时间字符串，格式为 yyyy-MM-dd HH:mm:ss
		String inputTime = "2023-06-10 11:30:00";
		LocalDateTime s = hourCalculator(inputTime);
		System.out.println(s);
	}

	// 判断是否为节假日（这里只列举了春节节假日）
	private static boolean isHoliday(LocalDate date) {
		int year = date.getYear();
		LocalDate springFestivalStart = LocalDate.of(year, 2, 1).with(nextOrSame(DayOfWeek.MONDAY));
		LocalDate springFestivalEnd = LocalDate.of(year, 2, 1).with(nextOrSame(DayOfWeek.SATURDAY)).plusDays(2);
		return date.isAfter(springFestivalStart) && date.isBefore(springFestivalEnd);
	}

	// 判断是否为周末
	private static boolean isWeekend(DayOfWeek dayOfWeek) {
		return dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY;
	}

	// 判断是否为下班时间（每天下午6点到第二天上午9点）
	private static boolean isOfftime1(LocalTime time) {
		LocalTime offTimeStart = LocalTime.of(18, 0);
		LocalTime offTimeEnd = LocalTime.of(9, 0).plusHours(24);
		return time.isAfter(offTimeStart) || time.isBefore(offTimeEnd);
	}

	// 判断是否为下班时间（每天下午6点到第二天上午9点）
	private static boolean isOfftime2(LocalTime time) {
		LocalTime offTimeStart = LocalTime.of(11, 0);
		LocalTime offTimeEnd = LocalTime.of(13, 0);
		return time.isAfter(offTimeStart) && time.isBefore(offTimeEnd);
	}
}
