package com.palmnest.application.core.util;

import net.sf.json.JSON;
import net.sf.json.util.JSONUtils;

import org.joda.time.DateTime;
import org.joda.time.Hours;
import org.joda.time.Minutes;

import cn.superdesk.libs.common.json.JsonUtils;

import java.io.ObjectInputStream.GetField;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * 日期工具类
 *
 * @author 陈照华
 */

public class DateHelper {

	public static final String[] FORMATS = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm",
			"yyyy-MM-dd HH:mm:ss", "HH:mm", "HH:mm:ss", "yyyy-MM",
			"yyyyMMddHHmm", "yyyyMMddHHmmss", "yyyyMMdd"};

	public static final String CURRENT_DATE = "yyyy-MM-dd";

	public static final String DATE = "yyyyMMdd";

	public static final String CURRENT_TIME = "HH:mm:ss";

	public static final String TIME_HOUR_MINUTE = "HH:mm";

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

	public static final String DATE_STRING = "yyyy-MM-dd HH:mm";

	static Calendar calendar = Calendar.getInstance();

	public static String currentMonth() {
		return String.valueOf(calendar.get(Calendar.MONTH) + 1);
	}

	public static String currentWeek() {
		return String.valueOf(calendar.get(Calendar.DAY_OF_WEEK) - 1);
	}

	public static String getWeek(String date) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(parseToDate(date));
		return String.valueOf(ca.get(Calendar.DAY_OF_WEEK) - 1);
	}

	public static String getMonth(String date) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(parseToDate(date));
		return String.valueOf(ca.get(Calendar.MONTH) + 1);
	}

	/**
	 * 获取指定日期加减天数后的日期字符传
	 *
	 * @param curDate
	 * @param offSet  +-n
	 * @param format
	 * @return
	 */
	public static String getDateStrByOffsetDay(Date curDate, int offSet,
											   String format) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(curDate);
		ca.add(Calendar.DATE, offSet);
		SimpleDateFormat sdf = null;
		if (format != null && !"".equals(format.trim())) {
			sdf = new SimpleDateFormat(format);
		} else {
			sdf = new SimpleDateFormat(FORMATS[0]);
		}
		return sdf.format(ca.getTime());
	}

	public static Date getDateByOffsetMonth(Date curDate, int offSet) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(curDate);
		ca.add(Calendar.MONTH, offSet);
		return ca.getTime();
	}

	/**
	 * 明天
	 *
	 * @return
	 */
	public static String getNextDay(String format) {
		Calendar date = Calendar.getInstance();
		date.add(Calendar.DATE, 1);// 把日期设置为当月第一天
		date.set(Calendar.HOUR, 0);
		date.set(Calendar.MINUTE, 0);
		date.set(Calendar.SECOND, 0);
		return formatDate(date.getTime(), format);
	}

	public static String getNextDay(String day,String format) {
		Date temp = DateHelper.parseToDate(day,format);
		Calendar date = Calendar.getInstance();
		date.setTime(temp);
		date.add(Calendar.DATE, 1);// 把日期设置为当月第一天
		return formatDate(date.getTime(), format);
	}

	public static void main(String[] args) {
		//System.out.println(DateHelper.getNextDay("2022-06-06",DateHelper.CURRENT_DATE));


		Date startTime = DateHelper.parseToDate("2022-08-10 18:20:58","yyyy-MM-dd HH:mm");
		Date endTime = DateHelper.parseToDate("2022-08-10 18:30:01","yyyy-MM-dd HH:mm");
		int hours = DateHelper.getMinutesBetween(startTime, endTime);
		System.out.println("分钟："+endTime.toLocaleString());

	}



	/**
	 * 下月第一天
	 *
	 * @return
	 */
	public static String getNextMonthFirstDay(String format) {
		Calendar date = Calendar.getInstance();
		date.add(Calendar.MONTH, 1);// 加一个月
		date.set(Calendar.DATE, 1);// 把日期设置为当月第一天
		date.set(Calendar.HOUR, 0);
		date.set(Calendar.MINUTE, 0);
		date.set(Calendar.SECOND, 0);
		return formatDate(date.getTime(), format);
	}

	/**
	 * 时间天数加减
	 *
	 * @param curDate
	 * @param offSet
	 * @return
	 */
	public static Date getDateByOffsetDay(Date curDate, int offSet) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(curDate);
		ca.add(Calendar.DATE, offSet);
		return ca.getTime();
	}

	/**
	 * 时间小时增减
	 *
	 * @param curDate
	 * @param offSet
	 * @return
	 */
	public static Date getDateByOffsetHour(Date curDate, int offSet) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(curDate);
		ca.add(Calendar.HOUR, offSet);
		return ca.getTime();
	}

	/**
	 * 时间分钟增减
	 *
	 * @param curDate
	 * @param offSet
	 * @return
	 */
	public static Date getDateByOffsetMinute(Date curDate, int offSet) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(curDate);
		ca.add(Calendar.MINUTE, offSet);
		return ca.getTime();
	}

	/**
	 * 取得当前时间
	 *
	 * @return 当前时间
	 */
	public static Date getNow() {
		return Calendar.getInstance().getTime();
	}

	/**
	 * 获取标准时间 防止出现晚8小时的状况
	 *
	 * @return
	 */
	public static String getStandardCurrentDateStr() {
		TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
		SimpleDateFormat sdf = new SimpleDateFormat(FORMATS[2]);
		return sdf.format(getStandardCurrentDate());
	}

	public static Date getStandardCurrentDate() {
		TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
		Calendar c = Calendar.getInstance();
		return c.getTime();
	}

	/**
	 * 获取指定格式的当前时间
	 *
	 * @param format
	 * @return
	 */
	public static String getCurrentDateStr(String format) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		Date date = new Date();
		String time = simpleDateFormat.format(date);
		return time;
	}

	/**
	 * 获取指定格式的当前时间 格式:yyyy-MM-dd HH:mm:ss
	 *
	 * @return
	 */
	public static String getCurrentDateTimeStr() {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FORMATS[2]);
		Date date = new Date();
		String time = simpleDateFormat.format(date);
		return time;
	}

	/**
	 * 字符串转日期(按指定格式)
	 *
	 * @param dateString
	 * @param format
	 * @return 错误返回null, 正常返回日期
	 */
	public static Date parseToDate(String dateString, String format) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		try {
			return simpleDateFormat.parse(dateString.trim());
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 字符串转日期
	 *
	 * @param dateString -字符串日期(支持的格式有: "yyyy-MM-dd", "yyyy-MM-dd HH:mm",
	 *                   "yyyy-MM-dd HH:mm:ss", "HH:mm", "HH:mm:ss", "yyyy-MM")
	 * @return 错误返回null, 正常返回日期
	 */
	public static Date parseToDate(String dateString) {
		String format = "";
		for (String formats : FORMATS) {
			if (dateString.trim().length() == formats.length())
				format = formats;
		}
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		try {
			return simpleDateFormat.parse(dateString.trim());
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 计算日期差
	 *
	 * @param startDate : 日期参数1
	 * @param endDate   : 日期参数2
	 * @param diffType  : 差值计算类别(1:秒数/2:分钟数/3:小时数/4:天数/5:周数/6:月数/7:年数)
	 * @return endDate小于startDate时返回-1,正常返回大于1
	 */
	public static long getDateDiff(Date startDate, Date endDate, int diffType) {
		long diffVal = -1;
		if (startDate.after(endDate))
			return diffVal;

		Calendar firstDay = Calendar.getInstance();
		Calendar lastDay = Calendar.getInstance();
		firstDay.setTime(startDate);
		lastDay.setTime(endDate);

		long fact = 1000;
		switch (diffType) {
			case 1: // 计算秒数差值
				break;
			case 2: // 计算分钟数差值
				fact = fact * 60;
				break;
			case 3: // 计算小时差值
				fact = fact * 60 * 60;
				break;
			case 4: // 计算天数差值
				fact = fact * 24 * 60 * 60;
				break;
			default:// 计算秒数差值
		}
		diffVal = (lastDay.getTimeInMillis() - firstDay.getTimeInMillis())
				/ fact;
		return diffVal;
	}

	public static int compare(String dateStrSrouce, String dateStrTarget,
							  String formatStr) {
		try {
			DateFormat format = new SimpleDateFormat(formatStr);
			Date source = format.parse(dateStrSrouce);
			Date target = format.parse(dateStrTarget);
			return source.compareTo(target);
		} catch (ParseException pe) {
			pe.printStackTrace();
			return -1;
		}
	}

	public static String toDateTimeString(Date date) {
		if (date == null) {
			return "";
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_STRING);
		return dateFormat.format(date);
	}

	/**
	 * 格式化日期
	 *
	 * @param date
	 * @param format
	 * @return
	 */
	public static String formatDate(Date date, String format) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		return simpleDateFormat.format(date);
	}

	/**
	 * 格式化日期成指定格式（yyyy-MM-dd HH:mm:ss）
	 *
	 * @param date
	 * @return
	 */
	public static String formatDateToStr(Date date) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FORMATS[2]);
		return simpleDateFormat.format(date);
	}

	/**
	 * 比较Date是否大于当前日期
	 *
	 * @return 0 -否  1-是
	 */
	public static Integer compareNowDate(Date targetDate) {
		return targetDate.after(getNow()) ? 1 : 0;
	}

	/**
	 * 得到本月的第一天
	 */
	public static String getMonthFirstDay() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, calendar
				.getActualMinimum(Calendar.DAY_OF_MONTH));
		SimpleDateFormat simpleFormate = new SimpleDateFormat(FORMATS[0]);
		return simpleFormate.format(calendar.getTime());
	}

	/**
	 * 得到本月的最后一天
	 */
	public static String getMonthLastDay() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, calendar
				.getActualMaximum(Calendar.DAY_OF_MONTH));
		SimpleDateFormat simpleFormate = new SimpleDateFormat(FORMATS[0]);
		return simpleFormate.format(calendar.getTime());
	}
	
	/**
     * 获取指定日期所在周的周日
     * 
     * @param date      日期
     */
    public static Date getLastDayOfWeek(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        // 如果是周日直接返回
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            return date;
        }
        System.out.println(c.get(Calendar.DAY_OF_WEEK));
        c.add(Calendar.DATE, 7 - c.get(Calendar.DAY_OF_WEEK) + 1);
        return c.getTime();
    }
    
    /**
     * 获取指定日期所在周的周一
     * 
     * @param date      日期
     */
    public static Date getFirstDayOfWeek(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            c.add(Calendar.DAY_OF_MONTH, -1);
        }
        c.add(Calendar.DATE, c.getFirstDayOfWeek() - c.get(Calendar.DAY_OF_WEEK) + 1);
        return c.getTime();
    }


	
	/**
	 * 获取一周
	 * @param dayte
	 * @return
	 */
	public static List<String>  dateToWeek(String dayte){
		List<String> list=new ArrayList<String>();
		SimpleDateFormat sdf=new SimpleDateFormat(CURRENT_DATE);
		Date mdate;
		try {
			mdate = sdf.parse(dayte);
			int b=mdate.getDay();
			Long fTime=mdate.getTime()-b*24*3600000;
			for(int a=1;a<8;a++){
				Date fdate=new Date();
				fdate.setTime(fTime+(a*24*3600000));
				list.add(sdf.format(fdate));
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(list!=null&&list.size()>0){
			for(String day:list){
				System.out.println(day);
			}
		}
		return list;
	}
	
//	public static List<Date> dateToWeek(Date mdate)
//	 {
//	   System.out.println("mdate :"+mdate);
//	    int b=mdate.getDay();
//	    System.out.println("b:  "+b);
//	    Date fdate ;
//	    List <Date> list = new ArrayList();
//	    Long fTime=mdate.getTime()-b*24*3600000;
//	    System.out.println("fTime: "+fTime);
//	    for(int a=0;a<8;a++)
//	    {   
//	     fdate= new Date();
//	     fdate.setTime(fTime+(a*24*3600000));
//	     list.add(a, fdate);
//	    }
//	    return list;
//	  }
	
	
	/**
	 * 获取传入年所有1号所在周的周一
	 * @param year
	 * @return
	 */
	public static List<String> getAllFistDay(int year){
		List<String> list=new ArrayList<String>();
		SimpleDateFormat sdf=new SimpleDateFormat(CURRENT_DATE);
		String days=year+"-01-01;"+year+"-02-01;"+year+"-03-01;"+year+"-04-01;"+year+"-05-01;"+year+"-06-01;"+year+"-07-01;"+year+"-08-01;"+year+"-09-01;"+year+"-10-01;"+year+"-11-01;"+year+"-12-01;";
		String [] dayArr=days.split(";");
		try{
			for(String day:dayArr){
				System.out.println(day);
				String fistDay=sdf.format(getFirstDayOfWeek(sdf.parse(day)));
				System.out.println(fistDay);
				list.add(fistDay);
			}
		}catch(ParseException e){
			e.printStackTrace();
		}
		if(list!=null&&list.size()>0){
			for(String day:list){
				System.out.println("每月月初所在的周的周一:"+day);
			}
		}
		return list;
	}


	/**
	 * 获取两个时间的差值
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static int getHoursBetween(Date startDate,Date endDate) {
		return Hours.hoursBetween(new DateTime(startDate), new DateTime(endDate)).getHours();
	}

	public static int getMinutesBetween(Date startDate,Date endDate) {
		return Minutes.minutesBetween(new DateTime(startDate),new DateTime(endDate)).getMinutes();
	}



//	public static void main(String[] args) {
////		Date startTime = DateHelper.parseToDate("2020-08-2818:20","yyyy-MM-ddHH:mm");
//////		int hours = DateHelper.getMinutesBetween(startTime, new Date());
//////		System.out.println("分钟："+hours+"--"+hours/60);
//////
//////		System.out.println(new BigDecimal(hours).divide(new BigDecimal(60),1, BigDecimal.ROUND_HALF_UP).doubleValue());
////System.out.println(DateHelper.getDateByOffsetMinute(startTime,30));
////		setInfo("22:00","02:00","15","2020-12-04");
////		List<String> list=getLastDate(7);
////		System.out.println(JsonUtils.toJson(list));
//		String times="2040682147338";
////
////		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日-hh时mm分ss秒");
////	    Date date =DateHelper.parseToDate(time);
////	    System.out.println(format.format(date));
//
//
//		    long time =Long.parseLong(times);
//		    SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日-hh时mm分ss秒");
//		    Date date = new Date(time);
//		    System.out.println(time);
//		    System.out.println(format.format(date));
//	}
	
	
	public static List<String> getLastDate(int intervals ) {  
		List<String> fetureDaysList = new ArrayList<>();  
	       for (int i = 0; i <intervals; i++) {  
	           fetureDaysList.add(getFetureDate(i));  
	       }  
	       return fetureDaysList;  
	   }  
	
	public static String getFetureDate(int past) {  
	       Calendar calendar = Calendar.getInstance();  
	       calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);  
	       Date today = calendar.getTime();  
	       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
	       String result = format.format(today);  
	       return result;  
	   }  
	
	public static void setInfo(String maxtime,String mintime,String slotdurate,String date){
		maxtime=padLeft(maxtime,5,'0');
        mintime=padLeft(mintime,5,'0');
        String maxDateTimestr = date + maxtime;
        String minDateTimestr = date + mintime;
        String dateStartTimestr = date + "00:00";
        String dateEndTimestr = date + "23:59";

        Date dateStartTime=DateHelper.parseToDate(dateStartTimestr,"yyyy-MM-ddHH:mm");
        Date dateEndTime=DateHelper.parseToDate(dateEndTimestr,"yyyy-MM-ddHH:mm");
        Date maxDateTime=DateHelper.parseToDate(maxDateTimestr,"yyyy-MM-ddHH:mm");
        Date minDateTime=DateHelper.parseToDate(minDateTimestr,"yyyy-MM-ddHH:mm");

        int n = Integer.parseInt(slotdurate);
        for (Date periodTime = dateStartTime; periodTime.compareTo(dateEndTime)<0; periodTime =DateHelper.getDateByOffsetMinute(periodTime,n)){
        	String  starttime=DateHelper.formatDate(periodTime, "HH:mm");
        	String endtime = DateHelper.formatDate(DateHelper.getDateByOffsetMinute(periodTime,n), "HH:mm");
        	System.out.println(starttime+"~"+endtime);
        }
	}
	
	public static String padLeft(String src, int len, char ch) {
        int diff = len - src.length();
        if (diff <= 0) {
            return src;
        }

        char[] charr = new char[len];
        System.arraycopy(src.toCharArray(), 0, charr, 0, src.length());
        for (int i = src.length(); i < len; i++) {
            charr[i] = ch;
        }
        return new String(charr);
    }
	
	
}
