import { defineStore } from 'pinia';
import { getWebsiteSetting } from '@/api/system/websiteSetting';
import { WebsiteSettingVO } from '@/api/system/websiteSetting/types';

/**
 * 网站全局配置设置
 */
export const useWebsiteStore = defineStore('website', () => {
  const websiteConfig = ref<WebsiteSettingVO>({
    id: 0,
    icon: 0,
    iconUrl: '',
    title: '',
    loginTitle: '',
    loginBackground: 0,
    loginBackgroundUrl: '',
    menuTitle: ''
  });

  /**
   * 获取网站设置详情
   */
  const getWebsiteConfig = async () => {
    try {
      const res = await getWebsiteSetting(2);
      if (res && res.data) {
        websiteConfig.value = res.data;
        // 更新网站标题和图标
        updatePageBranding();
      }
    } catch (error) {
      console.error('获取网站设置失败:', error);
    }
  };

  /**
   * 更新页面的标题和 favicon 图标
   */
  const updatePageBranding = () => {
    if (websiteConfig.value.title) {
      document.title = websiteConfig.value.title;
    }
    if (websiteConfig.value.iconUrl) {
      let iconLink = document.querySelector('link[rel~="icon"]') as HTMLLinkElement;
      if (!iconLink) {
        iconLink = document.createElement('link');
        iconLink.rel = 'icon';
        document.getElementsByTagName('head')[0].appendChild(iconLink);
      }
      iconLink.href = websiteConfig.value.iconUrl;
    }
  };

  return {
    websiteConfig,
    getWebsiteConfig,
    updatePageBranding
  };
});
