import { localForage } from "@/utils/localforage";
import { getLocalDict } from "@/api/public";

// 内存缓存，便于在 UI 格式化中同步返回
let DICT_CACHE = null;

// 模块加载后尝试初始化缓存（无需等待）
localForage()
  .getItem("dictionary")
  .then(dict => {
    DICT_CACHE = dict || null;
  })
  .catch(() => {
    DICT_CACHE = null;
  });

export const getDictionaryList = async () => {
  const res = await getLocalDict();
  const dictionary: Record<string, Record<string, string>> = {};
  res.data &&
    res.data.forEach(({ key, code, msg }) => {
      if (!(key in dictionary)) {
        dictionary[key] = {};
      }
      dictionary[key][code] = msg;
    });
  await localForage().setItem("dictionary", dictionary);
  await refreshDictionaryCache();
};

/**
 * 获取字典显示值（同步）
 * @param type 字典类型
 * @param code 字典值（字符串/数字）
 * @param opts 可选项：fallback占位符，showRawWhenMiss未命中时显示原值
 */
export const getDictionary = (
  type: string,
  code: string | number | null | undefined,
  opts: { fallback?: string; showRawWhenMiss?: boolean } = {}
): string => {
  const fallback = opts.fallback ?? "";
  if (code === null || code === undefined || code === "") return fallback;

  const key = String(code);
  const dictByType = DICT_CACHE?.[type];

  console.log(DICT_CACHE);

  if (dictByType && key in dictByType) {
    return dictByType[key] ?? fallback;
  }

  // 缓存未命中：按需返回原始值或占位
  return opts.showRawWhenMiss ? key : fallback;
};

/**
 * 重新刷新内存缓存（可在 App 初始化字典后调用）
 */
export const refreshDictionaryCache = async () => {
  try {
    const dict = await localForage().getItem("dictionary");
    DICT_CACHE = dict || null;
  } catch {
    DICT_CACHE = null;
  }
};
