package com.hw.common.core.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;

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

/**
 * 时间工具类
 *
 * @author ruoyi
 */
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 endDate 最后时间
     * @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());
    }
    /**
     * 判断String是否为："yyyy-MM-dd HH:mm:ss"
     * @param input
     * @return
     */
    public static boolean isFormatValid(String input) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        try {
            dateFormat.parse(input);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    public static List<String> getDatesBetween(String startDateStr, String endDateStr) {

        List<String> dates = new ArrayList<>();
        if(!isFormatValid(startDateStr)){
            startDateStr =  startDateStr + " 00:00:00";
            endDateStr =  endDateStr + " 23:59:59";
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startDate = LocalDateTime.parse(startDateStr, formatter);
        LocalDateTime endDate = LocalDateTime.parse(endDateStr, formatter);

        LocalDate currentDate = startDate.toLocalDate();

        while (!currentDate.isAfter(endDate.toLocalDate())) {
            dates.add(currentDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
            currentDate = currentDate.plusDays(1);
        }
        return dates;
    }

    public static List<String> getSortedMonthList(List<String> dates, String type) {
        List<Date> dateList = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (String dateStr : dates) {
            try {
                Date date = dateFormat.parse(dateStr);
                dateList.add(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        Collections.sort(dateList);
        List<String> monthList = new ArrayList<>();
        SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");
        if (type.equals("year")){
            monthFormat = new SimpleDateFormat("yyyy");
        }
        for (Date date : dateList) {
            String monthStr = monthFormat.format(date);
            if (!monthList.contains(monthStr)) {
                monthList.add(monthStr);
            }
        }
        return monthList;
    }

    /**
     * 两个日期之间的每个小时的整点时间
     * @param startDateStr
     * @param endDateStr
     * @return
     */
    public static List<String> getHourlyIntervals(String startDateStr, String endDateStr) {
        List<String> intervals = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startDate = LocalDateTime.parse(startDateStr, formatter);
        LocalDateTime endDate = LocalDateTime.parse(endDateStr, formatter);
        LocalDateTime currentHour = startDate.withMinute(0).withSecond(0);
        while (currentHour.isBefore(endDate)) {
            intervals.add(currentHour.format(formatter));
            currentHour = currentHour.plusHours(1);
        }
        return intervals;
    }

    /**
     * 获取去年的当前月日时间，格式为"yyyy-MM-dd HH:mm:ss"
     * @param inputStr
     * @return
     */
    public static String getLastYearMonthDayTime(String inputStr) {
        // 将字符串转换为LocalDateTime对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dt = LocalDateTime.parse(inputStr, formatter);
        // 获取去年的同一天
        LocalDateTime lastYearDt = dt.minusYears(1);
        // 格式化输出字符串
        return lastYearDt.format(formatter);
    }


    /**
     * 按type输出时间间隔List
     * 小时 天 月 年
     * @param startTime
     * @param endTime
     * @param type
     * @return
     */
    public static List<String> getTimeList(String startTime, String endTime, String type) {
        DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:00:00");
        DateTimeFormatter DAY_FORMATTER = DateTimeFormatter.ofPattern("MM-dd");
        DateTimeFormatter MONTH_FORMATTER = DateTimeFormatter.ofPattern("MM");
        DateTimeFormatter YEAR_FORMATTER = DateTimeFormatter.ofPattern("yyyy");
        LocalDateTime startDateTime = LocalDateTime.parse(startTime.substring(0,13) + ":00:00", DATE_TIME_FORMATTER);
        LocalDateTime endDateTime = LocalDateTime.parse(endTime.substring(0,13) + ":00:00", DATE_TIME_FORMATTER);
        List<String> timeList = new ArrayList<>();
        switch(type) {
            case "hour":
                while(startDateTime.isBefore(endDateTime)) {
                    timeList.add(startDateTime.format(DATE_TIME_FORMATTER));
                    startDateTime = startDateTime.plusHours(1);
                }
                break;
            case "day":
                while(startDateTime.isBefore(endDateTime)) {
                    timeList.add(startDateTime.format(DAY_FORMATTER));
                    startDateTime = startDateTime.plusDays(1);
                }
                break;
            case "month":
                while(startDateTime.isBefore(endDateTime)) {
                    timeList.add(startDateTime.format(MONTH_FORMATTER));
                    startDateTime = startDateTime.plusMonths(1);
                }
                break;
            case "year":
                while(startDateTime.isBefore(endDateTime)) {
                    timeList.add(startDateTime.format(YEAR_FORMATTER));
                    startDateTime = startDateTime.plusYears(1);
                }
                break;
            default:
                throw new IllegalArgumentException("Invalid type: " + type);
        }
        return timeList;
    }

    public static Map<String, String> getStartAndEndTime() {
        Map<String, String> resultMap = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();
        LocalDate today = LocalDate.now();
        LocalDate lastMonth = now.minusMonths(1).toLocalDate();
        LocalDate lastYear = now.minusYears(1).toLocalDate();

        resultMap.put("todayStart", now.with(LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        resultMap.put("todayEnd", now.with(LocalTime.MAX).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        resultMap.put("monthStart", now.withDayOfMonth(1).with(LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        resultMap.put("monthEnd", now.withDayOfMonth(today.lengthOfMonth()).with(LocalTime.MAX).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        resultMap.put("yearStart", now.withDayOfYear(1).with(LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        resultMap.put("yearEnd", now.withDayOfYear(today.lengthOfYear()).with(LocalTime.MAX).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        resultMap.put("weekStart", now.with(DayOfWeek.MONDAY).with(LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        resultMap.put("weekEnd", now.with(DayOfWeek.SUNDAY).with(LocalTime.MAX).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // 上月的开始和结束时间
        resultMap.put("lastMonthStart", now.minusMonths(1).withDayOfMonth(1).with(LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        resultMap.put("lastMonthEnd", now.withDayOfMonth(1).minusDays(1).with(LocalTime.MAX).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // 去年的开始和结束时间
        resultMap.put("lastYearStart", now.minusYears(1).withDayOfYear(1).with(LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        resultMap.put("lastYearEnd", now.minusYears(1).withDayOfYear(lastYear.minusYears(1).lengthOfYear()).with(LocalTime.MAX).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // 去年当月的开始和结束时间
        LocalDateTime nowNew = LocalDateTime.now();
        LocalDate lastYearMonth = LocalDate.now().minusYears(1).withMonth(nowNew.getMonthValue());
        resultMap.put("lastYearMonthStart", now.minusYears(1).withDayOfMonth(1).with(LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        resultMap.put("lastYearMonthEnd", now.minusYears(1).withDayOfMonth(today.lengthOfMonth()).with(LocalTime.MAX).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return resultMap;
    }

    public static String getYesterday(String timeStr) {
        if(!isFormatValid(timeStr)){
            timeStr =  timeStr + " 00:00:00";
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(timeStr, formatter);
        LocalDate date = dateTime.toLocalDate().minusDays(1);
        return date.atTime(dateTime.toLocalTime()).format(formatter);
    }

    public static String getLastYear(String timeStr) {
        if(!isFormatValid(timeStr)){
            timeStr =  timeStr + " 00:00:00";
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(timeStr, formatter);
        LocalDateTime lastYearDateTime = dateTime.minusYears(1);
        return lastYearDateTime.format(formatter);
    }

}
