package com.yem.ensign.common;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.*;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.text.*;
import org.joda.time.format.*;
import java.util.*;
import org.joda.time.*;


/**
 * 日期工具类
 *@author 
 *@date 2019-09-13 下午8:20:16
 */
public class DateUtils {
	public static String FORMAT_YMD = "yyyy-MM-dd";
    public static String FORMAT_YMDHMS = "yyyy-MM-dd HH:mm:ss";
    public static String FORMAT_yyyyMMdd = "yyyyMMdd";

    public static DateFormat format = new SimpleDateFormat("yyyy-MM-dd");//日期格式

    /**
     * 获取日期起始时间
     * @param date 日期对象
     * @return Date对象结果
     */
    public static Date getBeginTime(Date date) {
        if (date == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 获取日期结束时间
     * @param date 日期对象
     * @return Date对象结果
     */
    public static Date getEndTime(Date date) {
        if (date == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY,23);
        cal.set(Calendar.MINUTE,59);
        cal.set(Calendar.SECOND,59);
        cal.set(Calendar.MILLISECOND, 999);
        return cal.getTime();
    }

    /**
     * 获取指定日期增加/减去指定天数后的日期
     * @param date 日期
     * @param days 增加/减少天数（增加为正，减少为负）
     * @return Date对象结果
     */
    public static Date getAddDay(Date date,int days) {
        if (date == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH,days);
        return cal.getTime();
    }

    /**
     * 日期之间的天数
     * @param beginDate 起始日期
     * @param endDate 结束日期
     * @return 天数
     */
    public static int getDiffDays(Date beginDate, Date endDate) {
        if (beginDate == null) {
            throw new IllegalArgumentException("起始日期为空！");
        }
        if (endDate == null) {
            throw new IllegalArgumentException("结束日期为空！");
        }
        long diff = (endDate.getTime() - beginDate.getTime()) / 86400000L;
        int days = new Long(diff).intValue() + 1;
        return days;
    }

    /**
     * 默认日期格式化字符串（yyyy-MM-dd）
     * @param date 日期
     * @return 日期字符串
     */
    public static String formatString(Date date) {
        if (date == null) {
            return "";
        }else{
            return new DateTime((Object)date).toString(DateTimeFormat.forPattern(FORMAT_YMD));
        }
    }

    /**
     * 自定义日期格式化字符串
     * @param date 日期
     * @param forPattern 自定义格式
     * @return 日期字符串
     */
    public static String formatString(Date date, String forPattern) {
        if (date == null) {
            return "";
        }else{
            return new DateTime((Object)date).toString(DateTimeFormat.forPattern(forPattern));
        }
    }

    /**
     * 获取日期对应年
     * @param date 日期
     * @return 年
     */
    public static int getYear(Date date) {
        if (date == null) {
            return 0;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.YEAR);
    }

    /**
     * 获取日期对应月
     * @param date 日期
     * @return 月
     */
    public static int getMonth(Date date) {
        if (date == null) {
            return 0;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.MONTH);
    }

    /**
     * 获取日期对应日
     * @param date 日期
     * @return 日
     */
    public static int getDay(Date date) {
        if (date == null) {
            return 0;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取当前日期所在星期的起止日期
     * @return 起止日期Map
     */
    public static Map<String, Date> getWeekDate() {
        Map<String, Date> weekDate = new HashMap<String, Date>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int d = 0;
        if (cal.get(7) == 1) {
            d = -6;
        }
        else {
            d = 2 - cal.get(7);
        }
        cal.add(7, d);
        cal.setTime(getBeginTime(cal.getTime()));
        weekDate.put("beginDate", cal.getTime());
        cal.add(7, 6);
        cal.setTime(getEndTime(cal.getTime()));
        weekDate.put("endDate", cal.getTime());
        return weekDate;
    }

    /**
     * 获取日期所在月开始时间
     * @param date 日期
     * @return 月初时间
     */
    public static Date getMinMonthDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(5, calendar.getActualMinimum(5));
        calendar.setTime(getBeginTime(calendar.getTime()));
        return calendar.getTime();
    }

    /**
     * 获取日期所在月结束时间
     * @param date 日期
     * @return 月末时间
     */
    public static Date getMaxMonthDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(5, calendar.getActualMaximum(5));
        calendar.setTime(getEndTime(calendar.getTime()));
        return calendar.getTime();
    }

    /**
     * 是否同一天
     * @param date1 日期
     * @param date2 日期
     * @return 是,否
     */
    public static boolean isSameDay(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            return false;
        }
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        return isSameDay(cal1, cal2);
    }

    /**
     * 是否同一天
     * @param cal1 日期Calendar对象
     * @param cal2 日期Calendar对象
     * @return 是，否
     */
    public static boolean isSameDay(Calendar cal1, Calendar cal2) {
        return cal1 != null && cal2 != null && cal1.get(0) == cal2.get(0) && cal1.get(1) == cal2.get(1) && cal1.get(6) == cal2.get(6);
    }

    /**
     * 是否同一月
     * @param d1 日期
     * @param d2 日期
     * @return 是，否
     */
    public static boolean isSameMonth(Date d1, Date d2) {
        return isSameDay(getMinMonthDate(d1), getMinMonthDate(d2));
    }

    /**
     * 获得本周一0点时间
     * @return 时间
     */
    public static Date getTimesWeekmorning() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.setTime(getBeginTime(cal.getTime()));
        return cal.getTime();
    }

    /**
     * 获得本周日24点时间
     * @return 时间
     */
    public static Date getTimesWeeknight() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getTimesWeekmorning());
        cal.add(Calendar.DAY_OF_WEEK, 6);
        cal.setTime(getEndTime(cal.getTime()));
        return cal.getTime();
    }

    /**
     * 当前季度的结束时间
     * @return
     */
    public static Date getCurrentQuarterEndTime() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getCurrentQuarterStartTime());
        cal.add(Calendar.MONTH, 2);
        cal.setTime(getMaxMonthDate(cal.getTime()));
        cal.setTime(getEndTime(cal.getTime()));
        return cal.getTime();
    }

    /**
     * 当前季度的开始时间
     * @return
     */
    public static Date getCurrentQuarterStartTime() {
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3)
                c.set(Calendar.MONTH, 0);
            else if (currentMonth >= 4 && currentMonth <= 6)
                c.set(Calendar.MONTH, 3);
            else if (currentMonth >= 7 && currentMonth <= 9)
                c.set(Calendar.MONTH, 4);
            else if (currentMonth >= 10 && currentMonth <= 12)
                c.set(Calendar.MONTH, 9);
            c.set(Calendar.DATE, 1);
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 判断是否时期是否工作日
     * @param dDate 日期
     * @return 是,否
     */
    public static boolean isweekday(Date dDate) {
		QFilter qFilter1 = new QFilter("tpv_holidaydate", QCP.equals, dDate);
		DynamicObject tpv_holiday = BusinessDataServiceHelper.loadSingle("tpv_holiday", "id,billno,tpv_holidaydate",
				new QFilter[] { qFilter1 });
		if (tpv_holiday != null) {
			return true;
		}else {
			return false;
		}
        
    }

    /**
     * 获得日期 （前/后 n天的）的工作日;
     * @param dDate 日期
     * @param addday 前/后天数
     * @return 日期
     */
    public static Date getweekday(Date dDate, int addday) {
    	int iNbDay = Math.abs(addday);
    	for(int days = 1 ; days <iNbDay+1 ; days++) {
    		Date weekdate = getAddDay(dDate,addday);
    		if(isweekday(weekdate)) {
    			iNbDay = iNbDay+1;
    		}
    	}
    	return getAddDay(dDate,addday);
    }

    /**
     * 字符串转时间
     * @param datestr 字符串
     * @return 时间
     */
    public static Date parseDate(String datestr) {
        Date date = null;
        if(StringUtils.isNotEmpty(datestr)) {
            try {
                date = format.parse(datestr);
            } catch (ParseException e) {
                e.printStackTrace();
                throw new IllegalArgumentException("字符串转时间出错："+e.getMessage());
            }
        }
        return date;
    }
}
