import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getActiveNotices } from '@/api/notice'

export const useNoticeStore = defineStore('notice', () => {
  // 状态
  const notices = ref([])
  const isLoading = ref(false)
  const dismissedIds = ref([]) // 当前会话已关闭的公告 ID
  const lastFetchTime = ref(null)
  const useMock = ref(false) // 后台接口就绪后改为 false

  // 过滤已关闭公告后的有效列表
  const activeNotices = computed(() =>
    notices.value.filter(n => !dismissedIds.value.includes(n.id))
  )

  // info 或无 category 的公告 → 滚动栏显示 title
  const infoNotices = computed(() =>
    activeNotices.value.filter(n => !n.category || n.category === 'info')
  )

  // danger / warning 的公告 → 弹窗显示 title + content
  const alertNotices = computed(() =>
    activeNotices.value.filter(n => n.category === 'danger' || n.category === 'warning')
  )

  // 是否有可显示的公告
  const hasNotices = computed(() => activeNotices.value.length > 0)

  /**
   * 从后台拉取公告
   * 全局 axios 拦截器在 code==0 时返回 response.data.data，即数组本身
   */
  const fetchNotices = async () => {
    if (isLoading.value) return
    if (useMock.value) {
      loadMockNotices()
      return
    }

    isLoading.value = true
    try {
      const res = await getActiveNotices()
      console.log('[NoticeStore] 获取公告', res)
      notices.value = Array.isArray(res) ? res.filter(n => !n.deleted) : []
      lastFetchTime.value = Date.now()
    } catch (error) {
      console.error('[NoticeStore] 获取公告失败:', error)
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 关闭某条公告（仅当前会话生效）
   */
  const dismissNotice = (id) => {
    if (!dismissedIds.value.includes(id)) {
      dismissedIds.value.push(id)
    }
  }

  /**
   * 加载 Mock 数据（后台接口未就绪时使用）
   */
  const loadMockNotices = () => {
    notices.value = [
      { id: 1, title: 'YOLO 系统公告', content: '<p>欢迎使用 Yolo 系统，如有问题请联系管理员。</p>', category: 'info' },
      { id: 2, title: '系统维护通知', content: '<p>系统将于本周六凌晨 2:00-4:00 进行维护升级，届时服务将暂停，请提前做好安排。</p>', category: 'warning' },
      { id: 3, title: '紧急安全通知', content: '<p>请所有用户立即更新客户端至最新版本。</p>', category: 'danger' },
    ]
    lastFetchTime.value = Date.now()
  }

  return {
    // 状态
    notices,
    activeNotices,
    infoNotices,
    alertNotices,
    hasNotices,
    isLoading,
    useMock,

    // 方法
    fetchNotices,
    dismissNotice,
    loadMockNotices,
  }
})
