package com.cpp.web.utils;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class StartAndEndMonthUtil {
    public static List<long[]> singleMonth(Long startTime, Long endTime){
        LocalDate startDate = new Date(startTime).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endDate = new Date(endTime).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        List<long[]> segments = new ArrayList<>();

        while (startDate.isBefore(endDate) || startDate.isEqual(endDate)) {
            LocalDate nextMonth = startDate.plusMonths(1);
            long startSegment = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
            long endSegment = nextMonth.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();

            // 确保结束时间不超过原始的结束时间
            if (endSegment > endTime) {
                endSegment = getBeginAndEndMonth(endTime,2);
            }

            segments.add(new long[]{startSegment, endSegment});

            startDate = nextMonth;
        }
        return segments;
    }

    public static Long getBeginAndEndMonth(Long temp,Integer type){
        long newTemp = 0;
        // 将时间戳转换为 LocalDate
        LocalDate date = Instant.ofEpochMilli(temp)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        if (type == 1){
            // 获取该月的第一天
            LocalDate firstDayOfMonth = date.withDayOfMonth(1);

            // 将 LocalDate 转换回时间戳
            newTemp = firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
        }else {
            // 获取该月的最后一天
            LocalDate lastDayOfMonth = date.withDayOfMonth(date.lengthOfMonth());

            // 将 LocalDate 转换回时间戳
            newTemp = lastDayOfMonth.atTime(23, 59, 59, 999999999)
                    .atZone(ZoneId.systemDefault())
                    .toInstant()
                    .toEpochMilli();
        }
        return newTemp;
    }
}
