/**
 * 应用信息 store
 */
import { defineStore } from 'pinia';
import { getSiteInfo } from '@/api/layout';
import {AppInfo, CmsWebsite} from '@/api/cms/cmsWebsite/model';

export interface SiteState {
  // 应用信息
  siteInfo: AppInfo | null;
  // 加载状态
  loading: boolean;
  // 最后更新时间
  lastUpdateTime: number | null;
  // 缓存有效期（毫秒）
  cacheExpiry: number;
}

export const useSiteStore = defineStore({
  id: 'site',
  state: (): SiteState => ({
    siteInfo: null,
    loading: false,
    lastUpdateTime: null,
    // 默认缓存30分钟
    cacheExpiry: 30 * 60 * 1000
  }),

  getters: {
    /**
     * 获取应用ID
     */
    appId: (state): number | undefined => {
      return state.siteInfo?.appId;
    },
    /**
     * 获取应用名称
     */
    appName: (state): string => {
      return state.siteInfo?.appName || '';
    },

    /**
     * 获取应用Logo
     */
    logo: (state): string => {
      return state.siteInfo?.logo || '/logo.png';
    },

    /**
     * 获取应用描述
     */
    description: (state): string => {
      return state.siteInfo?.description || '';
    },

    /**
     * 获取小程序码
     */
    mpQrCode: (state): string => {
      return state.siteInfo?.mpQrCode || '';
    },

    /**
     * 获取应用域名
     */
    domain: (state): string => {
      return state.siteInfo?.domain || '';
    },

    /**
     * 获取应用版本
     * @param state
     */
    version: (state): string => {
      if(state.siteInfo?.version == 10){
        return '基础版'
      }
      if(state.siteInfo?.version == 20){
        return '专业版'
      }
      if(state.siteInfo?.version == 30){
        return '企业版'
      }
      return '';
    },

    statusText: (state): string => {
      return state.siteInfo?.statusText || '';
    },

    /**
     * 计算系统运行天数
     */
    runDays: (state): number => {
      if (!state.siteInfo?.createTime) return 0;
      const createTime = new Date(state.siteInfo.createTime).getTime();
      const now = new Date().getTime();
      return Math.floor((now - createTime) / (24 * 60 * 60 * 1000));
    },

    /**
     * 检查缓存是否有效
     */
    isCacheValid: (state): boolean => {
      if (!state.lastUpdateTime) return false;
      const now = Date.now();
      return (now - state.lastUpdateTime) < state.cacheExpiry;
    }
  },

  actions: {
    /**
     * 获取应用信息
     * @param forceRefresh 是否强制刷新
     */
    async fetchSiteInfo(forceRefresh = false) {
      // 如果缓存有效且不强制刷新，直接返回缓存数据
      if (!forceRefresh && this.isCacheValid && this.siteInfo) {
        return this.siteInfo;
      }

      this.loading = true;
      try {
        const data = await getSiteInfo();
        this.siteInfo = data;
        this.lastUpdateTime = Date.now();

        // 更新localStorage中的相关信息
        if (data.websiteId) {
          localStorage.setItem('WebsiteId', String(data.websiteId));
        }
        if (data.domain) {
          localStorage.setItem('Domain', data.domain);
          localStorage.setItem('SiteUrl', `${data.prefix || 'https://'}${data.domain}`);
        }

        return data;
      } catch (error) {
        console.error('获取应用信息失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 更新应用信息
     */
    updateSiteInfo(siteInfo: Partial<CmsWebsite>) {
      if (this.siteInfo) {
        this.siteInfo = { ...this.siteInfo, ...siteInfo };
        this.lastUpdateTime = Date.now();
      }
    },

    /**
     * 清除缓存
     */
    clearCache() {
      this.siteInfo = null;
      this.lastUpdateTime = null;
    },

    /**
     * 设置缓存有效期
     */
    setCacheExpiry(expiry: number) {
      this.cacheExpiry = expiry;
    }
  }
});
