package cn.cecep.talroad.util.effective;


import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;

public class NewDateUtil {
    public static final String DATE_PATTERN_GETDAY = "dd";
    public static final String DATE_PATTERN_MONTH = "yyyy-MM";
    public static final String DATE_PATTERN_MONTH01 = "yyyyMM01";
    public static final String DATE_PATTERN = "yyyy-MM-dd";
    public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String HOUR_FEN = "HH:mm";
    public static final String HOUR_TIME_PATTERN = "yyyy-MM-dd HH:00";
    public static final String HOUR_TIME_PATTERN_WHOLE = "yyyy-MM-dd HH:00:00";
    public static final String HOUR_PATTERN = "yyyy-MM-dd HH";
    public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
    public final static String DATE_TIME0_PATTERN = "yyyy-MM-dd 00:00:00";

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

    public NewDateUtil() {
    }

    public static String format(Date date) {
        return format(date, "yyyy-MM-dd");
    }

    public static String format(Date date, String pattern) {
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        } else {
            return null;
        }
    }

    public static int getHour(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(11);
    }

    public static Date getLastDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int lastDay = calendar.getActualMaximum(5);
        calendar.set(5, lastDay);
        return calendar.getTime();
    }

    public static Date stringToDate(String strDate, String pattern) {
        if (StringUtils.isBlank(strDate)) {
            return null;
        } else {
            DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
            return fmt.parseLocalDateTime(strDate).toDate();
        }
    }

    public static Date[] getWeekStartAndEnd(int week) {
        DateTime dateTime = new DateTime();
        LocalDate date = new LocalDate(dateTime.plusWeeks(week));
        date = date.dayOfWeek().withMinimumValue();
        Date beginDate = date.toDate();
        Date endDate = date.plusDays(6).toDate();
        return new Date[]{beginDate, endDate};
    }

    public static String getWeek(Date date) {
        String[] weeks = new String[]{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week_index = cal.get(7) - 1;
        if (week_index < 0) {
            week_index = 0;
        }

        return weeks[week_index];
    }
    public static String getDayOfWeek(DayOfWeek dayOfWeek) {
        String[] weeks = new String[]{ "星期一", "星期二", "星期三", "星期四", "星期五", "星期六","星期日"};

        return weeks[dayOfWeek.ordinal()];
    }

    public static Date addDateSeconds(Date date, int seconds) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusSeconds(seconds).toDate();
    }

    public static Date addDateMinutes(Date date, int minutes) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusMinutes(minutes).toDate();
    }

    public static Date addDateHours(Date date, int hours) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusHours(hours).toDate();
    }

    public static Date addDateDays(Date date, int days) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusDays(days).toDate();
    }

    public static Date addDateWeeks(Date date, int weeks) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusWeeks(weeks).toDate();
    }

    public static Date addDateMonths(Date date, int months) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusMonths(months).toDate();
    }

    public static Date addDateYears(Date date, int years) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusYears(years).toDate();
    }

    public static Integer achieveMonth(String start, String end) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();

        try {
            bef.setTime(sdf.parse(start));
            aft.setTime(sdf.parse(end));
        } catch (ParseException var7) {
            var7.printStackTrace();
        }

        int result = aft.get(2) - bef.get(2);
        int month = (aft.get(1) - bef.get(1)) * 12;
        return Math.abs(month + result) + 1;
    }

    public static Date lastDayOfMonth(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(1);
        int month = calendar.get(2) + 1;
        int lastDay = calendar.getActualMaximum(5);

        try {
            return format.parse(year + "-" + month + "-" + lastDay + " 23:59:59");
        } catch (ParseException var7) {
            var7.printStackTrace();
            return null;
        }
    }

    public static Date getStartTime(long date) {
        Date begin = new Date(date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(begin);
        cal.set(5, 1);
        cal.set(11, 0);
        cal.set(13, 0);
        cal.set(12, 0);
        return cal.getTime();
    }

    public static Date getEndTime(long date) {
        Date begin = new Date(date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(begin);
        int days = cal.getActualMaximum(5);
        cal.set(5, days);
        cal.set(11, 24);
        cal.set(13, 0);
        cal.set(12, 0);
        return cal.getTime();
    }

    public static int getDays(Date startTime, Date endTime) {
        DateTime startDate = new DateTime(startTime);
        DateTime endDate = new DateTime(endTime);
        int days = Days.daysBetween(startDate, endDate).getDays();
        return days;
    }

    public static Date getQuarterlyStartTime(int year, int quarter) {
        String startTimeStr = null;
        if (quarter == 1) {
            startTimeStr = year + "-01-01 00:00:00";
        } else if (quarter == 2) {
            startTimeStr = year + "-04-01 00:00:00";
        } else if (quarter == 3) {
            startTimeStr = year + "-07-01 00:00:00";
        } else {
            startTimeStr = year + "-10-01 00:00:00";
        }

        return stringToDate(startTimeStr, "yyyy-MM-dd HH:mm:ss");
    }

    public static Date getQuarterlyEndTime(int year, int quarter) {
        String endTimeStr = null;
        if (quarter == 1) {
            endTimeStr = year + "-03-31 23:59:59";
        } else if (quarter == 2) {
            endTimeStr = year + "-06-30 23:59:59";
        } else if (quarter == 3) {
            endTimeStr = year + "-09-30 23:59:59";
        } else {
            endTimeStr = year + "-12-31 23:59:59";
        }

        return stringToDate(endTimeStr, "yyyy-MM-dd HH:mm:ss");
    }

    public static int getYear(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(1);
    }

    public static int getYearDays(int year) {
        return (year % 4 != 0 || year % 100 == 0) && year % 400 != 0 ? 365 : 366;
    }

    private static Calendar getCalendarFormYear(int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(7, 2);
        cal.set(1, year);
        return cal;
    }

    public static String getStartDayOfWeekNo(int year, int weekNo) {
        Calendar cal = getCalendarFormYear(year);
        cal.set(3, weekNo);
        return cal.get(1) + "-" + (cal.get(2) + 1) + "-" + cal.get(5);
    }

    public static String getEndDayOfWeekNo(int year, int weekNo) {
        Calendar cal = getCalendarFormYear(year);
        cal.set(3, weekNo);
        cal.add(7, 6);
        return cal.get(1) + "-" + (cal.get(2) + 1) + "-" + cal.get(5);
    }

    public static String getFromToDate(SimpleDateFormat sdf, Date date, int n, int option, int k) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfWeek = calendar.get(7) - 1;
        int offset = 0 == option ? 1 - dayOfWeek : 7 - dayOfWeek;
        int amount = 0 == option ? offset - (n - 1 + k) * 7 : offset - k * 7;
        calendar.add(5, amount);
        return sdf.format(calendar.getTime());
    }

    public static String getNWeekTimeInterval(int n, SimpleDateFormat sdf) {
        String beginDate = getFromToDate(sdf, new Date(), n, 0, 0);
        String endDate = getFromToDate(sdf, new Date(), n, 1, 0);
        return beginDate + "," + endDate;
    }

    public static String getNWeekTimeIntervalTwo(int n, SimpleDateFormat sdf) {
        String beginDate = getFromToDate(sdf, new Date(), n, 0, 1);
        String endDate = getFromToDate(sdf, new Date(), n, 1, 1);
        return beginDate + "," + endDate;
    }

    public static String getThisWeekTimeInterval(SimpleDateFormat sdf) {
        return getNWeekTimeInterval(1, sdf);
    }

    public static String getLastWeekTimeInterval(SimpleDateFormat sdf) {
        return getNWeekTimeIntervalTwo(1, sdf);
    }

    public static List<String> getAllDays(Date startTime, Date endTime) {
        List<String> lDate = new ArrayList();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        lDate.add(sd.format(startTime));
        Calendar calBegin = Calendar.getInstance();
        calBegin.setTime(startTime);
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(endTime);

        while(endTime.after(calBegin.getTime())) {
            calBegin.add(5, 1);
            lDate.add(sd.format(calBegin.getTime()));
        }

        return lDate;
    }

    public static List<String> getAllHours(Date startTime, Date endTime, String format) {
        List<String> lDate = new ArrayList();
        SimpleDateFormat sd = new SimpleDateFormat(format);
        lDate.add(sd.format(startTime));
        Calendar calBegin = Calendar.getInstance();
        calBegin.setTime(startTime);
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(endTime);

        while(endTime.after(calBegin.getTime())) {
            calBegin.add(11, 1);
            lDate.add(sd.format(calBegin.getTime()));
        }

        return lDate;
    }

    public static String getToday() {
        return (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
    }

    public static String getYestoday() {
        Calendar cal = Calendar.getInstance();
        cal.add(5, -1);
        Date time = cal.getTime();
        return (new SimpleDateFormat("yyyy-MM-dd")).format(time);
    }

    public static Date getYestodayDate() {
        Calendar cal = Calendar.getInstance();
        cal.add(5, -1);
        return cal.getTime();
    }

    public static String getMonthStart() {
        Calendar cal = Calendar.getInstance();
        cal.add(2, 0);
        cal.set(5, 1);
        Date time = cal.getTime();
        return (new SimpleDateFormat("yyyy-MM-dd")).format(time);
    }

    public static Date getMonthStartDate() {
        Calendar cal = Calendar.getInstance();
        cal.add(2, 0);
        cal.set(5, 1);
        return cal.getTime();
    }

    public static String getMonthEnd() {
        Calendar cal = Calendar.getInstance();
        cal.set(5, cal.getActualMaximum(5));
        Date time = cal.getTime();
        return (new SimpleDateFormat("yyyy-MM-dd")).format(time);
    }

    public static String getWeekStart() {
        Calendar cal = Calendar.getInstance();
        cal.add(4, 0);
        cal.set(7, 2);
        Date time = cal.getTime();
        return (new SimpleDateFormat("yyyy-MM-dd")).format(time);
    }

    public static Date getWeekStartDate() {
        Calendar cal = Calendar.getInstance();
        cal.add(4, 0);
        cal.set(7, 2);
        return cal.getTime();
    }

    public static String getWeekEnd() {
        Calendar cal = Calendar.getInstance();
        cal.set(7, cal.getActualMaximum(7));
        cal.add(7, 1);
        Date time = cal.getTime();
        return (new SimpleDateFormat("yyyy-MM-dd")).format(time);
    }

    public static String getYearStart() {
        return (new SimpleDateFormat("yyyy")).format(new Date()) + "-01-01";
    }

    public static Date getYearStartDate() {
        Date now = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(now);
        c.set(6, 1);
        return c.getTime();
    }

    public static String getYearEnd() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(2, calendar.getActualMaximum(2));
        calendar.set(5, calendar.getActualMaximum(5));
        Date currYearLast = calendar.getTime();
        return (new SimpleDateFormat("yyyy-MM-dd")).format(currYearLast);
    }

    //获取当前月第一天
    public static String getFirstOfMonth(){
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
        String first = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return first;
    }

    //获取当前月最后一天
    public static String getLastOfMonth(){
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
        String last = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return last;
    }

    //获取当前周第一天
    public static String getFirstOfWeek(){
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int d = 0;
        if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
            d = -6;
        } else {
            d = 2 - cal.get(Calendar.DAY_OF_WEEK);
        }
        cal.add(Calendar.DAY_OF_WEEK, d);
        // 所在周开始日期
        String data = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return data;
    }

    //获取当前周最后一天
    public static String getLastOfWeek(){
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int d = 0;
        if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
            d = -6;
        } else {
            d = 2 - cal.get(Calendar.DAY_OF_WEEK);
        }
        cal.add(Calendar.DAY_OF_WEEK, d);
        // 所在周开始日期
        cal.add(Calendar.DAY_OF_WEEK, 6);
        String data = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return data;
    }

    /**
     * 获取参数时间所在年 的 最大周数
     *
     * @param year
     * @return 当前年份的最大周数
     */
    public static int getMaxWeakOfYear(int year) {
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, 11);//11表示的是12月
        cal.set(Calendar.DATE, 31);
        return cal.get(Calendar.WEEK_OF_YEAR) == 1 ? 52 : 53;
    }

    /**
     * 获取参数时间是所在年份的第几周
     *
     * @param date
     * @return 参数时间是所在年份的第几周
     */
    public static int getWeakOfYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        int weak = calendar.get(Calendar.WEEK_OF_YEAR);//当前周
        int month = calendar.get(Calendar.MONTH) + 1;//当前月份,注意:calendar的月份会自动-1

        if (weak == 1 && month == 12) {
            int year = calendar.get(Calendar.YEAR);
            return getMaxWeakOfYear(year);
        }
        return weak;
    }

    /**
     * 获取指定日期的所在周的第一天（周一）
     * @param time
     * @return
     */
    public static Date getWeekByDate(Date time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 设置时间格式
        Calendar cal = Calendar.getInstance();
        cal.setTime(time);
        // 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        int day = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值

        return stringToDate(sdf.format(cal.getTime()),"yyyy-MM-dd");
    }

    public static Date getLastWeekByDate(Date time) {
        Date date = getWeekByDate(time);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE,6);
        return calendar.getTime();
    }

    //获取日期所在月第一天
    public static String getFirstOfMonthByDate(Date date){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
        String first = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return first;
    }

    //获取日期所在月最后一天
    public static String getLastOfMonthByDate(Date date){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
        String last = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return last;
    }

    //日期相减得天数,得出结果需要+1
    public static long getDaySub(String beginDateStr,String endDateStr){
        long day = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date beginDate;
        Date endDate;
        try{
            beginDate = format.parse(beginDateStr);
            endDate= format.parse(endDateStr);
            day = (endDate.getTime() - beginDate.getTime()) / (24*60*60*1000);
        } catch (ParseException e){
            e.printStackTrace();
        }
        return day;
    }


    /**
     * date转LocalDateTime
     * @param date
     * @return
     */
    public static LocalDateTime dateToLocalDateTime(Date date){
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();

        return instant.atZone(zoneId).toLocalDateTime();
    }


    /**
     * LocalDateTime转date
     * @param localDateTime
     * @return
     */
    public static Date localDateTimeToDate(LocalDateTime localDateTime){
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);

        return Date.from(zdt.toInstant());
    }

    public static void main(String[] args) {
        String lastOfMonth = NewDateUtil.getLastOfMonth();
    }

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


}

