var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/systemSettings/registry/components/DataSourceTreeSelect/index.tsx
var DataSourceTreeSelect_exports = {};
__export(DataSourceTreeSelect_exports, {
  default: () => DataSourceTreeSelect_default
});
module.exports = __toCommonJS(DataSourceTreeSelect_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_react2 = require("react");
var import_serve = require("./serve");
var import_useEngineContext = __toESM(require("../../../../../hooks/useEngineContext"));
var import_utils = require("../../../../../utils");
var isString = (value) => {
  return typeof value === "string";
};
var defaultArr = [];
var DataSourceTreeSelect = (props) => {
  var _a, _b, _c;
  const {
    value,
    onChange,
    disabled,
    mode,
    variables = defaultArr,
    isShowOriginalDataSource = true,
    filters,
    dataSource = []
    // 从 props 中获取数据源，默认为空数组
  } = props;
  console.log("dataSource>>>>", dataSource);
  console.log("value>>>", value);
  const context = (0, import_useEngineContext.default)();
  const { request: apiRequest } = ((_c = (_b = (_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.getApp) == null ? void 0 : _c.call(_b)) || {};
  import_utils.request.setRequest(apiRequest);
  const valueRef = (0, import_react2.useRef)(value);
  valueRef.current = value;
  const [treeData, setTreeData] = (0, import_react2.useState)([]);
  const getTableDataSource = async () => {
    if (!isShowOriginalDataSource) {
      return [];
    }
    return dataSource.map((item) => {
      let collections = item.collections;
      if (item.type === "custom-api") {
        if (mode === "add") {
          collections = item.collections.filter(
            (collection) => {
              var _a2;
              return (_a2 = collection == null ? void 0 : collection.types) == null ? void 0 : _a2.includes("create");
            }
          );
        } else if (mode === "edit") {
          collections = item.collections.filter(
            (collection) => {
              var _a2;
              return (_a2 = collection == null ? void 0 : collection.types) == null ? void 0 : _a2.includes("update");
            }
          );
        } else if (mode === "view") {
          collections = item.collections.filter(
            (collection) => {
              var _a2;
              return (_a2 = collection == null ? void 0 : collection.types) == null ? void 0 : _a2.includes("get");
            }
          );
        } else if (mode === "list") {
          collections = item.collections.filter(
            (collection) => {
              var _a2;
              return (_a2 = collection == null ? void 0 : collection.types) == null ? void 0 : _a2.includes("list");
            }
          );
        }
      }
      const children = collections == null ? void 0 : collections.map((collection) => {
        var _a2;
        return {
          title: collection.title,
          value: collection.key || collection.tableName,
          item: {
            ...collection,
            headerDataSource: item.key,
            options: item.type === "mysql" ? {} : (_a2 = item == null ? void 0 : item.options) == null ? void 0 : _a2.options
          }
        };
      });
      return {
        title: item.displayName,
        value: item.key,
        selectable: false,
        children
      };
    });
  };
  const getVariablesDataSource = async (filterItem) => {
    if (filterItem !== "all") {
      if (filterItem) {
      }
    }
    return {
      title: "变量",
      value: "variables",
      selectable: false,
      children: variables.map((item) => {
        const treeNode = {
          title: item.label,
          value: item.value,
          item: item.item,
          isVariable: true
        };
        if (item.children) {
          treeNode.children = item.children.map((child) => ({
            title: child.label,
            value: child.value,
            item: child.item,
            isVariable: true
          }));
        }
        return treeNode;
      })
    };
  };
  const dataSources = {
    tables: getTableDataSource
    // variables: getVariablesDataSource,
  };
  const getMenuDataSource = async (_treeData) => {
    if ((filters == null ? void 0 : filters.variables) && typeof filters.variables !== "string") {
      if (filters.variables.menu !== "all") {
        return;
      }
    }
    const res = await (0, import_serve.getNocobaseMenuDataSource)();
    setTreeData(
      _treeData.map((d) => {
        if (d.value === "variables") {
          d.children = d.children || [];
          d.children.push(res);
        }
        return d;
      })
    );
  };
  const initDataSource = async () => {
    let _treeData = [];
    for (const key in dataSources) {
      const fn = dataSources[key];
      const filterKey = key;
      if (!filters || filters[filterKey]) {
        const res = await fn(filters ? filters[filterKey] : "all");
        _treeData = _treeData.concat(res);
      }
    }
    setTreeData(_treeData);
    getMenuDataSource(_treeData);
  };
  const _onChange = async (value2) => {
    onChange((value2 == null ? void 0 : value2.item) || null);
  };
  const handleSelect = async (val, option) => {
    _onChange({
      value: val,
      title: option.title,
      item: option.item,
      isSelect: true,
      isVariable: option.isVariable
    });
  };
  const handleChange = async (val, option) => {
    if (!val) {
      _onChange({ value: "", item: null, title: "" });
    }
  };
  const currentValue = (0, import_react2.useMemo)(() => {
    if (isString(value)) {
      return value;
    }
    return (value == null ? void 0 : value.key) || (value == null ? void 0 : value.tableName);
  }, [JSON.stringify(value)]);
  (0, import_react2.useEffect)(() => {
    initDataSource();
  }, [dataSource, variables]);
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_materials.TreeSelect,
    {
      treeExpandAction: "click",
      disabled,
      showSearch: true,
      popupMatchSelectWidth: false,
      treeNodeFilterProp: "title",
      style: { width: "100%" },
      value: currentValue,
      allowClear: true,
      onChange: handleChange,
      treeData,
      onSelect: handleSelect
    }
  ));
};
var DataSourceTreeSelect_default = DataSourceTreeSelect;
