package com.ho.common.tools.util;

import com.ho.common.tools.constant.CommonConstant;
import com.alibaba.excel.util.DateUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author fancl
 * @desc:
 * @date 2023/5/5
 */
public class DateNewUtil {

    public static void main(String[] args) {
        String begin = "2023-03-04";
        String end = "2023-05-04";
        List<String> betweenDates = DateNewUtil.getBetweenDates(begin, end, true);
        System.out.println();
    }


    public static List<String> getBetweenDates(String startTime, String endTime, boolean isIncludeStartTime){
        List<String> result = new ArrayList<>();
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date d1 = new SimpleDateFormat("yyyy-MM-dd").parse(startTime);//定义起始日期
            Date d2 = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);//定义结束日期  可以去当前月也可以手动写日期。
            Calendar dd = Calendar.getInstance();//定义日期实例
            dd.setTime(d1);//设置日期起始时间
            if(isIncludeStartTime) {
                result.add(format.format(d1));
            }
            while (dd.getTime().before(d2)) {//判断是否到结束日期
                dd.add(Calendar.DATE, 1);//进行当前日期加1
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String str = sdf.format(dd.getTime());
                result.add(str);
                System.out.println(str);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


    /**
     * 获取最靠近当前时间特定间隔的时间点
     * @param date 时间
     * @param interval 间隔
     * @param flow 方向 0代表向下，1代表向上
     * @return
     */
    public static Date roundToNearestQuarter(Date date,Integer interval,Integer flow) {
        Calendar time = Calendar.getInstance();
        time.setTime(date);
        int minutes = time.get(Calendar.MINUTE);
        int newMinutes = (minutes / interval) * interval;
        Float middle = interval/CommonConstant.F_TWO;
        if(flow != null){
            if(CommonConstant.ZERO.equals(flow)){
                time.set(Calendar.MINUTE, newMinutes);
            }else if(CommonConstant.ONE.equals(flow)){
                newMinutes += interval;
                time.set(Calendar.MINUTE, newMinutes);
            }
        }else{
            if (minutes - newMinutes < middle) {
                // 如果距离小于一半，向下舍入
                time.set(Calendar.MINUTE, newMinutes);
            } else {
                // 如果距离大于或等于一半，向上舍入
                newMinutes += interval;
                time.set(Calendar.MINUTE, newMinutes);
            }
        }
        // 将秒数设置为0
        time.set(Calendar.SECOND, 0);
        return time.getTime();
    }
}
