import { ref, watch } from "vue";
import { createDataSource } from "../packages/utils/datasource.mjs";
import { getEditConfigDataSources } from "../packages/utils/common.mjs";
import { getDataSourceWithConcurrencyControl, getDictionaryWithConcurrencyControl } from "./simpleCache.mjs";
import api from "../api/index.mjs";
async function loadOptions(ctx, config, callback) {
  const { fieldType, optionConfig = {} } = config;
  if (fieldType !== "select" && fieldType !== "multipleSelection" && fieldType !== "cascader" && fieldType !== "area" && fieldType !== "industry" && fieldType !== "radio" && fieldType !== "checkbox") {
    const result = optionConfig.options || [];
    return result;
  }
  if (fieldType == "area") {
    const rawData = await getDataSourceWithConcurrencyControl(
      "sysArea",
      async () => {
        const data = await api.getDataDicArea4Cascader(ctx.$http);
        return data;
      }
    );
    return rawData;
  } else if (fieldType == "industry") {
    const rawData = await getDataSourceWithConcurrencyControl(
      "sysIndustry",
      async () => {
        const data = await api.getDataDicTrade4Cascader(ctx.$http);
        return data;
      }
    );
    return rawData;
  }
  const {
    optionSource,
    dataSourceValue,
    dictionaryValue,
    options: staticOptions = [],
    displayField = "label",
    valueField = "value"
  } = optionConfig;
  if (!optionSource || optionSource === "static") {
    return staticOptions;
  }
  try {
    if (optionSource === "dataSource" && dataSourceValue) {
      const result = await loadDataSourceOptions(
        ctx,
        dataSourceValue,
        displayField,
        valueField,
        staticOptions
      );
      if (callback) ;
      return result;
    }
    if (optionSource === "dictionary" && dictionaryValue) {
      const result = await loadDictionaryOptions(
        ctx,
        dictionaryValue,
        staticOptions
      );
      if (callback) ;
      return result;
    }
    if (callback) ;
    return staticOptions;
  } catch (error) {
    console.error("加载选项失败:", error);
    return staticOptions;
  }
}
async function loadDataSourceOptions(ctx, dataSourceValue, displayField, valueField, fallbackOptions = []) {
  var _a, _b;
  try {
    const dataSources = getEditConfigDataSources();
    const rawData = await getDataSourceWithConcurrencyControl(
      dataSourceValue,
      async () => {
        const dsManager = createDataSource({
          http: ctx.$http,
          dataSources,
          currentDataSourceId: dataSourceValue
        });
        try {
          const data = await dsManager.fetch();
          dsManager.destroy();
          return data;
        } catch (error) {
          dsManager.destroy();
          throw error;
        }
      }
    );
    let dataArray = [];
    if (Array.isArray(rawData)) {
      dataArray = rawData;
    } else if (typeof rawData === "object") {
      dataArray = Array.isArray(rawData.data) ? rawData.data : ((_a = rawData.data) == null ? void 0 : _a.records) || ((_b = rawData.data) == null ? void 0 : _b.list) || [];
    }
    const processedOptions = dataArray.map((item) => ({
      ...item,
      label: item[displayField] || item.label || item.name || String(item[valueField] || ""),
      value: item[valueField] || item.value || item.id
    }));
    return processedOptions;
  } catch (error) {
    console.error(`加载数据源失败： ${dataSourceValue}:`, error);
    return fallbackOptions;
  }
}
async function loadDictionaryOptions(ctx, dictionaryValue, fallbackOptions = []) {
  try {
    const dictData = await getDictionaryWithConcurrencyControl(
      dictionaryValue,
      () => api.getDicDataByKey(ctx.$http, dictionaryValue)
    );
    const result = [];
    for (const key in dictData) {
      result.push({
        label: dictData[key] || key,
        value: key
      });
    }
    return result;
  } catch (error) {
    console.error(`加载字典数据失败： ${dictionaryValue}:`, error);
    return fallbackOptions;
  }
}
function useOptions(ctx, config) {
  const options = ref([]);
  const loading = ref(false);
  const configRef = isRef(config) ? config : ref(config);
  watch(
    configRef,
    async (newConfig) => {
      var _a;
      if (!newConfig) return;
      loading.value = true;
      try {
        const result = await loadOptions(ctx, newConfig);
        options.value = result;
      } catch (error) {
        console.error("加载选项失败:", error);
        options.value = ((_a = newConfig.optionConfig) == null ? void 0 : _a.options) || [];
      } finally {
        loading.value = false;
      }
    },
    { immediate: true, deep: true }
  );
  return { options, loading };
}
function isRef(value) {
  return value && typeof value === "object" && "value" in value;
}
export {
  loadDataSourceOptions,
  loadDictionaryOptions,
  loadOptions,
  useOptions
};
