package com.xunmei.common.core.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.xunmei.common.core.domain.DateRange;
import org.apache.commons.lang3.time.DateFormatUtils;

import javax.validation.constraints.NotNull;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 时间工具类
 *
 * @author xunmei
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "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"};

    /**
     * 获取当前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 final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    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 dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

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

    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");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

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

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

    /**
     * 计算时间差
     *
     * @param endTime   最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.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 DateRange getStartAndEnd(Date date, int planCycle) {
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDateTime startDateTime;
        LocalDateTime endDateTime;
        Date startTime;
        Date endTime;
        switch (planCycle) {
            case 1: // day
                startDateTime = localDate.atStartOfDay();
                endDateTime = localDate.atTime(LocalTime.MAX);
                startTime = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant());
                endTime = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant());
                return new DateRange(startTime, endTime);
            case 2: // week
                LocalDate startOfWeek = localDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
                LocalDate endOfWeek = localDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
                startDateTime = startOfWeek.atStartOfDay();
                endDateTime = endOfWeek.atTime(LocalTime.MAX);
                startTime = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant());
                endTime = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant());
                return new DateRange(startTime, endTime);
            case 3: // month
                LocalDate startOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth());
                LocalDate endOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());
                startDateTime = startOfMonth.atStartOfDay();
                endDateTime = endOfMonth.atTime(LocalTime.MAX);
                startTime = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant());
                endTime = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant());
                return new DateRange(startTime, endTime);
            case 4: // quarter
                Month month = localDate.getMonth();
                int quarter = (month.getValue() - 1) / 3 + 1;
                LocalDate startOfQuarter = LocalDate.of(localDate.getYear(), (quarter - 1) * 3 + 1, 1);
                LocalDate endOfQuarter = startOfQuarter.plusMonths(2).with(TemporalAdjusters.lastDayOfMonth());
                startDateTime = startOfQuarter.atStartOfDay();
                endDateTime = endOfQuarter.atTime(LocalTime.MAX);
                startTime = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant());
                endTime = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant());
                return new DateRange(startTime, endTime);
            case 5: // half-year
                int halfYear = (localDate.getMonthValue() - 1) / 6 + 1;
                LocalDate startOfHalfYear = LocalDate.of(localDate.getYear(), (halfYear - 1) * 6 + 1, 1);
                LocalDate endOfHalfYear = startOfHalfYear.plusMonths(5).with(TemporalAdjusters.lastDayOfMonth());
                startDateTime = startOfHalfYear.atStartOfDay();
                endDateTime = endOfHalfYear.atTime(LocalTime.MAX);
                startTime = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant());
                endTime = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant());
                return new DateRange(startTime, endTime);
            case 6: // year
                LocalDate startOfYear = localDate.with(TemporalAdjusters.firstDayOfYear());
                LocalDate endOfYear = localDate.with(TemporalAdjusters.lastDayOfYear());
                startDateTime = startOfYear.atStartOfDay();
                endDateTime = endOfYear.atTime(LocalTime.MAX);
                startTime = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant());
                endTime = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant());
                return new DateRange(startTime, endTime);
            default: // unsupported planCycle
                throw new IllegalArgumentException("Unsupported planCycle: " + planCycle);
        }

    }

    /**
     * 根据次数count等分时间段(不适用于秒级别的时间段分割)
     * 传入:
     * 2023-01-01 00:00:00, 2023-01-01 23:59:59, 6
     * 返回:
     * Key: 1, Start Time: 2023-01-01 00:00:00, End Time: 2023-01-01 03:59:59
     * Key: 2, Start Time: 2023-01-01 04:00:00, End Time: 2023-01-01 07:59:59
     * Key: 3, Start Time: 2023-01-01 08:00:00, End Time: 2023-01-01 11:59:59
     * Key: 4, Start Time: 2023-01-01 12:00:00, End Time: 2023-01-01 15:59:59
     * Key: 5, Start Time: 2023-01-01 16:00:00, End Time: 2023-01-01 19:59:59
     * Key: 6, Start Time: 2023-01-01 20:00:00, End Time: 2023-01-01 23:59:59
     */

    public static Map<Integer, DateRange> splitDateRange(@NotNull Date startTime, @NotNull Date endTime, int count) {
        Map<Integer, DateRange> dateRanges = new HashMap<>();
        long start = startTime.getTime();
        long end = endTime.getTime();
        if (start >= end || (end - start) < 1000L * count) {
            throw new IllegalArgumentException("开始时间不能大于结束时间且单次时间间隔不能小于1秒");
        }
        long interval = (end - start) / count;
        for (int i = 1; i <= count; i++) {
            DateRange dateRange;
            if (i == count) {
                dateRange = new DateRange(new Date(start + (i - 1) * interval), endTime);
            } else {
                dateRange = new DateRange(new Date(start + (i - 1) * interval), new Date(start + i * interval - 1));
            }
            if (ObjectUtil.notEqual(1, i)) {
                dateRange.setStartTime(DateUtil.offsetSecond(dateRange.getStartTime(), 1));
            }
            dateRanges.put(i, dateRange);
        }
        return dateRanges;
    }

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = sdf.parse("2023-01-01 00:00:00");
        Date endDate = sdf.parse("2023-01-01 00:00:02");
        Map<Integer, DateRange> dateRanges = splitDateRange(startDate, endDate, 2);

        for (Map.Entry<Integer, DateRange> entry : dateRanges.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Start Time: " + sdf.format(entry.getValue().getStartTime()) + ", End Time: " + sdf.format(entry.getValue().getEndTime()));
        }
    }
}

