package com.ruoyi.app.utils;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DictUtils;
import lombok.SneakyThrows;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class DateUtil {

    /**
     * 检查当前时间是否接近或已超过开始时间
     * @param time 时间字符串，格式：2025-11-13 16:00-17:00
     * @param minute 分钟数，例如30
     * @return true：当前时间距离开始时间小于等于minute分钟，或者已经超过开始时间；false：其他情况
     */
    @SneakyThrows
    public static boolean isNearOrPastStartTime(String time,int minute){
        if (time == null || time.isEmpty()) {
            return false;
        }

        // 解析时间字符串，提取日期和开始时间
        // 格式：2025-11-13 16:00-17:00
        String trimmedTime = time.trim();
        String[] parts = trimmedTime.split(" ");
        if (parts.length != 2) {
            return false;
        }

        String dateStr = parts[0].trim(); // 2025-11-13
        String timeRange = parts[1].trim(); // 16:00-17:00

        // 提取开始时间
        String startTimeStr = timeRange.split("-")[0].trim(); // 16:00

        // 构建完整的开始时间字符串
        String fullStartTimeStr = dateStr + " " + startTimeStr + ":00"; // 2025-11-13 16:00:00

        // 解析开始时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime = sdf.parse(fullStartTimeStr);

        // 获取当前时间
        Date currentTime = new Date();

        // 计算时间差（毫秒）
        long diffMillis = startTime.getTime() - currentTime.getTime();

        // 转换为分钟
        long diffMinutes = diffMillis / (1000 * 60);

        // 判断：如果当前时间距离开始时间小于等于minute分钟，或者已经超过开始时间，返回true
        // diffMinutes <= minute 表示距离开始时间还有minute分钟以内
        // diffMinutes <= 0 表示已经超过或等于开始时间
        return diffMinutes <= minute;
    }

    /**
     * 获取预约订单距离预约时间多少分钟处理为显示的时间
     * @return
     */
    public static int getAppoinmentOrderHandleTime(){
        int minute=60;
        List<SysDictData> datas= DictUtils.getDictCache("sys_appointorder_handletime");
        if (datas != null && !datas.isEmpty()) {
            minute=Integer.parseInt(datas.get(0).getDictValue());
        }
        return minute;
    }

    //获取当前时间戳
    public Long getTimeMillis() throws ParseException {
        return System.currentTimeMillis();
    }
    //判断多少天后的日期
    public String addDate(String date,int days) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = format.parse(date);
        calendar.setTime(parse);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        // days  多少天后的日期
        int newDay = day+days;
        calendar.set(Calendar.YEAR,year);
        calendar.set(Calendar.MONTH,month);
        calendar.set(Calendar.DAY_OF_MONTH,newDay);
        return format.format(calendar.getTime());
    }
    //时间字符串转为时间
    @SneakyThrows
    public Date getDatetim(String dateString) {

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = dateFormat.parse(dateString);
        return date;
    }
    //转换时间为字符串
    public String setDate(Date date) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }

    //获取当前日期
    public String GetDate() {
        Calendar calendar = Calendar.getInstance(); // get current instance of the calendar
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(calendar.getTime());
    }
    //获取当前日期(不带时间)
    public String GetDateNt() {
        Calendar calendar = Calendar.getInstance(); // get current instance of the calendar
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(calendar.getTime());
    }
    //获取当前日期(无格式)
    public String GetDatewjg() {
        Calendar calendar = Calendar.getInstance(); // get current instance of the calendar
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        return formatter.format(calendar.getTime());
    }
    @SneakyThrows
    public  boolean isLegalTime(String startTime, String endTime){
        Date currentDate = new Date();
        String format = "HH:mm";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String nowtTime = sdf.format(currentDate);
        Date nowDate = sdf.parse(nowtTime);
        Date startDate = sdf.parse(startTime);
        Date endDate = sdf.parse(endTime);

        if (nowDate.getTime() == startDate.getTime()
                || nowDate.getTime() == endDate.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowDate);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startDate);

        Calendar end = Calendar.getInstance();
        end.setTime(endDate);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    //判断日期是否小于当前日期
    public boolean isPastDate(String str){

        boolean flag = false;
        Date nowDate = new Date();
        Date pastDate = null;
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.CHINA);
        //在日期字符串非空时执行
        if (str != null && !"".equals(str)) {
            try {
                //将字符串转为日期格式，如果此处字符串为非合法日期就会抛出异常。
                pastDate = sdf.parse(str);
                //调用Date里面的before方法来做判断
                flag = pastDate.before(nowDate);
                if (flag) {
                    System.out.println("该日期早于今日");
                }else {
                    System.out.println("该日期晚于今日");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("日期参数不可为空");
        }
        return flag;
    }

    /**
     * 获取指定秒数之后的时间,返回小时和分钟
     * @param seconds
     * @return
     */
    public String getHourAndMinute(long seconds) {
        LocalTime now = LocalTime.now(); // 当前时间
        LocalTime newTime = now.plusSeconds(seconds); // 加上秒数
        String result = newTime.format(DateTimeFormatter.ofPattern("HH:mm"));
        return result;
    }
}
