package com.fs.sop.util;

import com.fs.course.config.CourseConfig;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class TimeCalculator {

    // 计算可用时间段的入口方法
    public static List<String> calculateAvailableTimes(List<CourseConfig.DisabledTimeVo> disabledTimeList) {
        List<CourseConfig.DisabledTimeVo> merged = mergeTimeRanges(disabledTimeList);
        List<String> availableTimes = new ArrayList<>();
        LocalTime prevEnd = LocalTime.MIN; // 初始化为00:00

        for (CourseConfig.DisabledTimeVo interval : merged) {
            LocalTime currentStart = interval.getStartDisabledTime();
            LocalTime currentEnd = interval.getEndDisabledTime();

            // 计算两个禁用时间段之间的间隙
            if (currentStart.isAfter(prevEnd)) {
                LocalTime availableStart = prevEnd.plusMinutes(1);
                LocalTime availableEnd = currentStart.minusMinutes(1);
                if (!availableStart.isAfter(availableEnd)) {
                    availableTimes.add(formatTimeRange(availableStart, availableEnd));
                }
            }
            // 更新prevEnd为较大的currentEnd
            prevEnd = prevEnd.isBefore(currentEnd) ? currentEnd : prevEnd;
        }

        // 处理最后一个禁用时间段之后的时间（直到23:59）
        LocalTime dayEnd = LocalTime.of(23, 59);
        if (prevEnd.isBefore(dayEnd)) {
            LocalTime availableStart = prevEnd.plusMinutes(1);
            availableTimes.add(formatTimeRange(availableStart, dayEnd));
        }

        return availableTimes;
    }

    // 合并重叠或相邻的时间段
    private static List<CourseConfig.DisabledTimeVo> mergeTimeRanges(List<CourseConfig.DisabledTimeVo> disabledTimeList) {
        if (disabledTimeList.isEmpty()) return new ArrayList<>();

        // 1. 按开始时间排序
        List<CourseConfig.DisabledTimeVo> sorted = disabledTimeList.stream()
                .sorted(Comparator.comparing(CourseConfig.DisabledTimeVo::getStartDisabledTime))
                .collect(Collectors.toList());

        // 2. 合并时间段
        List<CourseConfig.DisabledTimeVo> merged = new ArrayList<>();
        CourseConfig.DisabledTimeVo current = copy(sorted.get(0));
        merged.add(current);

        for (int i = 1; i < sorted.size(); i++) {
            CourseConfig.DisabledTimeVo next = sorted.get(i);
            // 如果下一个时间段的开始 <= 当前时间段的结束，合并
            if (!next.getStartDisabledTime().isAfter(current.getEndDisabledTime())) {
                LocalTime newEnd = next.getEndDisabledTime().isAfter(current.getEndDisabledTime())
                        ? next.getEndDisabledTime()
                        : current.getEndDisabledTime();
                current.setEndDisabledTime(newEnd);
            } else {
                current = copy(next);
                merged.add(current);
            }
        }
        return merged;
    }

    // 辅助方法：复制对象以避免修改原始数据
    private static CourseConfig.DisabledTimeVo copy(CourseConfig.DisabledTimeVo source) {
        CourseConfig.DisabledTimeVo target = new CourseConfig.DisabledTimeVo();
        target.setStartDisabledTime(source.getStartDisabledTime());
        target.setEndDisabledTime(source.getEndDisabledTime());
        return target;
    }

    // 格式化时间段为"HH:mm:ss - HH:mm:ss"
    private static String formatTimeRange(LocalTime start, LocalTime end) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        return start.format(formatter) + " - " + end.format(formatter);
    }
}