package com.scpyun.platform.jilinsscgsdp.utils;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;

import cn.hutool.core.map.MapUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;

public class DateUtil {


	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static final String YEAR_MONTH_DAY_PATTERN = "yyyy-MM-dd";

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


    // 日期转换为时间戳
    public static long timeToStamp(String timers) {
        Date d = new Date();
        long timeStemp = 0;
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            d = sf.parse(timers);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        timeStemp = d.getTime();
        return timeStemp;

    }
    public static long timeStrToStamp(String timers) {
        Date d = new Date();
        long timeStemp = 0;
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            d = sf.parse(timers);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        timeStemp = d.getTime();
        return timeStemp;

    }

    public static Date timeStrToDate(String timers) {
        Date d = new Date();
        long timeStemp = 0;
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            d = sf.parse(timers);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return d;

    }


    /**
     * 打印该年份的第一天
     */
    public static String getFirstDateForYear(int year) {
    	String fristDay = "";
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, calendar.getActualMinimum(Calendar.MONTH));
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.SECOND,0); //这是将当天的【秒】设置为0
        calendar.set(Calendar.MINUTE,0); //这是将当天的【分】设置为0
        calendar.set(Calendar.HOUR_OF_DAY,0); //这是将当天的【时】设置为0
        fristDay = sdf.format(calendar.getTime());
        return fristDay;
    }

    /**
     * 打印该年份的最后一天
     */
    public static String getLastDateForYear(int year) {
    	String lastDay = "";
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, calendar.getActualMaximum(Calendar.MONTH));
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.SECOND,59); //这是将当天的【秒】设置为0
        calendar.set(Calendar.MINUTE,59); //这是将当天的【分】设置为0
        calendar.set(Calendar.HOUR_OF_DAY,23); //这是将当天的【时】设置为0
        lastDay = sdf.format(calendar.getTime());
        return lastDay;
    }


    /**
     * 打印该月份的第一天
     */
    public static String getFirstDateForYearAndMonth(int year, int month) {
    	String fristDay = "";
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.SECOND,0); //这是将当天的【秒】设置为0
        calendar.set(Calendar.MINUTE,0); //这是将当天的【分】设置为0
        calendar.set(Calendar.HOUR_OF_DAY,0); //这是将当天的【时】设置为0
        fristDay = sdf.format(calendar.getTime());
        return fristDay;
    }

    /**
     * 打印该月份的第一天
     */
    public static String getLastDateForYearAndMonth(int year, int month) {
    	String lastDay = "";
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.SECOND,59); //这是将当天的【秒】设置为0
        calendar.set(Calendar.MINUTE,59); //这是将当天的【分】设置为0
        calendar.set(Calendar.HOUR_OF_DAY,23); //这是将当天的【时】设置为0
        lastDay = sdf.format(calendar.getTime());
        return lastDay;
    }


    /**
     * 打印本年份的第一天
     */
    public static String getCurrentFirstDateForYear() {
    	Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
		int year = aCalendar.get(Calendar.YEAR);//年份
        return getFirstDateForYear(year);
    }

    /**
     * 打印本月份的第一天
     */
    public static String getCurrentFirstDateForYearAndMonth() {
    	Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
		int year = aCalendar.get(Calendar.YEAR);//年份
		int month = aCalendar.get(Calendar.MONTH) + 1;//月份
        return getFirstDateForYearAndMonth(year, month);
    }

    /**
     * 打印本星期的第一天
     */
    public static String getCurrentFirstDateForWeek() {
    	Calendar cal = Calendar.getInstance();
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if(dayWeek==1){
            dayWeek = 8;
        }
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        cal.set(Calendar.SECOND,0); //这是将当天的【秒】设置为0
        cal.set(Calendar.MINUTE,0); //这是将当天的【分】设置为0
        cal.set(Calendar.HOUR_OF_DAY,0); //这是将当天的【时】设置为0
        Date mondayDate = cal.getTime();
        return sdf.format(mondayDate);
    }

    /**
     * 打印当前时间
     */
    public static String getCurrentTimeStr() {
    	Calendar cal = Calendar.getInstance();
        Date time = cal.getTime();
        return sdf.format(time);
    }

    /**
     * 打印当前天的零点
     */
    public static String getCurrentDateTimeBegin() {
    	Calendar calendar = Calendar.getInstance();
    	calendar.set(Calendar.SECOND,0); //这是将当天的【秒】设置为0
    	calendar.set(Calendar.MINUTE,0); //这是将当天的【分】设置为0
    	calendar.set(Calendar.HOUR_OF_DAY,0); //这是将当天的【时】设置为0
    	Date beginTime = calendar.getTime();
        return sdf.format(beginTime);
    }

    /**
     * 获取当前年份
     */
    public static String getCurrentYear() {
    	Calendar date = Calendar.getInstance();
    	String year = String.valueOf(date.get(Calendar.YEAR));
    	return year;

    }

    public static String convertToLocalDateTime(String dateTimeString) {
        if(StringUtils.isNotEmpty(dateTimeString)){
            try {
                // 解析 ISO 8601 格式的日期时间字符串
                OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateTimeString, DateTimeFormatter.ISO_OFFSET_DATE_TIME);

                // 将其转换为本地时间
                OffsetDateTime localDateTime = offsetDateTime.toLocalDateTime().atOffset(offsetDateTime.getOffset());

                // 使用 DateTimeFormatter 格式化为字符串
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                return localDateTime.format(formatter);
            } catch (Exception e) {
                // 处理解析错误或其他异常
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }


    public static void main(String[] args) {

        String inputDateString = "2023-11-08T16:00:00.000+00:00";
        String localDateString = convertToLocalDateTime(inputDateString);
        System.out.println("本地时间：" + localDateString);
	}
    public static String getCurrentTime() {
        Date date = new Date();
        SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dtf.format(date);
    }
    
	public static void queryDateRange(Map<String,Object> map,String key){
		String data=MapUtil.getStr(map, key);
		if(data!=null && StringUtils.isNotBlank(data)) {
			try {
				JSONArray timeJson=JSONArray.parseArray(data);
				if(!timeJson.isEmpty()&&timeJson.size()==2&&StringUtils.isNotBlank(timeJson.get(0).toString())&&StringUtils.isNotBlank(timeJson.get(1).toString())) {
					map.put(key+"_begin", timeJson.get(0).toString());
					try {
						map.put(key+"_end", tomorrow(parse(timeJson.get(1).toString())));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
    public static Date tomorrow(Date today) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(today);
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);
        return calendar.getTime();
    }
    
    public static Date parse(final String dateStr) throws ParseException {
        return cn.hutool.core.date.DateUtil.parse(dateStr, YEAR_MONTH_DAY_PATTERN);
    }


    public static Date parseTime(final String dateStr) throws ParseException {
        return cn.hutool.core.date.DateUtil.parse(dateStr, YEAR_MONTH_DAY_TIME_PATTERN);
    }


    /**
     * 根据生日计算当前年龄
     *
     * @param birthday 用户生日
     * @return 当前年龄，若生日为空则返回null
     */
    public static Integer calculateAge(LocalDate birthday) {
        if (birthday == null) {
            return null;
        }
        LocalDate currentDate = LocalDate.now();
        Period period = Period.between(birthday, currentDate);
        return period.getYears();
    }

    /**
     * 根据中国大陆18位身份证号计算年龄
     *
     * @param idCard 身份证号
     * @return 当前年龄，若身份证号格式错误则返回null
     */
    public static Integer calculateAgeByIdCard(String idCard) {
        if (idCard == null || idCard.length()!= 18) {
            return null;
        }
        // 校验身份证号合法性，简单校验，更严谨需引入身份证号校验库
        boolean isValid = Pattern.matches("^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[0-1])\\d{3}[0-9Xx]$", idCard);
        if (!isValid) {
            return null;
        }
        // 提取出生年月日
        String birthYear = idCard.substring(6, 10);
        String birthMonth = idCard.substring(10, 12);
        String birthDay = idCard.substring(12, 14);
        LocalDate birthday;
        try {
            birthday = LocalDate.of(Integer.parseInt(birthYear), Integer.parseInt(birthMonth), Integer.parseInt(birthDay));
        } catch (Exception e) {
            return null;
        }
        return calculateAge(birthday);
    }
    /**
     * 计算两个日期的跨年月份差
     * @param date1 第一个日期
     * @param date2 第二个日期
     * @return 月份差值（可为负数）
     */
    public static int compareMonthsAcrossYears(Date date1, Date date2) {
        LocalDate ld1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate ld2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        // 调整为当月的第一天（避免天数影响结果）
        ld1 = ld1.withDayOfMonth(1);
        ld2 = ld2.withDayOfMonth(1);

        return (int) ChronoUnit.MONTHS.between(ld1, ld2);
    }

    /**
     * 判断两个日期是否在连续月份中（跨年有效）
     * 示例：2023-12 和 2024-01 返回 true
     */
    public static boolean areConsecutiveMonths(Date date1, Date date2) {
        int monthDiff = Math.abs(compareMonthsAcrossYears(date1, date2));
        return monthDiff == 1 || monthDiff == -1;
    }
}
