import { ref, toRefs } from "vue";
import { useDictStore } from "@/store/modules/dict";
import { isString } from "@pureadmin/utils";

export function useDict(...args: string[]) {
  const res = ref<Record<string, any[]>>({});
  const dictStore = useDictStore();

  args.forEach(dictType => {
    res.value[dictType] = [];
    const dicts = dictStore.getDict(dictType);

    if (dicts && dicts.length) {
      res.value[dictType] = dicts;
    } else {
      dictStore
        .fetchDictByType(dictType)
        .then(dictData => {
          res.value[dictType] = dictData;
        })
        .catch(error => {
          console.error(`获取字典${dictType}失败:`, error);
        });
    }
  });

  return toRefs<any>(res.value);
}

/**
 * 统一的字典查询核心方法
 * @param dictType 字典类型
 * @param searchValue 查询值
 * @param property 要返回的属性名 ('label' | 'class' | 'value' 等)
 * @param isAsync 是否异步模式
 * @returns 查询结果或Promise
 */
export async function getDictProperty<T>(
  dictType: T,
  searchValue: string,
  property: string,
  isAsync: boolean = false
): Promise<string | null> {
  if (!isString(searchValue)) searchValue = String(searchValue);
  const dictStore = useDictStore();

  if (isAsync) {
    try {
      await dictStore.fetchDictByType(dictType as string);
    } catch (error) {
      console.error(`获取字典${String(dictType)}失败:`, error);
    }
  } else {
    // 同步模式：触发获取但不等待
    dictStore.fetchDictByType(dictType as string).catch(error => {
      console.error(`获取字典${String(dictType)}失败:`, error);
    });
  }

  const dicts = dictStore.getDict(dictType as string) || [];
  const item = dicts.find((d: any) => d.value === searchValue);
  return item ? item[property] : null;
}

// 保持向后兼容的同步方法
export function useDictValue<T>(
  dictType: T,
  searchValue: string
): string | null {
  // 对于同步调用，直接从store获取当前可用数据
  if (!isString(searchValue)) searchValue = String(searchValue);
  const dictStore = useDictStore();
  // 触发获取但不等待
  dictStore.fetchDictByType(dictType as string).catch(error => {
    console.error(`获取字典${String(dictType)}失败:`, error);
  });
  const dicts = dictStore.getDict(dictType as string) || [];
  const item = dicts.find((d: any) => d.value === searchValue);
  return item ? item.label : null;
}

export function useDictClass<T>(
  dictType: T,
  searchValue: string
): string | null {
  if (!isString(searchValue)) searchValue = String(searchValue);
  const dictStore = useDictStore();
  // 触发获取但不等待
  dictStore.fetchDictByType(dictType as string).catch(error => {
    console.error(`获取字典${String(dictType)}失败:`, error);
  });
  const dicts = dictStore.getDict(dictType as string) || [];
  const item = dicts.find((d: any) => d.value === searchValue);
  return item ? item.class : null;
}

// 异步方法使用统一的核心方法
export async function useDictValueAsync<T>(
  dictType: T,
  searchValue: string
): Promise<string | null> {
  return getDictProperty(dictType, searchValue, "label", true);
}

export async function useDictClassAsync<T>(
  dictType: T,
  searchValue: string
): Promise<string | null> {
  return getDictProperty(dictType, searchValue, "class", true);
}

/**
 * 通用的字典属性查询方法（新增）
 * @param dictType 字典类型
 * @param searchValue 查询值
 * @param property 要返回的属性名
 * @returns Promise<string | null>
 */
export async function useDictPropertyAsync<T>(
  dictType: T,
  searchValue: string,
  property: string
): Promise<string | null> {
  return getDictProperty(dictType, searchValue, property, true);
}

/**
 * 通用的字典属性查询方法（同步版本）
 * @param dictType 字典类型
 * @param searchValue 查询值
 * @param property 要返回的属性名
 * @returns string | null
 */
export function useDictProperty<T>(
  dictType: T,
  searchValue: string,
  property: string
): string | null {
  if (!isString(searchValue)) searchValue = String(searchValue);
  const dictStore = useDictStore();
  // 触发获取但不等待
  dictStore.fetchDictByType(dictType as string).catch(error => {
    console.error(`获取字典${String(dictType)}失败:`, error);
  });
  const dicts = dictStore.getDict(dictType as string) || [];
  const item = dicts.find((d: any) => d.value === searchValue);
  return item ? item[property] : null;
}
