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/dataSourceComponents/hooks/useActions.ts
var useActions_exports = {};
__export(useActions_exports, {
  default: () => useActions_default
});
module.exports = __toCommonJS(useActions_exports);
var import_react = require("react");
var import_ahooks = require("ahooks");
var import_pisellToast = __toESM(require("../../pisellToast"));
var import_useFormat = __toESM(require("../dataSourceTable/hooks/useFormat"));
var import_serve = require("../dataSourceForm/serve");
var import_useParseActionsVariable = __toESM(require("./useParseActionsVariable"));
var import_useVariables = __toESM(require("./useVariables"));
var import_useDataSource = __toESM(require("./useDataSource"));
var import_locales = require("../../../locales");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var useActions = ({
  dataSource: propsDataSource,
  currentValue: propsCurrentValue,
  __designMode,
  extraParams: propsExtraParams
} = {}) => {
  var _a;
  const { dataSource: ctxDataSource, __designMode: ctxDesignMode } = (0, import_useDataSource.default)();
  const context = (0, import_useEngineContext.default)();
  const { pisell2ApiBaseUrl, mypisellApiBaseUrl } = ((_a = context.appHelper) == null ? void 0 : _a.constants) || {};
  const baseUrlMap = {
    "pisell2-api": pisell2ApiBaseUrl,
    "mypisell-api": mypisellApiBaseUrl
  };
  const { parseVariable } = (0, import_useVariables.default)();
  const { parseActions } = (0, import_useParseActionsVariable.default)();
  const currentDataSource = propsDataSource || ctxDataSource;
  const currentValue = propsCurrentValue || "server";
  const designMode = __designMode || ctxDesignMode;
  const {
    isCustomApi,
    actions: originalActions,
    options,
    headerDataSource,
    name,
    dataSourceKey,
    fields
  } = currentDataSource || {};
  const { formatListResult, formatListParams, formatCreateUpdateParams } = (0, import_useFormat.default)({
    dataSourceKey: dataSourceKey || "",
    fields: fields || []
  });
  const currentRecord = (0, import_react.useMemo)(() => {
    return parseVariable == null ? void 0 : parseVariable(currentValue, {});
  }, [currentValue, parseVariable]);
  const extraParams = (0, import_react.useMemo)(() => {
    return Object.entries(propsExtraParams || {}).reduce((acc, [key, value]) => {
      acc[key] = Object.entries(value || {}).reduce((acc2, [k, v]) => {
        acc2[k] = parseVariable == null ? void 0 : parseVariable(v, {});
        return acc2;
      }, {});
      return acc;
    }, {});
  }, [propsExtraParams, parseVariable]);
  const getParsedActions = (0, import_ahooks.useMemoizedFn)(() => {
    return parseActions(originalActions, { currentRecord });
  });
  const genCustomApi = (0, import_ahooks.useMemoizedFn)(
    ({
      method,
      path,
      parsedPath,
      params,
      headers,
      body
    }) => {
      return async (data) => {
        const result = await (0, import_serve.customApi)(parsedPath || path, data, {
          method,
          baseUrl: baseUrlMap[dataSourceKey] || (options == null ? void 0 : options.baseUrl),
          params,
          headers,
          body
        });
        if (["pisell2-api", "mypisell-api"].includes(dataSourceKey)) {
          if ("mypisell-api" === dataSourceKey && designMode === "design") {
            return result;
          }
          return result.data;
        }
        return result;
      };
    }
  );
  const getHeaders = (0, import_ahooks.useMemoizedFn)(() => {
    return headerDataSource ? { "x-data-source": headerDataSource } : {};
  });
  const designModeToast = (0, import_ahooks.useMemoizedFn)(() => {
    return (0, import_pisellToast.default)({
      content: (0, import_locales.getText)("pisell-design-mode-action-disabled")
    });
  });
  const create = (0, import_ahooks.useMemoizedFn)(async (values) => {
    if (designMode === "design") {
      designModeToast();
      return Promise.reject();
    }
    if (isCustomApi) {
      const actions = getParsedActions();
      const createApi = genCustomApi(actions == null ? void 0 : actions.create);
      return createApi(formatCreateUpdateParams(values));
    } else {
      if (!name)
        return {};
      return (0, import_serve.createNocobaseData)({
        key: name,
        data: formatCreateUpdateParams(values),
        headers: getHeaders()
      });
    }
  });
  const get = (0, import_ahooks.useMemoizedFn)(async () => {
    if (currentValue === "server") {
      if (isCustomApi) {
        const actions = getParsedActions();
        if (!(actions == null ? void 0 : actions.get)) {
          return {};
        }
        const getApi = genCustomApi(actions == null ? void 0 : actions.get);
        return getApi(extraParams == null ? void 0 : extraParams.get);
      }
      const res = await (0, import_serve.getNocobaseData)({
        key: name || "",
        query: extraParams == null ? void 0 : extraParams.get,
        headers: getHeaders()
      });
      return (res == null ? void 0 : res.data) || {};
    } else if (currentValue) {
      return parseVariable == null ? void 0 : parseVariable(currentValue, {});
    }
    return {};
  });
  const update = (0, import_ahooks.useMemoizedFn)(async (values) => {
    if (designMode === "design") {
      designModeToast();
      return Promise.reject();
    }
    if (isCustomApi) {
      const actions = getParsedActions();
      if (!actions.update) {
        return {};
      }
      const updateApi = genCustomApi(actions == null ? void 0 : actions.update);
      return updateApi(formatCreateUpdateParams(values));
    } else {
      const id = (extraParams == null ? void 0 : extraParams.filterByTk) || (values == null ? void 0 : values.id);
      if (!id || !name) {
        (0, import_pisellToast.default)({
          content: (0, import_locales.getText)("pisell-action-get-data")
        });
        return Promise.reject();
      }
      try {
        const res = await (0, import_serve.updateNocobaseData)({
          key: name,
          data: formatCreateUpdateParams(values),
          headers: getHeaders(),
          query: { filterByTk: id, ...extraParams == null ? void 0 : extraParams.update }
        });
        return res;
      } catch (error) {
        return Promise.reject();
      }
    }
  });
  const list = (0, import_ahooks.useMemoizedFn)(
    async (params) => {
      const formatParams = formatListParams(params);
      if (isCustomApi) {
        const actions = getParsedActions();
        if (!(actions == null ? void 0 : actions.list)) {
          return [];
        }
        const listApi = genCustomApi(actions == null ? void 0 : actions.list);
        return formatListResult(await listApi(formatParams));
      }
      if (!name)
        return {};
      return formatListResult(
        await (0, import_serve.getNocobaseDataList)({
          key: name,
          params: {
            ...formatParams,
            ...(extraParams == null ? void 0 : extraParams.list) || {}
          },
          headers: getHeaders()
        })
      );
    }
  );
  const destroy = (0, import_ahooks.useMemoizedFn)(async (id) => {
    if (designMode === "design") {
      designModeToast();
      return Promise.reject();
    }
    if (isCustomApi) {
      const actions = getParsedActions();
      if (!actions.destroy) {
        return {};
      }
      const deleteApi = genCustomApi(actions == null ? void 0 : actions.destroy);
      return deleteApi({});
    }
    if (!name)
      return Promise.reject();
    return (0, import_serve.deleteNocobaseData)(name, id, getHeaders());
  });
  return {
    create,
    get,
    update,
    list,
    destroy
  };
};
var useActions_default = useActions;
