import { defineStore } from "pinia";
import { ref } from "vue";
import { getAllDictData, refreshDictCache } from "@/api/dict";
import type { DictData } from "@/api/dict";

export const useDictStore = defineStore("dict", () => {
  const dictData = ref<Record<string, DictData[]>>({});
  const loaded = ref(false);
  const loading = ref(false);

  const loadDictData = async () => {
    if (loaded.value || loading.value) return;

    loading.value = true;
    try {
      const { data } = await getAllDictData();
      if (data) {
        dictData.value = data;
        loaded.value = true;
      }
    } catch (error) {
      console.error("加载字典数据失败:", error);
    } finally {
      loading.value = false;
    }
  };

  const refresh = async () => {
    loading.value = true;
    try {
      await refreshDictCache();
      const { data } = await getAllDictData();
      if (data) {
        dictData.value = data;
      }
    } catch (error) {
      console.error("刷新字典数据失败:", error);
    } finally {
      loading.value = false;
    }
  };

  const getDictList = (dictCode: string): DictData[] => {
    return dictData.value[dictCode] || [];
  };

  const getDictLabel = (dictCode: string, value: string | number): string => {
    const list = getDictList(dictCode);
    const item = list.find(d => d.itemValue === String(value));
    return item?.itemLabel || String(value);
  };

  const getDictValue = (dictCode: string, label: string): string => {
    const list = getDictList(dictCode);
    const item = list.find(d => d.itemLabel === label);
    return item?.itemValue || "";
  };

  const getDictColor = (dictCode: string, value: string | number): string => {
    const list = getDictList(dictCode);
    const item = list.find(d => d.itemValue === String(value));
    return item?.listClass || "";
  };

  return {
    dictData,
    loaded,
    loading,
    loadDictData,
    refresh,
    getDictList,
    getDictLabel,
    getDictValue,
    getDictColor
  };
});
