package com.fufan.mtsaas.util;

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

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

/**
 * 时间工具类
 *
 */
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 YYYYMM = "yyyyMM";

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

    public static String MMDD_1 = "M月d号";
    public static String MMDD_2 = "M月d日";
    public static String MMDD_3 = "M.d";
    public static String MMDD_4 = "M月dd日";
    public static String MMDD_5 = "MMdd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

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

    public static String YYYYYMMM = "yyyy年M月";

    public static String YYYYYMMMDDD = "yyyy年M月d日";

    public static String YYYYMMDD = "yyyyMMdd";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yy-MM-dd HH:mm", "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();
    }

    public static Date getToday(){
        return dateTime(YYYY_MM_DD,getDate());
    }

    /**
     * 获取当前日期, 默认格式为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 String parseDateToStr(final String format, final Long 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 + "分钟";
    }


    /**
     * 获取一天的开始时间  00:00:00
     *
     * @param date 传入日期
     * @return Date
     */
    public static Date getBeginTime(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取一天的结束时间 23:59:59
     *
     * @param date 传入日期
     * @return Date
     */
    public static Date getEndTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    public static final Date parseCSTTime(final String formart, final String date) {
        if (StringUtils.isEmpty(date)){
            return null;
        }
        String formatDate = date;
        if (date.contains("CST")) {
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
            Date d = null;
            try {
                d = sdf.parse(date);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            formatDate = new SimpleDateFormat(formart).format(d);
        }
        return dateTime(formart, formatDate);
    }

    public static final String parseCSTStr(final String formart, final String date) {
        String formatDate = date;
        if (date.contains("CST")) {
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
            Date d = null;
            try {
                d = sdf.parse(date);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            formatDate = new SimpleDateFormat(formart).format(d);
        }
        return formatDate;
    }


    public static final Date parseUTCDate(final String formart, final String dateStr) {
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.ENGLISH);
        LocalDateTime ldt = LocalDateTime.parse(dateStr,sdf);
        ZoneId currentZone = ZoneId.of("UTC");
        ZoneId newZone = ZoneId.of("Asia/Shanghai");
        String formatDate  = ldt.atZone(currentZone).withZoneSameInstant(newZone).toLocalDateTime().toString();
        if(formatDate.length()>10){
            formatDate = formatDate.substring(0,10);
        }
        return DateUtils.parseDate(formatDate);
    }



    /**
     * 判断时间是否为当天时间
     *
     * @param date 传入日期
     * @return Boolean
     */
    public static Boolean checkIsToday(Date date) {
        Date nowDate = DateUtils.getNowDate();
        Date beginTime = DateUtils.getBeginTime(nowDate);
        Date endTime = DateUtils.getEndTime(nowDate);
        if (date.getTime() >= beginTime.getTime() && date.getTime() <= endTime.getTime()) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    /**
     * 判断时间是否小于等于当天时间
     *
     * @param date 传入日期
     * @return Boolean
     */
    public static Boolean checkLEToday(Date date) {
        Date nowDate = DateUtils.getNowDate();
        if (getBeginTime(date).getTime() <= getBeginTime(nowDate).getTime()) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    /**
     * 处理excel导入时时间格式传入后台是 数字类型
     *
     * @param formart
     * @param date
     * @return
     */
    public static String excelDateFormat(final String formart, final Integer date) {
        Calendar calendar = Calendar.getInstance();
        Date parse = parseCSTTime(YYYY_MM_DD_HH_MM_SS, "1900-01-01 00:00:00");
        calendar.setTime(parse);
        //i-2的原因是实际天数比获取的天数少2天
        calendar.add(Calendar.DATE, date - 2);
        return parseDateToStr(formart, calendar.getTime());
    }

    public static Date getDate(long time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        return calendar.getTime();
    }

    /**
     * 计算两个时间差
     */
    public static Long getDateDay(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        return diff / nd;
    }

    /**
     * 计算两个时间差
     */
    public static Long getDateDays(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        if (diff % nd == 0) {
            return diff / nd;
        } else {
            return (diff / nd) + 1;
        }
    }

    /**
     * 计算两个时间差毫秒值绝对值
     */
    public static Long getDateDayABS(Date endDate, Date nowDate) {
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        return Math.abs(diff);
    }

    public static boolean checkDate(Date inputDate, String begin, String end) {
        Calendar c = Calendar.getInstance();
        c.setTime(inputDate);
        c.set(Calendar.YEAR, 1970);
        c.set(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);
        inputDate = c.getTime();

        Date beginDate;
        Date endDate;

        boolean checkFlag = false;

        SimpleDateFormat ft = new SimpleDateFormat("HH:mm");
        try {
            beginDate = ft.parse(begin);
            endDate = ft.parse(end);
            if (inputDate.getTime() >= beginDate.getTime() && inputDate.getTime() < endDate.getTime()) {
                checkFlag = true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return checkFlag;
    }

    //获取当天日期的开始时间0点 的前后--day---天   前则为负数 后则为正数
    public static String getDateStr(int day) {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        calendar.add(Calendar.DAY_OF_MONTH, day);
        date = calendar.getTime();
        return parseDateToStr(YYYY_MM_DD_HH_MM_SS, date);
    }

    //获取日期的开始时间0点 的前后--day---天   前则为负数 后则为正数
    public static Date getDateByDays(Date date, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        calendar.add(Calendar.DAY_OF_MONTH, day);
        date = calendar.getTime();
        return date;
    }

    //获取时间区间内的日期 以天为间隔
    public static List<Date> getDatesByDayInterval(Date beginTime, Date endTime) {
        List<Date> list = new ArrayList<>();
        do {
            Calendar c = Calendar.getInstance();
            c.setTime(beginTime);
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
            c.add(Calendar.DATE, 1);
            list.add(beginTime);
            beginTime = c.getTime();
        } while (beginTime.before(endTime));
        return list;
    }

    public static String getDateInTimeRange(Date time, String startTime, String endTime){
        String yearMonthDay = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, time);
        Date startDate = DateUtils.parseDate(yearMonthDay + " " + startTime);
        Date endDate = DateUtils.parseDate(yearMonthDay + " " + endTime);

        Calendar c = Calendar.getInstance();
        c.setTime(time);
        int day = c.get(Calendar.DAY_OF_MONTH);

        //如果配置时间为同一天的区间
        if (startDate.before(endDate)){
            if (time.getTime() >= startDate.getTime() && time.getTime() < endDate.getTime()){
                return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,time);
            }
        }else{
            //时间区间不在同一天  开始时间前移一天
            Date newStartDate = setYearMonthDate(startDate, day - 1);
            if (time.getTime() >= newStartDate.getTime() && time.getTime() < endDate.getTime()){
                return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,time);
            }
            //结束时间后移一天
            Date newEndDate = setYearMonthDate(startDate, day + 1);
            if (time.getTime() >= startDate.getTime() && time.getTime() < newEndDate.getTime()){
                return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,newEndDate);
            }
        }
        return null;
    }

    private static Date setYearMonthDate(Date startDate, int day) {
        Calendar calendarStart = Calendar.getInstance();
        calendarStart.setTime(startDate);
        calendarStart.set(Calendar.DAY_OF_MONTH, day);
        startDate = calendarStart.getTime();
        return startDate;
    }

    /**
     * 获取给定时间月初
     * @param date
     * @return
     */
    public static String getFirstDayOfMonth(Date date) {
        Calendar cale = Calendar.getInstance();
        cale.setTime(date);
        cale.add(Calendar.MONTH, 0);
        cale.set(Calendar.DAY_OF_MONTH, 1);
        return new SimpleDateFormat(DateUtils.YYYY_MM_DD).format(cale.getTime());
    }

    /**
     * 获取给定时间月初
     * @param date
     * @return
     */
    public static String getLastDayOfMonth(Date date) {
        Calendar cale = Calendar.getInstance();
        cale.setTime(date);
        cale.add(Calendar.MONTH, 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        return new SimpleDateFormat(DateUtils.YYYY_MM_DD).format(cale.getTime());
    }

    /**
     * 获取前后时间
     * @param timeStart 开始时间
     * @param days 往前往后天数
     * @return
     */
    public static Date getDateUpDown(Date timeStart, int days) {
        Calendar c = Calendar.getInstance();
        c.setTime(timeStart);
        c.add(Calendar.DAY_OF_WEEK, days);
        return c.getTime();
    }

    /**
     * 是否是两年前的时间
     * @param date
     * @return
     */
    public static boolean isDateTwoYearsAgo(Date date) {
        Calendar calendar = Calendar.getInstance();  // 获取当前日期的Calendar实例
        int currentYear = calendar.get(Calendar.YEAR);  // 获取当前年份

        calendar.setTime(date);  // 将要判断的日期设置到Calendar实例中
        int dateYear = calendar.get(Calendar.YEAR);  // 获取要判断的日期的年份

        // 判断年份差是否为2
        return currentYear - dateYear > 2;
    }

}
