package com.cf.imes.framework.common.util.time;

import cn.hutool.core.util.ObjectUtil;
import com.cf.imes.framework.common.enums.OrderStatisticsUnit;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

/**
 * 统计时间转换工具类
 */
public class StatisticsChangeUtils {

    /**
     * 获取日期区间格式下的所有日期字符串
     * 1、reqVO设置机构id
     * 2、计算时间跨度设置到reqVO
     * 3、返回所有日期的集合
     * @return
     */
    public static List<String> getDateList(LocalDate[] createTime, Integer unit) {
        // 计算时间跨度
        getTimeSpan(createTime, unit);

        // 所有的日期集合
        return generateDateRange(createTime, unit);
    }

    /**
     * 获取统计的时间跨度
     * 计算起止时间：前端不传入时间就根据维度单位从当前日期计算
     *
     */
    public static LocalDate[] getTimeSpan(LocalDate[] createTime, Integer unit) {
        LocalDate startTime = null;
        LocalDate endTime;
        LocalDate now = LocalDate.now();
        if (ObjectUtil.isNull(createTime) || ObjectUtil.isNull(createTime[0]) || ObjectUtil.isNull(createTime[1])) {
            endTime = now;
            switch (OrderStatisticsUnit.fromValue(unit)) {
                case QUARTER:
                    // 从now往前的2年
                    startTime = now.minusYears(2);
                    break;
                case MONTH:
                    // 包含now往前的12个月
                    startTime = now.minusMonths(11);
                    break;
                case WEEK:
                    // 包含now往前的12周
                    startTime = now.minusWeeks(11);
                    break;
                case DAY:
                    // 包含now往前的15天
                    startTime = now.minusDays(14);
                    break;
                default:
                    break;
            }
            // 声明一个LocalDateTime的数组，把startTime和endTime放进去
            createTime[0] = startTime;
            createTime[1] = endTime;
        }
        return  createTime;
    }

    /**
     * 获取日期范围内的所有格式字符串
     *
     * @return
     */
    public static List<String> generateDateRange(LocalDate[] createTime, Integer unit) {
        // 计算时间跨度
        getTimeSpan(createTime, unit);
        // 计算后的开始和结束时间
        LocalDate startDate = ObjectUtil.clone(createTime[0]);
        LocalDate endDate = ObjectUtil.clone(createTime[1]);

        List<String> dates = new ArrayList<>();
        while (!startDate.isAfter(endDate)) {
            String dateStr;
            switch (OrderStatisticsUnit.fromValue(unit)) {
                case QUARTER:
                    dateStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-Q"));
                    // 加一季度（3个月）
                    startDate = startDate.plusMonths(3);
                    break;
                case MONTH:
                    dateStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-M"));
                    // 加一月
                    startDate = startDate.plusMonths(1);
                    break;
                case WEEK:
                    // 使用自定义格式表示月份
                    dateStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-M"));
                    // 计算从月份第一天到当前日期经过了多少周
                    LocalDate monthStart = startDate.with(TemporalAdjusters.firstDayOfMonth());
                    long weeksInMonth = ChronoUnit.WEEKS.between(monthStart, startDate) + 1;
                    dateStr = dateStr + "-" + weeksInMonth;
                    // 加一周
                    startDate = startDate.plusWeeks(1);
                    break;
                case DAY:
                    dateStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-M-d"));
                    // 加一天
                    startDate = startDate.plusDays(1);
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported unit: " + unit);
            }
            dates.add(dateStr);
        }
        return dates;
    }

    /**
     * 构建日期格式到图标横轴可用格式
     * 2024-1 -> 2024年第1季度
     * 2024-1-1 -> 2024年1月
     * ...
     * @param unit
     * @return
     */
    public static String generateDateRangeAxis(String date, Integer unit) {
        OrderStatisticsUnit orderStatisticsUnit = OrderStatisticsUnit.fromValue(unit);
        StringBuilder newDateStrBuffer = new StringBuilder();
        String[] dateSplit = date.split("-");
        switch (orderStatisticsUnit) {
            case QUARTER:
                newDateStrBuffer.append("第").append(dateSplit[1]).append("季度");
                break;
            case MONTH:
                newDateStrBuffer.append(dateSplit[1]).append("月");
                break;
            case WEEK:
                newDateStrBuffer.append("第").append(dateSplit[2]).append("周");
                break;
            case DAY:
                newDateStrBuffer.append(dateSplit[2]);
                break;
            default:
        }
        return newDateStrBuffer.toString();
    }
}
