/**
 * 网站配置 store
 */
import { defineStore } from 'pinia';
import { configWebsiteField } from '@/api/cms/cmsWebsiteField';
import type { Config } from '@/api/cms/cmsWebsiteField/model';

export interface ConfigState {
  config: Config | null;
  loading: boolean;
  error: Error | null;
}

export const useConfigStore = defineStore({
  id: 'config',
  state: (): ConfigState => ({
    // 网站配置数据
    config: null,
    // 加载状态
    loading: false,
    // 错误信息
    error: null
  }),
  getters: {
    /**
     * 获取网站配置
     */
    getConfig(state): Config | null {
      return state.config;
    },

    /**
     * 获取API地址
     */
    getApiUrl(state): string | undefined {
      return state.config?.ApiUrl;
    },

    /**
     * 获取网站名称
     */
    getSiteName(state): string | undefined {
      return state.config?.siteName;
    },

    /**
     * 获取网站Logo
     */
    getSiteLogo(state): string | undefined {
      return state.config?.siteLogo;
    }
  },
  actions: {
    /**
     * 获取网站配置数据
     */
    async fetchConfig() {
      try {
        this.loading = true;
        this.error = null;
        const data = await configWebsiteField();
        this.config = data;

        // 保存到localStorage中，供其他地方使用
        localStorage.setItem('config', JSON.stringify(data));

        // 设置主题
        if (data.theme && !localStorage.getItem('user_theme')) {
          localStorage.setItem('user_theme', data.theme);
        }

        return data;
      } catch (err) {
        this.error = err instanceof Error ? err : new Error('获取配置失败');
        console.error('获取网站配置失败:', err);
        throw err;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 更新配置数据
     */
    setConfig(value: Config) {
      this.config = value;
      // 同时更新localStorage
      localStorage.setItem('config', JSON.stringify(value));
    },

    /**
     * 重新获取配置数据
     */
    async refetchConfig() {
      try {
        this.loading = true;
        this.error = null;
        const data = await configWebsiteField();
        this.config = data;
        localStorage.setItem('config', JSON.stringify(data));
        return data;
      } catch (err) {
        this.error = err instanceof Error ? err : new Error('获取配置失败');
        console.error('重新获取网站配置失败:', err);
        throw err;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 清除配置数据
     */
    clearConfig() {
      this.config = null;
      localStorage.removeItem('config');
    }
  }
});
