import {
  createConfig,
  getConfigKey,
  getConfigPage,
  updateConfig,
} from '#/api/infra/config';

export namespace PortalUiConfigApi {
  /** 门户界面配置（全局参数，存于 infra_config 参数表，所有用户共用） */
  export interface Config {
    /** 首页字号百分比，100 表示原始大小 */
    homeFontSize: number;
    /** 菜单字号，单位 px */
    menuFontSize: number;
  }
}

/** 参数键名，与 sql/mysql/portal_ui_font_config.sql 保持一致 */
export const PORTAL_CONFIG_KEYS = {
  homeFontSize: 'portal.ui.home-font-size',
  menuFontSize: 'portal.ui.menu-font-size',
} as const;

interface ConfigMeta {
  category: string;
  defaultValue: number;
  name: string;
  remark: string;
}

const CONFIG_META: Record<keyof PortalUiConfigApi.Config, ConfigMeta> = {
  homeFontSize: {
    category: '门户配置',
    defaultValue: 115,
    name: '首页字号(%)',
    remark: '首页文字缩放百分比，100 为原始大小，可设置 100-150',
  },
  menuFontSize: {
    category: '门户配置',
    defaultValue: 16,
    name: '菜单字号(px)',
    remark: '顶部导航与侧边菜单文字大小，单位 px，可设置 12-22',
  },
};

export const defaultPortalUiConfig: PortalUiConfigApi.Config = {
  homeFontSize: CONFIG_META.homeFontSize.defaultValue,
  menuFontSize: CONFIG_META.menuFontSize.defaultValue,
};

function parseNumber(value: null | string | undefined, fallback: number) {
  const parsed = Number(value);
  return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}

/** 读取全局门户界面配置 */
export async function getPortalUiConfig(): Promise<PortalUiConfigApi.Config> {
  const [homeFontSize, menuFontSize] = await Promise.all([
    getConfigKey(PORTAL_CONFIG_KEYS.homeFontSize),
    getConfigKey(PORTAL_CONFIG_KEYS.menuFontSize),
  ]);
  return {
    homeFontSize: parseNumber(homeFontSize, defaultPortalUiConfig.homeFontSize),
    menuFontSize: parseNumber(menuFontSize, defaultPortalUiConfig.menuFontSize),
  };
}

/** 保存单个参数：已存在则更新，不存在则创建 */
async function upsertConfig(
  key: string,
  meta: ConfigMeta,
  value: number,
) {
  const page = await getConfigPage({ pageNo: 1, pageSize: 10, key });
  const existing = page.list?.find((item) => item.key === key);
  if (existing?.id) {
    await updateConfig({ ...existing, value: String(value) });
    return;
  }
  await createConfig({
    category: meta.category,
    key,
    name: meta.name,
    remark: meta.remark,
    type: 1,
    value: String(value),
    visible: true,
  });
}

/** 保存全局门户界面配置 */
export async function savePortalUiConfig(config: PortalUiConfigApi.Config) {
  await Promise.all([
    upsertConfig(
      PORTAL_CONFIG_KEYS.homeFontSize,
      CONFIG_META.homeFontSize,
      Math.round(config.homeFontSize),
    ),
    upsertConfig(
      PORTAL_CONFIG_KEYS.menuFontSize,
      CONFIG_META.menuFontSize,
      Math.round(config.menuFontSize),
    ),
  ]);
}
