package com.junmp.jyzb.utils;

import cn.hutool.core.util.ObjectUtil;
import com.junmp.jyzb.api.exception.enums.InventoryExceptionEnum;
import com.junmp.v2.common.exception.base.ServiceException;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class DateTimeUtil {
    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static Date getCurrentDateTime() {
        Date currentDate = new Date();
        String dateString = DATE_FORMAT.format(currentDate);
        try {
            return DATE_FORMAT.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static List<Map<String,Object>> timeSort(List<Map<String,Object>> allPoliceman) {
        Collections.sort(allPoliceman, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Date updateTime1 = (Date) o1.get("updateTime");
                Date updateTime2 = (Date) o2.get("updateTime");
                return updateTime2.compareTo(updateTime1);
            }
        });
        return allPoliceman;
    }

    //时间戳转时间(Long->String)
    public static String TimeLongToString(Long time){
        //时间戳转时间Date
        if (ObjectUtil.isNotNull(time)){
            Date updateTime = new Date(time*1000);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date= format.format(updateTime);
            return date;
        }else {
            return null;
        }
    }



    //String->Long(将string类型的时间转成时间戳)
    public static Long TimeStringToLong(String time){
        if (ObjectUtil.isNotNull(time) && !time.trim().isEmpty()){
            Date date = null;
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                date = sdf.parse(time);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            long timestamp = date.getTime();
            return timestamp;
        }else {
            return null;
        }
    }
    //Date->Long (将date类型转为Long)
    public static Long TimeDateToLong(Date time){
        if (ObjectUtil.isNotNull(time)){
            long time1 = time.getTime();
            return time1;
        }else {
            return null;
        }
    }


    public static Date TimeStringToDateWithFormat(String time,String[] style){
        Date parse = null;
        for (String pattern :style) {

            SimpleDateFormat format = new SimpleDateFormat(pattern);
            format.setLenient(false);
            try {
                parse = format.parse(time);
                if (parse!=null){
                    return parse;
                }
            } catch (ParseException e) {
                throw new ServiceException(InventoryExceptionEnum.TIME_ERROR);
            }
        }
        return parse;
    }
    //String  -> Date(将string类型转成Date)
    public static Date TimeStringToDate(String time,String pattern){
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date parse = null;
        try {
            parse = format.parse(time);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return parse;
    }
    //将Date ->String （将Date转成String
    public static String TimeDateToString(Date time,String rule){
        SimpleDateFormat format = new SimpleDateFormat(rule);
        String format1 = format.format(time);
        return format1;
    }

    //获取当前时间年月日，时分秒都为0（获取当前时间）
    public static Date DateByDays(){
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = today.atStartOfDay().format(formatter);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date();
        try {
            date = sdf.parse(formattedDateTime);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    //将时分秒转成00:00:00(根据指定时间进行传递返回)
    public static  Date DaysToZero(Date time){


            // 将Date转换为Instant
        Instant instant = time.toInstant();

// 获取默认时区的ZonedDateTime对象
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());

// 将ZonedDateTime转换为LocalDateTime对象
        LocalDateTime dateTime = zonedDateTime.toLocalDateTime();

// 将时分秒部分设置为0
        LocalDateTime newDateTime = dateTime.with(LocalTime.MIN);

// 将LocalDateTime转换为Date
        Date newDate = Date.from(newDateTime.atZone(ZoneId.systemDefault()).toInstant());


        return newDate;
    }

    //将时分秒转成23:59:59
    public static Date setTimeToMax(Date time) {

            // 将Date转换为Instant
        Instant instant = time.toInstant();

        // 获取默认时区的ZonedDateTime对象
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());

        // 将ZonedDateTime转换为LocalDateTime对象
        LocalDateTime dateTime = zonedDateTime.toLocalDateTime();

        // 将时分秒部分设置为23:59:59
        LocalDateTime newDateTime = dateTime.with(LocalTime.MAX);

        // 将LocalDateTime转换为Date
        Date newDate = Date.from(newDateTime.atZone(ZoneId.systemDefault()).toInstant());

        return newDate;
    }

    //返回指定时间后指定月份的时间（如：返回2024-07-01 00：00：00后6个月的时间，那返回结果就是2024-08-01 00：00：00）
    public static Date addMonsAfterDate(Date time,Integer months){
        if (ObjectUtil.isNull(months) || months==0){
            return null;
        }
        if (ObjectUtil.isNull(time)){
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.MONTH, months);
        time = calendar.getTime();
        return time;
    }

    /**
     *  获取当前年月的最后一天（如2025-09，返回2025-09-30 23：59：59）
     */
    public static String getLastDayOfMonth(String yearMonth) {
        LocalDate date = LocalDate.parse(yearMonth + "-01");
        LocalDate lastDay = date.withDayOfMonth(date.lengthOfMonth());
        LocalDateTime localDateTime = lastDay.atTime(23, 59, 59);
        return localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

}