package com.ximai.common.utils.data;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.ximai.common.constant.Constants.DateConstant.*;

/**
 * 时间工具类
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {

    public static final String[] DATE_PARSE_PATTERNS = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};


    public static boolean isTimePeriodOverlapping(Date start1, Date end1, Date start2, Date end2) {
//        // 如果区间1的结束时间早于区间2的开始时间，则不交叉
//        if (end1.before(start2)) {
//            return false;
//        }
        // 如果区间2的结束时间早于区间1的开始时间，则不交叉
        return start2.after(end1);
    }

    public static boolean hasTimeOverlap(Date start1, Date end1, Date start2, Date end2) {
        // 如果第一个时间段的结束时间早于第二个时间段的开始时间，则无交集
        if (end1.before(start2)) {
            return false;
        }
        // 如果第二个时间段的结束时间早于第一个时间段的开始时间，则无交集
        if (end2.before(start1)) {
            return false;
        }
        // 否则，两个时间段有交集
        return true;
    }

    public static void main(String[] args) {
//        // 示例：时间区间1 (10:00 AM - 11:00 AM) 与时间区间2 (10:30 AM - 11:30 AM) 交叉
//        Date start1 = new Date(); // 当前时间
//        Date end1 = new Date(); // 当前时间
//        start1.setMinutes(start1.getMinutes() + 60); // 开始时间增加一小时
////        end1.setMinutes(end1.getMinutes() + 70); // 结束时间增加一小时半
//
//        Date start2 = new Date(); // 当前时间
//        Date end2 = new Date(); // 当前时间
//        start2.setMinutes(start2.getMinutes() + 30); // 开始时间增加30分钟
//        end2.setMinutes(end2.getMinutes() + 90); // 结束时间增加一小时半
//        System.out.println("时间区间交叉end1: " + end1 + ", start2:" + start2);
//
//        boolean overlaps = isTimePeriodOverlapping(start1, end1, start2, end2);
//        System.out.println("时间区间交叉: " + overlaps);


//
//        Date date1 = new Date();
//        Date date2 = new Date();
//        List<Date> weekendByMonth = getWeekendByMonth(date1, date2, null);
//        System.out.println(JSONObject.toJSON(weekendByMonth));
    }

    /**
     * 获取日期时间字符串
     *
     * @param date    需要转化的日期时间
     * @param pattern 时间格式
     * @return String 日期时间字符串，例如 2015-08-11 09:51:53
     */
    public static String format(Date date, String pattern) {
        return new SimpleDateFormat(pattern).format(date);
    }

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static String getDateTime(Date date) {
        return parseDateToStr(YYYY_MM_DD_HH_MM_SS, date);
    }


    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }


    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }


    public static Date getDownDateMax(Date downDate) {
//        if (this.downDate != null) {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 指定日期格式
//            String strDate = sdf.format(this.downDate); // 格式化日期为字符串
//            String[] split = strDate.split("-");
////            System.out.println(split);
//            // 假设我们要获取2023年3月10日的最大时间
//            LocalDate date2 = LocalDate.of(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
//
//            // 将LocalDate转换为当天的最后一秒
//            LocalDateTime endOfDay = date2.atTime(LocalTime.MAX);
//            // 将 LocalDateTime 转换为 Instant（时间线上的点）
//            downDateMax= Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
//        }
//        return downDateMax;
        Date downDateMax = null;
        if (downDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(downDate);
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            downDateMax = calendar.getTime();
        }

        return downDateMax;
    }


    public static Date getDownDateMin(Date downDate) {
        Date downDateMin = null;

        if (downDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(downDate);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            downDateMin = calendar.getTime();
        }
        return downDateMin;
    }


    public static Date getUpDateMin(Date upDate) {
        Date upDateMin = null;

        if (upDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(upDate);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            upDateMin = calendar.getTime();
        }
        return upDateMin;
    }

    public static Date getUpDateMax(Date upDate) {
        Date upDateMax = null;
        if (upDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(upDate);
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            upDateMax = calendar.getTime();
        }

        return upDateMax;
    }


    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }


    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), DATE_PARSE_PATTERNS);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }


    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }


    public static List<Date> getWeekendByMonth(Date startDate, Date endDate, List<Integer> execudeDay) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);

        long time = endDate.getTime();

        List<Date> objects = new ArrayList<>();
//        int year = 2022;
//        int month = Calendar.JANUARY;
        do {
            int day = cal.get(Calendar.DAY_OF_WEEK);
            // 验证是否为 星期六或星期天

            if (!execudeDay.contains(day)) {
                objects.add(cal.getTime());
            }
            // 下一天
            cal.add(Calendar.DAY_OF_YEAR, 1);
        } while (cal.getTime().getTime() <= time);

        return objects;
    }

    public static Date formatShiftDate(String dayFormat, String hourFormat) {
        String dateStr = dayFormat + " " + hourFormat;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = null;
        try {
            date = dateFormat.parse(dateStr);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return date;
    }

    public static Date getNextDay(Date startDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        calendar.add(Calendar.DATE, 1); // 在当前日期基础上加一天
        // 获取加一天后的日期
        Date nextDay = calendar.getTime();
        return nextDay;
    }
}
