import { preferencesManager } from '@vben/preferences';

import { ref } from 'vue';

/** 登录页品牌 Logo，未配置时为空 */
export const appearanceLogoUrl = ref('');
/** 登录页背景图，未配置时为空 */
export const appearanceLoginBackgroundUrl = ref('');

/** 首次应用时记录的默认 Logo，用于清除配置后回退 */
let defaultLogoSource: string | undefined;

interface AppearancePayload {
  logoUrl?: string;
  loginBackgroundUrl?: string;
}

/**
 * 应用外观设置：更新首页侧边栏 Logo 与登录页样式
 */
export function applyAppearance(appearance: AppearancePayload) {
  appearanceLogoUrl.value = appearance.logoUrl ?? '';
  appearanceLoginBackgroundUrl.value = appearance.loginBackgroundUrl ?? '';
  defaultLogoSource ??= preferencesManager.getPreferences().logo.source;
  preferencesManager.updatePreferences({
    logo: { source: appearanceLogoUrl.value || defaultLogoSource },
  });
  if (appearanceLoginBackgroundUrl.value) {
    document.documentElement.style.setProperty(
      '--login-bg-image',
      `url("${appearanceLoginBackgroundUrl.value}")`,
    );
  } else {
    document.documentElement.style.removeProperty('--login-bg-image');
  }
}

/**
 * 启动时加载系统外观，失败时静默保留默认样式
 */
export async function loadSystemAppearance() {
  try {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 2000);
    const baseURL = ((import.meta.env.VITE_GLOB_API_URL as string) || '').replace(
      /\/+$/,
      '',
    );
    const response = await fetch(`${baseURL}/system/appearance/get`, {
      headers: { 'tenant-id': '1' },
      signal: controller.signal,
    });
    clearTimeout(timer);
    if (!response.ok) {
      return;
    }
    const result = await response.json();
    if (result?.code !== 0 || !result.data) {
      return;
    }
    applyAppearance(result.data);
  } catch {
    // 外观加载失败不影响应用启动
  }
}
