package com.ruoyi.common.utils;

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author condey
 * @version $$package: com.ruoyi.common.utils, v 0.1 2024/6/25 3:03 PM condey Exp $$
 */
public class AdDateUtils {

    /**
     * 获取指定月份有几周，每周的开始日期和结束日期
     *
     * @param yearMonth
     * @return
     */
    public static Map<Integer, WeekData> weeks(YearMonth yearMonth) {
        // 获取指定月份的第一天
        LocalDate start = LocalDate.now().with(yearMonth).with(TemporalAdjusters.firstDayOfMonth());
        // 获取指定月份的最后一天
        LocalDate end = LocalDate.now().with(yearMonth).with(TemporalAdjusters.lastDayOfMonth());

        Map<Integer, WeekData> map = Stream.iterate(start, localDate -> localDate.plusDays(1l))
                .limit(ChronoUnit.DAYS.between(start, end) + 1)
                // DayOfWeek.MONDAY 这里是指定周一（MONDAY）为一周的开始
                .collect(Collectors.groupingBy(localDate -> localDate.get(WeekFields.of(DayOfWeek.MONDAY, 1).weekOfMonth()),
                        Collectors.collectingAndThen(Collectors.toList(), WeekData::new)));
        return map;

    }

    /**
     * 获取指定时期的后面月份的第一天开始时间
     *
     * @param startDate 开始时间
     * @param month     第几个月
     * @return
     */
    public static Date getMonthDate(Date startDate, int month) {
        LocalDateTime localDateTime = startDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime().plusMonths(month);
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        return date;
    }


    public static class WeekData {
        // 一周的开始时间
        private LocalDate start;
        // 一周的结束时间
        private LocalDate end;

        public WeekData(List<LocalDate> localDates) {
            this.start = localDates.get(0);
            this.end = localDates.get(localDates.size() - 1);
        }

        @Override
        public String toString() {
            return this.start + "~" + this.end;
        }

        public boolean isIn(LocalDate date) {

            if (date.isBefore(start) || date.isAfter(end)) {
                return false;
            }
            return true;
        }

    }

    public static void main(String[] args) throws Exception {
        System.out.println(weeks(YearMonth.of(2021, 4)));

        String targetStr = YearMonth.now().toString() + "-01";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = getMonthDate(sdf.parse(targetStr), 2);
        System.out.println("后2个月的时间:" + sdf.format(date));

    }
}
