package com.xisc.pm.infra.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;

public class DateUtils {
    
    public static final String Y_M_D = "yyyy-MM-dd";
    public static final String YMD = "yyyyMMdd";
    public static final String YMD_HMS = "yyyy-MM-dd HH:mm:ss";
    
    /**
     * 获取当前月份
     * @return
     */
    public static String getCurrentMonthOneChar() {
        LocalDate localDate = LocalDate.now();
        int month = localDate.getMonth().getValue();
        if(month == 10) {
            return "A";
        }
        if(month == 11) {
            return "B";
        }
        if(month == 12) {
            return "C";
        }
        return String.valueOf(month);
    }
    
    public static Date lastedDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(Y_M_D);
        SimpleDateFormat sdf2 = new SimpleDateFormat(YMD_HMS);
        String dateStr = sdf.format(date);
        try {
            return sdf2.parse(dateStr + " 23:59:59");
        } catch (ParseException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    public static Date firstDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(Y_M_D);
        SimpleDateFormat sdf2 = new SimpleDateFormat(YMD_HMS);
        String dateStr = sdf.format(date);
        try {
            return sdf2.parse(dateStr + " 00:00:00");
        } catch (ParseException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }
    
    /**
     * 指定格式转换
     * @param date
     * @param format
     * @return
     */
    public static Date parseDate(String date , String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(date);
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }
    
    /**
     * 
     * @param date
     * @param parsePatterns
     * @return
     */
    public static Date parseDate(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat(YMD_HMS);
        try {
            return sdf.parse(date);
        } catch (Exception e) {
            SimpleDateFormat sdf2 = new SimpleDateFormat(Y_M_D);
            try {
                return sdf2.parse(date);
            } catch (Exception e1) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
    }

    /**
     * 获取昨天的结束时间
     *
     * @return
     */
    public static Date getYesterdayEndOfDay() {
        LocalDate yesterday = LocalDate.now().minusDays(1);
        LocalDateTime endOfDay = yesterday.atTime(LocalTime.MAX);
        return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }

}
