package com.yutou.qqbot.utlis;

import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DateFormatUtils {
    private final Map<String, ThreadLocal<SimpleDateFormat>> formats = new ConcurrentHashMap<>();
    private static volatile DateFormatUtils utils;
    public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";

    private DateFormatUtils() {}

    public static DateFormatUtils getInstance() {
        if (utils == null) {
            synchronized (DateFormatUtils.class) {
                if (utils == null) {
                    utils = new DateFormatUtils();
                }
            }
        }
        return utils;
    }

    public String format(Date date, String format) {
        getFormat(format).applyPattern(format);
        return getFormat(format).format(date);
    }

    public String format(long time, String format) {
        return getFormat(format).format(new Date(time));
    }

    public String format(long time) {
        if (time < 1000000000) {
            time *= 1000;
        }
        return getFormat().format(new Date(time));
    }

    public String format(Date date) {
        return getFormat().format(date);
    }

    public String format() {
        return getFormat().format(new Date());
    }

    public Date parseTimer(String date) {
        return parse(date, "HH:mm:ss");
    }

    public Date parse(String date, String format) {
        try {
            if(date.startsWith("1")){
                return new Date(Long.parseLong(date));
            }
            return getFormat(format).parse(date);
        } catch (ParseException e) {
            System.err.println("Error parsing date: " + e.getMessage());
            return null;
        }
    }

    public String parseString(String date, String format) {
        Date time = parse(date, format);
        return format(time, format);
    }
    public String convertSeconds(long totalSeconds) {
        // 计算总小时数
        long hours = totalSeconds / 3600;
        // 剩余的秒数
        long remainingSecondsAfterHours = totalSeconds % 3600;
        // 计算分钟数
        long minutes = remainingSecondsAfterHours / 60;
        // 最后剩余的秒数
        long seconds = remainingSecondsAfterHours % 60;
        return String.format("%d小时%d分%d秒", hours, minutes, seconds);
    }
    public String formatMillis(long millis) {
        Duration duration = Duration.ofMillis(millis);
        int seconds = (int) (duration.getSeconds() % 60);
        int minutes = (int) ((duration.getSeconds() / 60) % 60);
        int hours = (int) (duration.getSeconds() / 3600);

        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
    public boolean checkTime(List<String> weeks, String recordDate) {
        if (!StringUtils.hasText(recordDate)) {
            recordDate = "00:00:00 - 23:59:59";
        }
        String[] parts = recordDate.split(" - ");
        LocalTime startTime = LocalTime.parse(parts[0], DateTimeFormatter.ofPattern("HH:mm:ss"));
        LocalTime endTime = LocalTime.parse(parts[1], DateTimeFormatter.ofPattern("HH:mm:ss"));


        // 获取当前时间
        LocalTime currentTime = LocalTime.now();
        LocalDate currentDate = LocalDate.now();


        // 获取当前日期对应的星期几（1-7分别对应周一到周日）
        int currentWeekDay = currentDate.getDayOfWeek().getValue();

        // 判断当前日期是否在指定的星期列表中
        boolean isSpecifiedWeekDay;
        if (weeks == null) {
            isSpecifiedWeekDay = true;
        } else {
            isSpecifiedWeekDay = weeks.contains(String.valueOf(currentWeekDay));
        }

        // 判断当前时间是否在指定的时间范围内
        boolean isWithinRange = (currentTime.isAfter(startTime) || currentTime.equals(startTime)) &&
                (currentTime.isBefore(endTime) || currentTime.equals(endTime));
        return isWithinRange && isSpecifiedWeekDay;
    }
    private SimpleDateFormat getFormat() {
        return getFormat(DEFAULT_PATTERN);
    }

    private SimpleDateFormat getFormat(String format) {
        return formats.computeIfAbsent(format, key -> ThreadLocal.withInitial(() -> new SimpleDateFormat(key))).get();
    }
}
