import { computed, ref } from 'vue'

const STORAGE_KEY = 'ruoyi_screen_stat_year'
const currentCalendarYear = new Date().getFullYear()
/** 全局统计年份可选下限（含） */
const STAT_YEAR_MIN = 2021

/**
 * 从最低年到结束年（含），降序
 * @param {number} [endYear]
 * @param {number} [minYear]
 */
function buildYearOptions(endYear = currentCalendarYear, minYear = STAT_YEAR_MIN) {
  const end = Number(endYear)
  const start = Number(minYear)
  if (!Number.isFinite(end) || !Number.isFinite(start) || end < start) {
    return [start]
  }
  const years = []
  for (let y = end; y >= start; y--) {
    years.push(y)
  }
  return years
}

function readStoredYear() {
  try {
    const raw = sessionStorage.getItem(STORAGE_KEY)
    if (raw && /^\d{4}$/.test(raw)) {
      const y = Number(raw)
      if (y >= STAT_YEAR_MIN && y <= 2100) {
        return String(y)
      }
    }
  } catch {
    /* ignore */
  }
  return String(currentCalendarYear)
}

/** 若存储年不在可选范围内，回落到当年 */
function clampToAvailableYears(yearStr) {
  const years = buildYearOptions()
  const y = Number(yearStr)
  if (years.includes(y)) {
    return String(y)
  }
  return String(years[0])
}

/** 全局统计年份 YYYY（字符串，与各看板接口一致） */
const statYear = ref(clampToAvailableYears(readStoredYear()))

/** 可选年份：2021～当年（降序） */
const availableYears = ref(buildYearOptions())

function persistYear(year) {
  try {
    sessionStorage.setItem(STORAGE_KEY, String(year))
  } catch {
    /* ignore */
  }
}

/**
 * 设置全局统计年份；值未变则返回 false
 * @param {string|number} year
 * @returns {boolean}
 */
export function setStatYear(year) {
  const next = String(year ?? '').trim()
  if (!/^\d{4}$/.test(next)) {
    return false
  }
  const clamped = clampToAvailableYears(next)
  if (clamped === statYear.value) {
    return false
  }
  statYear.value = clamped
  persistYear(clamped)
  return true
}

/**
 * 刷新可选年份为 2021～当年；选中年若超出范围则回落当年。
 * （保留入参兼容各页 mergeAvailableYears 调用，不再并集扩展）
 * @param {Array<number|string>|null|undefined} [_years]
 */
export function mergeAvailableYears(_years) {
  availableYears.value = buildYearOptions()
  const clamped = clampToAvailableYears(statYear.value)
  if (clamped !== statYear.value) {
    statYear.value = clamped
    persistYear(clamped)
  }
}

/**
 * 大屏全局统计年份（ScreenNavBar 与各页面共用）
 */
export function useStatYear() {
  const yearModel = computed({
    get: () => statYear.value,
    set: (v) => setStatYear(v)
  })

  return {
    statYear,
    availableYears,
    yearModel,
    setStatYear,
    mergeAvailableYears
  }
}
