package com.njcn.harmonic.util;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Year;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class TimeUtil {

    /**
     * 根据传入的月份数获取时间集合
     * @param month
     * @return
     */
    public static List<YearMonth> getLastThreeMonth(int month) {
        //按月获取时间集合
        LocalDate currentDate = LocalDate.now();
        int currentYear = currentDate.getYear();
        LocalDate beginDay = LocalDate.of(currentYear, 1, 1);
        List<YearMonth> monthList = getMonthsBetween(beginDay,currentDate);
        if (monthList.size() > month) {
            monthList = monthList.subList(monthList.size() - month,monthList.size());
        }
        return monthList;
    }

    public static List<YearMonth> getMonthsBetween(LocalDate startDate, LocalDate endDate) {
        List<YearMonth> months = new ArrayList<>();
        YearMonth currentMonth = YearMonth.from(startDate);
        YearMonth endMonth = YearMonth.from(endDate);
        while (!currentMonth.isAfter(endMonth)) {
            months.add(currentMonth);
            currentMonth = currentMonth.plusMonths(1);
        }
        return months;
    }

    public static List<Integer> getLastFiveYear(int year) {
        List<Integer> yearList = new ArrayList<>();
        LocalDate currentDate = LocalDate.now();
        int currentYear = currentDate.getYear();
        for (int i = year; i >= 0; i--) {
            yearList.add(currentYear - i);
        }
        return yearList;
    }

    public static String getYearFirst(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(currYearFirst);
    }

    public static String getYearLast(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        return new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
    }
}
