package org.springblade.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created By lidexi in 2021/7/14
 * 日期工具类
 **/
public class DateUtil {

	public static List<String> getHalfYearMonth(boolean flag) {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, -5);
		String before_six = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH);// 六个月前
		ArrayList<String> result = new ArrayList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月
		Calendar min = Calendar.getInstance();
		Calendar max = Calendar.getInstance();
		try {
			try {
				min.setTime(sdf.parse(before_six));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
			max.setTime(sdf.parse(sdf.format(new Date())));

//不含当前月

			int month = max.get(Calendar.MONTH);
			max.set(Calendar.MONTH, month-1);

//不含当前月
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
		Calendar curr = min;
		while (curr.before(max)) {
			if (flag) {
				result.add(sdf.format(curr.getTime()));
			} else {
				result.add(curr.get(Calendar.MONTH) + 1 + "月");
			}
			curr.add(Calendar.MONTH, 1);
		}
		/*
		 * Calendar curr = max; while (curr.after(min)) {
		 * result.add(sd.format(curr.getTime())+"月"); curr.add(Calendar.MONTH, -1); }
		 */
		return result;
	}

	/**
	 * 获取本周的所有日期
	 * @param date
	 * @return "beginDate,endDate"
	 */
	public static String getTimeInterval(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		// 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
		int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
		if (1 == dayWeek) {
			cal.add(Calendar.DAY_OF_MONTH, -1);
		}
		// System.out.println("要计算日期为:" + sdf.format(cal.getTime())); // 输出要计算日期
		// 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
		cal.setFirstDayOfWeek(Calendar.MONDAY);
		// 获得当前日期是一个星期的第几天
		int day = cal.get(Calendar.DAY_OF_WEEK);
		// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
		cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
		String imptimeBegin = sdf.format(cal.getTime());
		// System.out.println("所在周星期一的日期：" + imptimeBegin);
		cal.add(Calendar.DATE, 6);
		String imptimeEnd = sdf.format(cal.getTime());
		// System.out.println("所在周星期日的日期：" + imptimeEnd);
		return imptimeBegin + "," + imptimeEnd;
	}

	public static void main(String[] args) {
		List<String> halfYearMonth = getHalfYearMonth(true);
		System.out.println(halfYearMonth.toString());
	}

}
