package com.ag.dynamicmodule.common;

import org.apache.commons.lang3.StringUtils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Administrator on 2017/6/23 0023.
 */
public class TimeUtil {

    public static String getDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }
    public static String getDate(Date date) {
        if (date == null || "".equals(date)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    public static String getSerDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(new Date());
    }

    public static String getSerDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(date);
    }

    public static String getTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(new Date());
    }

    public static String getTime(Date dt) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(dt);
    }

    /**
     * Description: 处理时间
     * @param dt
     * Note: Nothing much.
     */
    public static Date getMinute(Date dt){
        SimpleDateFormat sdf=new SimpleDateFormat("HH:mm");
        String strdt = sdf.format(dt);
        try {
            return sdf.parse(strdt);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Description: 处理时间
     * @param hm
     * Note: Nothing much.
     */
    public static Date getMinute(String hm){
        SimpleDateFormat sdf=new SimpleDateFormat("HH:mm");
        try {
            return sdf.parse(hm);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

    public static String getDateTime(Date dt) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(dt);
    }

    public static String getDateTimeSSS() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        return sdf.format(new Date());
    }

    public static Date getTimestamp(String strDate) {
        try {
            return Timestamp.valueOf(strDate);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 通过出生日期返回年龄
     */
    public static Integer getAge(String DCsrq) throws Exception {
        if (StringUtils.isEmpty(DCsrq)) {
            return 0;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDay = sdf.parse(DCsrq);
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            return 0;
			/*throw new IllegalArgumentException(
					"The birthDay is before Now.It's unbelievable!");*/
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                // monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                } else {
                    // do nothing
                }
            } else {
                // monthNow>monthBirth
                age--;
            }
        } else {
            // monthNow<monthBirth
            // donothing
        }
        return age;
    }

    /**
     * 通过年龄返回出生日期 月和日为当前日期

     public static String getCsrq(String csrq, String ageStr) {
     if (csrq != null && !"".equals(csrq)) {
     return csrq;
     }
     if (ageStr == null || "".equals(ageStr)) {
     return null;
     }
     int age = Integer.parseInt(ageStr);
     if (age <= 0 && age > 100) {
     return null;
     } */
		/*
		 * SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
		 * SimpleDateFormat sdf2 = new SimpleDateFormat("-MM-dd"); int year_age
		 * = Integer.valueOf(sdf1.format(new Date())) - age; String md_age =
		 * sdf2.format(new Date());
		 */
    /**
     SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
     int year_age = Integer.valueOf(sdf1.format(new Date())) - age;
     return year_age + "-01-01";
     }*/



    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }

    /**
     * 返回当前日期的指定范围日期，dt正数则为当前日期后几天，负则为前几天
     *
     * @param dt
     * @return
     */
    @SuppressWarnings("static-access")
    public static String getSomeDayOfToday(int dt) {
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DAY_OF_MONTH, dt);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(ca.getTime());
    }

    /**
     * 返回当前日期的指定范围日期，
     *
     * @param min 正数则为当前时间后几分钟，负则为前几分钟
     * @return
     */
    @SuppressWarnings("static-access")
    public static Date getSomeTimeOfMinute(int min) {
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.MINUTE, min);
        return ca.getTime();
		/*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(ca.getTime());*/
    }

    /**
     * 补齐日期类型
     */
    public static String getFullYYMMDD(String date) {
        if (null == date || "".equals(date)) {
            return null;
        }
        Calendar ca = Calendar.getInstance();
        int month = ca.get(Calendar.MONTH) + 1;
        int day = ca.get(Calendar.DATE);
        // 小于7位，只取年
        String rtnDate = "";
        if (date.length() < 7) {
            rtnDate = date.substring(0, 4) + "-" + String.valueOf(month) + "-"
                    + String.valueOf(day);
        } else if (date.length() < 10) {// 小于10位只取年月
            rtnDate = date.substring(0, 4) + "-" + date.substring(5, 7) + "-"
                    + String.valueOf(day);
        } else {
            rtnDate = date.substring(0, 4) + "-" + date.substring(5, 7) + "-"
                    + date.substring(8, 10);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.format(sdf.parse(rtnDate));
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获得当月第一天
     *
     * @param date
     * @return

    public static String getFirstDay() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
    return sdf.format(new Date()).concat("-01");
    }*/

    /**
     * 获得当月最后一天
     *

    public static String getLastDay() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
    String yearAndMonth = sdf.format(new Date());
    Integer days = getDays(yearAndMonth.split("-")[1],
    yearAndMonth.split("-")[0]);
    return yearAndMonth.concat("-" + days);
    }*/

    public static Integer getDays(String month, String year) {
        String months1 = "01,03,05,07,08,10,12,";
        String months2 = "04,06,09,11,";
        if (months1.contains(month + ",")) {
            return 31;
        } else if (months2.contains(month + ",")) {
            return 30;
        } else {
            if (0 == Integer.parseInt(year) % 4
                    && 0 != Integer.parseInt(year) % 100) {
                return 29;
            } else {
                return 28;
            }
        }
    }

    /**
     * 给定时间前后i天
     * @param date
     * @return
     */
    public static Date getTimeLaterDay(Date date, int i){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        if (i < 0){
            i = i + 1;
        }
        calendar.add(Calendar.DATE, i);
        return calendar.getTime();
    }

    /**
     * 给定时间加月份
     * @param date
     * @param month
     * @return
     */
    public static Date getTimeByAddMonth(Date date ,Integer month) {
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, month);
        return new Timestamp(calendar.getTimeInMillis());
    }

    /**
     * 返回yyMMdd格式
     * @return
     */
    public static String getDemandDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        return sdf.format(new Date());
    }

    /**
     * 判断两个时间是否在差值范围内，是返回true，否返回false
     * @param date1 时间小
     * @param date1 时间大
     * @param subdu 差值
     * @return
     */
    public static boolean getDValueByTime(Date date1, Date date2, int  subdu){
        long time1 = date1.getTime();
        long time2 = date2.getTime();
        if(time2 - time1 >  subdu){
            return false;
        }else{
            return true;
        }
    }


    public static Date getDateFromString(String str) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date=sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static Date StrToDate(String s) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(s);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static Date getDateFromToday() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date=sdf.parse(getDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static int compareDate(String DATE1, String DATE2) {
        if(DATE1 == null || DATE2 == null){
            return 0;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            throw new RuntimeException("日期格式异常");
        }
    }

    /**
     *两时间比较，日期差值，堆存天，当天返回0
     * @param start
     * @param end
     * @return
     */
    public static int compareDaysLimit(Date start, Date end){
        long dayLong = 1000*60*60*24;
        long dv = (getDayZero(end).getTime() - getDayZero(start).getTime()) / dayLong;
        return (int)dv;
    }

    /**
     * 两时间比较，日期差值，堆存小时，不满一小时=1小时
     * @param start
     * @param end
     * @return
     */
    public static int compareHoursLimit(Date start, Date end){
        long hourLong = 1000*60*60;
        long dv = (end.getTime() - start.getTime()) / hourLong;
        return (int)dv + 1;
    }

    /**
     * 两时间比较，开始时间小于结束时间返回true
     * @param start
     * @param end
     * @return
     */
    public static boolean compareDate(Date start, Date end){
        return (end.getTime() - start.getTime()) > 0;
    }

    /**
     * 两个日期之间间隔天数
     *
     * @param isWork  true: 包含工作日   false: 不包含工作日
     *
     * @return
     */
    public static int workDays(String beginDATE, String endDATE, boolean isWork) {
        if(beginDATE == null || endDATE == null){
            return 0;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date dt1 = df.parse(beginDATE);
            Date dt2 = df.parse(endDATE);
            int days = (int) ((dt2.getTime()-dt1.getTime())/(1000*60*60*24))+1;
            if(isWork){
                return days;
            }else{
                int weeks = days / 7;
                int rs = 0;
                // 整数周
                if (days % 7 == 0) {
                    rs = days - 2 * weeks;
                }
                else {
                    Calendar begCalendar = Calendar.getInstance();
                    Calendar endCalendar = Calendar.getInstance();
                    begCalendar.setTime(dt1);
                    endCalendar.setTime(dt2);
                    // 周日为1，周六为7
                    int beg = begCalendar.get(Calendar.DAY_OF_WEEK);
                    int end = endCalendar.get(Calendar.DAY_OF_WEEK);
                    if (beg > end) {
                        rs = days - 2 * (weeks + 1);
                    } else if (beg < end) {
                        if (end == 7) {
                            rs = days - 2 * weeks - 1;
                        } else {
                            rs = days - 2 * weeks;
                        }
                    } else {
                        if (beg == 1 || beg == 7) {
                            rs = days - 2 * weeks - 1;
                        } else {
                            rs = days - 2 * weeks;
                        }
                    }
                }
                return rs;
            }
        } catch (Exception exception) {
            throw new RuntimeException("日期格式异常");
        }
    }

    /**
     * 变更字符串时间转换格式
     *
     * @param fromFormat   变换前的日期格式
     * @param toFormat	变换后的日期格式
     * @param date  符合fromFormat格式的日期字符串
     */
    public static String changeFormat(String fromFormat, String toFormat, String date) {
        SimpleDateFormat oldFormat=new SimpleDateFormat(fromFormat);
        Date date1;
        String newDate="";
        try {
            date1 = oldFormat.parse(date);
            SimpleDateFormat newFormat=new SimpleDateFormat(toFormat);
            newDate = newFormat.format(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return newDate;
    }

    //获取时间的零点
    public static Date getDayZero(Date 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);
        return calendar.getTime();
    }


    /**
     * 相差分钟
     * @param beginTime
     * @param endTime
     * @return
     */
    public static int differSecond(String beginTime, String endTime) {
        if (StringUtils.isEmpty(beginTime) || StringUtils.isEmpty(endTime)) {
            return 0;
        }
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        try {
            Date beginDate = df.parse(beginTime);
            Date endDate = df.parse(endTime);
            return (int) ((endDate.getTime()-beginDate.getTime())/(1000*60));
        } catch (Exception exception) {
            throw new RuntimeException("日期格式异常");
        }
    }

    public static void main(String arg[]) {
//		System.out.println(TimeUtil.getDValueByTime(TimeUtil.getDayBegin(),TimeUtil.getNowTimestamp(),0));
//		System.out.println(TimeUtil.getDValueByTime(TimeUtil.getNowTimestamp(),TimeUtil.getDayBegin(),0));
        //System.out.println(compareDate(Timestamp.valueOf("2017-07-09 15:26:07"), Timestamp.valueOf("2017-07-10 00:00:00")));
        //System.out.println(toOrclDate(new Date()));
        //System.out.println(TimeUtil.getDateTime(TimeUtil.getTimeLaterDay(new Date(), -2)));
        // 取当前日期：
        System.out.println(LocalDate.now());// -> 2014-12-24
        // 根据年月日取日期，12月就是12：
        //LocalDate crischristmas = LocalDate.of(2014,-25
        // 根据字符串取： 12, 25); // -> 2014-12
        System.out.println(LocalDate.parse("2018-02-01")); // 严格按照ISO yyyy-MM-dd验证，02写成2都不行，当然也有一个重载方法允许自己定义格式
        System.out.println(LocalDateTime.now());
        System.out.println(LocalDateTime.parse("2018-02-01 13:59:56", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        System.out.println(LocalDateTime.parse("2018-02-01T13:59:56").toString());


        Integer one = 128,two = 128;
    }

}