package com.nantian.cloud.dbcapp.unit;



import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author suixin
 * @date 2022/7/28
 */
public class DateUtil {

    /**
     * @Description: 获取两个时间节点之间的月份列表
     * @Author: suixin
     * @Date: 2022/7/28
     * @Return: java.util.List<java.lang.String>
     * @Param: [minDate, maxDate]
     */
    public static List<String> getMonthBetween(String minDate, String maxDate){
        ArrayList<String> result = new ArrayList<String>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

            Calendar min = Calendar.getInstance();
            Calendar max = Calendar.getInstance();
            min.setTime(sdf.parse(minDate));
            min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

            max.setTime(sdf.parse(maxDate));
            max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

            Calendar curr = min;
            while (curr.before(max)) {
                result.add(sdf.format(curr.getTime()));
                curr.add(Calendar.MONTH, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 判断时间是否在时间段内
     *
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        return nowTime.getTime() >= beginTime.getTime() && nowTime.getTime() <= endTime.getTime();
    }

    public static Date parseDateByStr(String dateStr){
        Date date = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = simpleDateFormat.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * @Description: 获取当前月指定时间
     * @Author: dengjian
     *
     */
    public static String getMonthAppointDay(int year,int month,int day){
        YearMonth yearMonth = YearMonth.of(year, month);
        int maxDays = yearMonth.lengthOfMonth();
        //判断一下，如果配置的时间大于当月最后一天，则取最后一天。
        if(day > maxDays){
            day = maxDays;
        }
        LocalDate localDate = yearMonth.atDay(day);
        return localDate.toString();
    }

    /**
     * @Author: dengjian
     * @DATE: 2024/2/22 16:53
     * @Description: 判断当前时间是否大于当月最后一天，如果大于则返回当月最后一天
     *
     */
    public static String setToLastDayOfMonthIfAfter(String dateStr) {
        try {
            String[] split = dateStr.split("-");
            List<String> collect = Arrays.stream(split).collect(Collectors.toList());
            if (collect.size() == 3){
                int year = Integer.parseInt(collect.get(0));
                int month = Integer.parseInt(collect.get(1));
                int day = Integer.parseInt(collect.get(2));
                return getMonthAppointDay(year,month,day);
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 计算自定义结算时间
     * @Author: dengjian
     * @DATE: 2024/6/27 9:59
     * @param month
     * @param startDate
     * @param endDate
     * @param isMonth
     * @param customStartDate
     * @param customEndDate
     * @return java.util.Map<java.lang.String,java.lang.String>
     *
     */
    public static Map<String,String> getCustomTime(String month, String startDate, String endDate, String isMonth, String customStartDate, String customEndDate){
        Map<String,String> map = new HashMap<>();
        Integer yearInt = Integer.parseInt(month.substring(0, 4));
        Integer monthInt = Integer.parseInt(month.substring(5, 7));
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        if (StringUtils.isNotBlank(customStartDate) && StringUtils.isNotBlank(customEndDate)){
            Integer startYear = yearInt;
            Integer endYear = yearInt;
            //判断一下是否跨年的情况，同时取月份，如果当前结算月份为1月份，那么开始时间12月份，结束时间1月份，则取上一年，如果当前结算月份是12月份，则
            //开始时间12月份，结束时间1月份，则结束时间取下一年
            if("12".equals(customStartDate.split("-")[0]) && "01".equals(customEndDate.split("-")[0])){
                if(monthInt == 1){
                    startYear -= 1;
                }
                if(monthInt == 12){
                    endYear += 1;
                }
            }
            map.put("startDate",DateUtil.setToLastDayOfMonthIfAfter(startYear + "-" + customStartDate));
            map.put("endDate",DateUtil.setToLastDayOfMonthIfAfter(endYear + "-" + customEndDate));
        }else{
            //取当月的自定义结算时间。是否跨月，不跨月则都取本月的时间范围
            if("1".equals(isMonth)){

                map.put("startDate",DateUtil.getMonthAppointDay(yearInt,monthInt,Integer.parseInt(startDate)));
                //跨月，月份加一，大于12月份后，则跨年计算
                monthInt = Integer.parseInt(month.substring(5, 7)) + 1;
                if (monthInt > 12){
                    yearInt = yearInt + 1;
                    monthInt = 1;
                }

                map.put("endDate",DateUtil.getMonthAppointDay(yearInt, monthInt,Integer.parseInt(endDate)));
            }else{

                map.put("startDate",DateUtil.getMonthAppointDay(yearInt,monthInt,Integer.parseInt(startDate)));
                map.put("endDate",DateUtil.getMonthAppointDay(yearInt, monthInt,Integer.parseInt(endDate)));
            }
        }
        return map;

    }

    /**
     * 获取日期范围内的所有日期列表
     * @param startDateStr
     * @param endDateStr
     * @return
     */
    public static List<String> getBetweenDateStr(String startDateStr,String endDateStr){
        List<String> dateList = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try{
            Date startDate = dateFormat.parse(startDateStr);
            Date endDate = dateFormat.parse(endDateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            while(calendar.getTime().before(endDate)){
                dateList.add(dateFormat.format(calendar.getTime()));
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
            dateList.add(dateFormat.format(endDate));
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return dateList;
    }

    /**
     * @Description:  获取某月第一天
     * @Author: dengjian
     * @DATE: 2024/11/12 15:11
     * @param yearMonthStr
     * @return java.lang.String
     *
     */
    public static String getFirstDayOfMonth(String yearMonthStr) throws DateTimeParseException {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 解析输入字符串为 YearMonth 对象
        YearMonth yearMonth = YearMonth.parse(yearMonthStr, formatter);
        // 获取该月份的第一天
        LocalDate firstDay = yearMonth.atDay(1);
        return firstDay.format(dtf);
    }
    /**
     * @Description:  获取某月最后一天
     * @Author: dengjian
     * @DATE: 2024/11/12 15:10
     * @param yearMonthStr
     * @return java.lang.String
     *
     */
    public static String getLastDayOfMonth(String yearMonthStr) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 尝试解析输入字符串
        YearMonth yearMonth;
        try {
            yearMonth = YearMonth.parse(yearMonthStr, formatter);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid date format. Please use 'yyyy-MM'.", e);
        }
        // 获取该月的最后一天
        return yearMonth.atEndOfMonth().format(dtf);
    }





}
