import { defineStore } from 'pinia' import { ref, watch } from 'vue' import { isAfterSunset, getMsUntilNextSwitch } from '../utils/sunset' export const useThemeStore = defineStore('theme', () => { const STORAGE_KEY = 'onu-theme' const savedTheme = localStorage.getItem(STORAGE_KEY) // 无手动偏好时,根据广西日落时间自动选择 const theme = ref(savedTheme || (isAfterSunset() ? 'dark' : 'light')) const applyTheme = (t) => { document.documentElement.setAttribute('data-theme', t) } let switchTimer = null // 初始化时立即应用 applyTheme(theme.value) // 设置日落/日出自动切换定时器,仅在用户未手动选择时生效 const scheduleAutoSwitch = () => { if (switchTimer) clearTimeout(switchTimer) // 始终在日落/日出时自动切换 const delay = getMsUntilNextSwitch() switchTimer = setTimeout(() => { theme.value = isAfterSunset() ? 'dark' : 'light' scheduleAutoSwitch() // 递归调度下一次 }, delay + 60000) // 加 1 分钟余量 } scheduleAutoSwitch() // 切换 const toggle = () => { theme.value = theme.value === 'dark' ? 'light' : 'dark' } // 监听变化:同步到 DOM + localStorage watch(theme, (t) => { applyTheme(t) localStorage.setItem(STORAGE_KEY, t) }) return { theme, toggle } })