import { defineStore } from 'pinia'
import { ref } from 'vue'
import { get } from '@/utils/request'

const STORAGE_KEY = 'announcement_popup_last_id'

interface SystemAnnouncement {
  id: number | string
  title: string
  content: string
  createTime: string
  isShow: boolean
  isPopup: boolean
  imgUrl: string
}

export const useSystemAnnouncementStore = defineStore('systemAnnouncement', () => {
  const announcement = ref<SystemAnnouncement | null>(null)
  const loading = ref(false)
  const showModal = ref(false)
  const checked = ref(false)

  function wasShown(id: number | string): boolean {
    try {
      const cached = localStorage.getItem(STORAGE_KEY)
      return cached === String(id)
    } catch {
      return false
    }
  }

  function markShown(id: number | string) {
    try {
      localStorage.setItem(STORAGE_KEY, String(id))
    } catch { /* 静默处理 */ }
  }

  async function check() {
    if (loading.value || checked.value) { return }

    loading.value = true
    try {
      const res = await get<SystemAnnouncement>('uc/announcement/system')
      console.log('[系统公告] API返回:', res)
      if (res && res.isShow && !wasShown(res.id)) {
        console.log('[系统公告] 准备弹窗, id:', res.id)
        announcement.value = res
        showModal.value = true
      }
    } catch (e) {
      console.log('[系统公告] 请求失败:', e)
    } finally {
      loading.value = false
      checked.value = true
    }
  }

  function dismiss() {
    showModal.value = false
    if (announcement.value) {
      markShown(announcement.value.id)
    }
  }

  function reset() {
    checked.value = false
  }

  return {
    announcement,
    loading,
    showModal,
    checked,
    check,
    dismiss,
    reset,
  }
})
