package com.tuoheng.common.utils;

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

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 时间工具类
 */
public final 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"};


    /**
     * 获取当前时间
     *
     * @return
     */
    public static Date now() {
        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);
    }

    /**
     * 计算两个时间差
     */
    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 + "分钟";
    }

    /**
     * 指定日期字符串加/减指定月数
     * @param dataTime
     * @param months
     * @return
     * @throws ParseException
     */
    public static Date getLastMonthDate(String dataTime,int months) throws ParseException {
        //时间字符串转 LocalDate 类型
        LocalDate today = LocalDate.parse(dataTime, DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
        //当前月份+（-1）
        today = today.plusMonths(months);
        Instant instant = today.atTime(LocalTime.MIDNIGHT).atZone(ZoneId.systemDefault()).toInstant();
        Date date = Date.from(instant);
        return date;

    }

    /**
     * 计算下一个循环周期
     *
     * @param beginDate 开始日期：格式yyyy-MM-dd HH:mm:ss
     * @param cycleType 周期类型0-每周 1-每月
     * @param cycleDate 循环日期：如果周期类型是每周，那么循环日期日期值范围为：1-7，如果周期类型为每月，那么周期日期值范围为：1-31
     * @return
     * @throws ParseException
     */
    public static String getNextCycleDay(String beginDate, String cycleType, String cycleDate) throws ParseException {
        if (StringUtils.isNotEmpty(cycleType) && "0".equals(cycleType)) {
            if (StringUtils.isNotEmpty(cycleDate) && (Integer.valueOf(cycleDate) < 0 || Integer.valueOf(cycleDate) > 7)) {
                throw new RuntimeException("循环周期类型为周，循环日期只能再1~7范围内！");
            }
        } else if (StringUtils.isNotEmpty(cycleType) && "1".equals(cycleType)) {
            if (StringUtils.isNotEmpty(cycleDate) && (Integer.valueOf(cycleDate) < 0 || Integer.valueOf(cycleDate) > 31)) {
                throw new RuntimeException("循环周期类型为月，循环日期只能再1~31范围内！");
            }
        }

        Date dateBegin = DateUtils.parseDate(beginDate, YYYY_MM_DD_HH_MM_SS);
        String beginDateTime = DateUtils.parseDateToStr("HH:mm:ss", dateBegin);//开始时间点
        String nextDate = "";//下一个日期
        Date date = null;

        String today = DateUtils.getDate();//获取今天的日期
        //开始日期大于当前，取开始日期进行比较，否则取当天进行比较
        if (beginDate.compareTo(today) > 0) {
            date = DateUtils.parseDate(beginDate, YYYY_MM_DD_HH_MM_SS);
        } else {
            date = new Date();
        }
        if ("0".equals(cycleType)) {
            //每周
            //如果指定周几大于今天所属的周几，则取本周的周几
            //如果指定周几小于今天所属的周几，则取下个周的周几
            Calendar cal = Calendar.getInstance(Locale.CHINA);
            cal.setTime(date);
            cal.setFirstDayOfWeek(Calendar.MONDAY);//将每周第一天设为星期一，默认是星期天
            int week = cal.get(Calendar.DAY_OF_WEEK) - 1;//获取指定日期的周几
            if (week == 0) week = 7;
            if (Integer.valueOf(cycleDate) >= week) {//如果指定的周几大于等于当前周几，去本周的周几
                cal.set(Calendar.DAY_OF_WEEK, Integer.valueOf(cycleDate) + 1);//星期
            } else {
                cal.add(Calendar.WEEK_OF_MONTH, 1);//周数加1，即下周
                cal.set(Calendar.DAY_OF_WEEK, Integer.valueOf(cycleDate) + 1);//星期
            }
            nextDate = DateUtils.parseDateToStr(YYYY_MM_DD, cal.getTime());
        } else if ("1".equals(cycleType)) {
            //每月
            //如果指定每月几号大于等于今天所属几号，则取本月的几号
            //如果指定每月几号小于今天所属几号，则取下个月的几号
            if (cycleDate.length() == 1) {
                cycleDate = "0" + cycleDate;
            }
            if (Integer.valueOf(cycleDate) >= Integer.valueOf(DateUtils.parseDateToStr("dd", date))) {
                while (true) {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(date);
                    //如果当月最大天数小于指定的每月几号，则取下一个月的几号，直到找到对应月数有对应的几号为止
                    if (cal.getActualMaximum(Calendar.DATE) < Integer.valueOf(cycleDate)) {
                        date = DateUtils.getLastMonthDate(DateUtils.parseDateToStr(YYYY_MM_DD_HH_MM_SS, date), 1);
                    } else {
                        break;
                    }
                }
                nextDate = DateUtils.parseDateToStr("yyyy-MM", date) + "-" + cycleDate;
            } else {
                Date lastMonthDate = DateUtils.getLastMonthDate(DateUtils.parseDateToStr(YYYY_MM_DD_HH_MM_SS, date), 1);
                nextDate = DateUtils.parseDateToStr("yyyy-MM", lastMonthDate) + "-" + cycleDate;
            }
        }

        return nextDate + " " + beginDateTime;
    }

    /**
     * 获取日期列表中离当前日期最近的一个日期
     * @param dateList
     * @return
     */
    public static String getLatstDate(List<Date> dateList){

        final long now = System.currentTimeMillis();
        // Get date closest to "now"
        Date closest = Collections.min(dateList, new Comparator<Date>() {
            public int compare(Date d1, Date d2) {
                long diff1 = Math.abs(d1.getTime() - now);
                long diff2 = Math.abs(d2.getTime() - now);
                return Long.compare(diff1, diff2);
            }
        });
        return DateUtils.parseDateToStr(YYYY_MM_DD_HH_MM_SS, closest);
    }

    public static void main(String[] args) {
        String beginDate = "2023-05-04 12:12:12";
        try {
            System.out.println("最近下一个周：" + getNextCycleDay(beginDate,"0","7"));
            System.out.println("最近下一个月：" + getNextCycleDay(beginDate,"1","31"));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        List<Date> list = new ArrayList<>();
        list.add(DateUtils.dateTime(YYYY_MM_DD_HH_MM_SS,"2023-05-12 12:00:00"));
        list.add(DateUtils.dateTime(YYYY_MM_DD_HH_MM_SS,"2023-06-12 12:00:00"));
        list.add(DateUtils.dateTime(YYYY_MM_DD_HH_MM_SS,"2023-07-12 11:00:00"));
        System.out.println(getLatstDate(list));
    }
}
