import { storageSession } from "@pureadmin/utils";
import { getDictList } from "@/api/dict";

export interface DictItem {
  id?: number;
  code: string;
  name: string;
  value: any;
  weight?: number;
  remark?: string;
  list?: DictItem[];
}

export interface DictGroup {
  [code: string]: DictItem[];
}

const DICT_KEY = "dicts";

const dictUtil = {
  loadDicts: async (): Promise<DictGroup> => {
    try {
      const list: any[] = await getDictList({ pageSize: 1024 });
      const dictGroup = dictUtil.groupByKey(list, "code");
      storageSession().setItem(DICT_KEY, dictGroup);
      return dictGroup;
    } catch (error) {
      console.error("加载字典数据失败:", error);
      return {};
    }
  },

  getDicts: (): DictGroup => {
    return storageSession().getItem(DICT_KEY) || {};
  },

  getDictList: (code: string): DictItem[] => {
    const dicts = dictUtil.getDicts();
    return dicts[code] || [];
  },

  getDictLabel: (code: string, value: any): string => {
    if (value === null || value === undefined || value === "") {
      return "--";
    }
    const dicts = dictUtil.getDicts();
    const list = dicts[code];
    if (!list || list.length === 0) {
      return "--";
    }
    const item = list.find(k => k.value == value);
    return item ? item.name : "--";
  },

  getDictValue: (code: string, name: string): any => {
    const dicts = dictUtil.getDicts();
    const list = dicts[code];
    if (!list || list.length === 0) {
      return null;
    }
    const item = list.find(k => k.name === name);
    return item ? item.value : null;
  },

  groupByKey: (elements: any[], key: string): DictGroup => {
    const map: DictGroup = {};
    if (!elements || elements.length === 0) {
      return map;
    }
    for (let i = 0; i < elements.length; i++) {
      if (!elements[i][key] && elements[i][key] !== 0) {
        continue;
      }
      const k = elements[i][key].toString();
      const tmp = map[k] || [];
      tmp.push(elements[i]);
      map[k] = tmp;
    }
    return map;
  },

  clearDicts: () => {
    storageSession().removeItem(DICT_KEY);
  }
};

export const formatDict = (code: string, value: any): string => {
  return dictUtil.getDictLabel(code, value);
};

export const getDictOptions = (code: string): { label: string; value: any }[] => {
  const list = dictUtil.getDictList(code);
  return list.map(item => ({
    label: item.name,
    value: item.value
  }));
};

export const getDictColor = (code: string, value: any): string => {
  const list = dictUtil.getDictList(code);
  const item = list.find(k => k.value == value);
  return item?.color || "";
};

export default dictUtil;
