package org.jeecg.modules.quartz.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.DateUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wzq
 * @date 2025/7/14 15:29
 * @description 判断今天是工作日/周末/节假日 工具类
 * 0上班 1周末 2节假日
 */
public class HolidayUtil {

    //判断是否为节假日
    /**
     * @param time 日期参数 格式‘yyyy-MM-dd’，不传参则默认当前日期
     * @return
     */
    public static String isWorkingDay(String time,List<String> holiday,List<String> extraWorkDay) throws ParseException {
        Date parse = null;
        //为空则返回当前时间
        if (StringUtils.isNotBlank(time)) {
            SimpleDateFormat getYearFormat = new SimpleDateFormat("yyyy-MM-dd");
            parse = getYearFormat.parse(time);
        } else {
            parse = new Date();
        }
        String newDate = new SimpleDateFormat("yyyy").format(parse);

        //判断key是否有参数年份
//        if (!holiday.containsKey(newDate)) {
//            String holiday = getYearHoliday(newDate);
//            if ("No!".equals(holiday)) {
//                return "该年份未分配日期安排！";
//            }
//        }

        //得到日期是星期几
        String format = "yyyy-MM-dd";
        DateFormat df = new SimpleDateFormat(format);
        Date baseTime;
        try {
            baseTime = df.parse(time);
        } catch (Exception e) {
            return null;
        }

        //获取日期的中国式星期几（1-7分别代表周一至周日）
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(baseTime);
        int weekday = getDayOfWeek(calendar);

        //是否节假日
        if (holiday.contains(time)) {
            return "2";
        } else if (extraWorkDay.contains(time)) {//是否为调休
            return "0";
        } else if (weekday == Calendar.SATURDAY || weekday == Calendar.FRIDAY) {//是否为周末
            return "1";
        } else {
            return "0";
        }
    }

    /**
     * @param date 日期参数 格式‘yyyy’，不传参则默认当前日期
     * @return
     */
    public static Map<String,List<String>> getYearHoliday(String date) {

        HashMap<String , List<String>> map = new HashMap<>();

        //获取免费api地址
        String httpUrl = "https://timor.tech/api/holiday/year/" + date;
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();

        try {
            URL url = new URL(httpUrl);
            URLConnection connection = url.openConnection();
            //connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            connection.setRequestProperty("User-Agent", "Mozilla/4.76");
            //使用Get方式请求数据
            //connection.setRequestMethod("GET");
            //connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();

            //字符串转json
            JSONObject json = JSON.parseObject(sbf.toString());
            //根据holiday字段获取jsonObject内容
            JSONObject holiday = json.getJSONObject("holiday");
            if (holiday.size() == 0) {
                return null;
            }
            List hoList = new ArrayList<>();
            List extraList = new ArrayList<>();
            for (Map.Entry<String, Object> entry : holiday.entrySet()) {
                String value = entry.getValue().toString();
                JSONObject jsonObject = JSONObject.parseObject(value);
                String hoBool = jsonObject.getString("holiday");
                String extra = jsonObject.getString("date");
                //判断不是假期后调休的班
                if (hoBool.equals("true")) {
                    hoList.add(extra);
                } else {
                    extraList.add(extra);
                }
            }
            map.put("holiday", hoList);
            map.put("extraWorkDay", extraList);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 获得本日星期数,星期一:1,星期日:7 如果传入null则默认为本日
     *
     * @return
     */
    public static int getDayOfWeek(Calendar calendar) {
        int today;
        if (calendar != null) {
            today = calendar.get(Calendar.DAY_OF_WEEK);
        } else {
            today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
        }
        if (today == 1)
            return 7;
        else
            return today - 1;
    }

    public static List<Date> getDaysBetweenDates(Date startDate, Date endDate) {
        List<Date> dates = new ArrayList<Date>();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(startDate);

        while (calendar.getTime().before(endDate)) {
            Date result = calendar.getTime();
            dates.add(result);
            calendar.add(Calendar.DATE, 1);
        }
        return dates;
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date dt) {
//        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        String[] weekDays = {"7", "1", "2", "3", "4", "5", "6"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;

        return weekDays[w];
    }

    public static void main(String[] args) {
        int year = 2025;
        Map<String, List<String>> HolidayMap = HolidayUtil.getYearHoliday(String.valueOf(2026));
        HolidayMap.forEach((key, value) -> {
            System.out.println(key + ":" + value);
        });
        Date beginDate = DateUtils.str2Date((year + 1) + "-01-01 00:00:00", new SimpleDateFormat("yyyy-MM-dd"));
        Date endDate = DateUtils.str2Date((year + 2) + "-01-01 00:00:00", new SimpleDateFormat("yyyy-MM-dd"));
        List<Date> daysBetweenDates = getDaysBetweenDates(beginDate, endDate);
        for (Date daysBetweenDate : daysBetweenDates) {
            System.out.println(daysBetweenDate);
        }
    }

}