import type { AnnouncementLogDto } from '@/api';
import { defineStore } from 'pinia';

export type CloseType = 'today' | 'permanent';

export const useAnnouncementStore = defineStore(
  'announcement',
  () => {
    // 弹窗显示状态
    const isDialogVisible = ref(false);

    // 公告数据（统一存储所有公告）
    const announcements = ref<AnnouncementLogDto[]>([]);

    // 关闭记录
    const closeType = ref<CloseType | null>(null);
    const closedAt = ref<number | null>(null);

    // 打开弹窗
    const openDialog = () => {
      isDialogVisible.value = true;
    };

    // 关闭弹窗
    const closeDialog = (type: CloseType) => {
      isDialogVisible.value = false;
      closeType.value = type;
      closedAt.value = Date.now();
    };

    // 检查是否应该显示弹窗
    const shouldShowDialog = computed(() => {
      if (!closedAt.value || !closeType.value)
        return true;

      const now = Date.now();
      const elapsed = now - closedAt.value;

      if (closeType.value === 'permanent')
        return true;

      if (closeType.value === 'today') {
        // 检查是否已过去一周（7天）
        return elapsed > 7 * 24 * 60 * 60 * 1000;
      }

      return true;
    });

    // 设置公告数据
    const setAnnouncementData = (data: AnnouncementLogDto[]) => {
      announcements.value = data;
    };

    // 重置关闭状态（用于测试或管理员重置）
    const resetCloseStatus = () => {
      closeType.value = null;
      closedAt.value = null;
    };

    return {
      isDialogVisible,
      announcements,
      closeType,
      closedAt,
      shouldShowDialog,
      openDialog,
      closeDialog,
      setAnnouncementData,
      resetCloseStatus,
    };
  },
  {
    persist: {
      // 只持久化关闭状态相关的数据，公告数据不缓存
      paths: ['closeType', 'closedAt'],
    },
  },
);
