import { getText } from "../../../locales/index.js";
import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import { _asyncToGenerator } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useDataSource from "./useDataSource.js";
import PisellToast from "../../pisellToast/index.js";
import useFormat from "../dataSourceTable/hooks/useFormat.js";
import { createNocobaseData, customApi, deleteNocobaseData, getNocobaseData, getNocobaseDataList, updateNocobaseData } from "../dataSourceForm/serve.js";
import useVariables from "./useVariables.js";
import useParseActionsVariable from "./useParseActionsVariable.js";
import { useMemo } from "react";
import { useMemoizedFn } from "ahooks";
//#region src/components/dataSourceComponents/hooks/useActions.ts
const useActions = ({ dataSource: propsDataSource, currentValue: propsCurrentValue, __designMode, extraParams: propsExtraParams } = {}) => {
	var _context$appHelper;
	const { dataSource: ctxDataSource, __designMode: ctxDesignMode } = useDataSource();
	const { pisell2ApiBaseUrl, mypisellApiBaseUrl } = ((_context$appHelper = useEngineContext().appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.constants) || {};
	const baseUrlMap = {
		"pisell2-api": pisell2ApiBaseUrl,
		"mypisell-api": mypisellApiBaseUrl
	};
	const { parseVariable } = useVariables();
	const { parseActions } = useParseActionsVariable();
	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 } = useFormat({
		dataSourceKey: dataSourceKey || "",
		fields: fields || []
	});
	const currentRecord = useMemo(() => {
		return parseVariable === null || parseVariable === void 0 ? void 0 : parseVariable(currentValue, {});
	}, [currentValue, parseVariable]);
	const extraParams = useMemo(() => {
		return Object.entries(propsExtraParams || {}).reduce((acc, [key, value]) => {
			acc[key] = Object.entries(value || {}).reduce((acc, [k, v]) => {
				acc[k] = parseVariable === null || parseVariable === void 0 ? void 0 : parseVariable(v, {});
				return acc;
			}, {});
			return acc;
		}, {});
	}, [propsExtraParams, parseVariable]);
	const getParsedActions = useMemoizedFn(() => {
		return parseActions(originalActions, { currentRecord });
	});
	const genCustomApi = useMemoizedFn(({ method, path, parsedPath, params, headers, body }) => {
		return function() {
			var _ref = _asyncToGenerator(function* (data) {
				const result = yield customApi(parsedPath || path, data, {
					method,
					baseUrl: baseUrlMap[dataSourceKey] || (options === null || options === void 0 ? void 0 : options.baseUrl),
					params,
					headers,
					body,
					dataSourceKey
				});
				if (["pisell2-api", "mypisell-api"].includes(dataSourceKey)) {
					if ("mypisell-api" === dataSourceKey && designMode === "design") return result;
					return result.data;
				}
				return result;
			});
			return function(_x) {
				return _ref.apply(this, arguments);
			};
		}();
	});
	const getHeaders = useMemoizedFn(() => {
		return headerDataSource ? { "x-data-source": headerDataSource } : {};
	});
	const designModeToast = useMemoizedFn(() => {
		return PisellToast({ content: getText("pisell-design-mode-action-disabled") });
	});
	return {
		create: useMemoizedFn(function() {
			var _ref2 = _asyncToGenerator(function* (values) {
				if (designMode === "design") {
					designModeToast();
					return Promise.reject();
				}
				if (isCustomApi) {
					const actions = getParsedActions();
					return genCustomApi(actions === null || actions === void 0 ? void 0 : actions.create)(formatCreateUpdateParams(values));
				} else {
					if (!name) return {};
					return createNocobaseData({
						key: name,
						data: formatCreateUpdateParams(values),
						headers: getHeaders()
					});
				}
			});
			return function(_x2) {
				return _ref2.apply(this, arguments);
			};
		}()),
		get: useMemoizedFn(_asyncToGenerator(function* () {
			if (currentValue === "server") {
				if (isCustomApi) {
					const actions = getParsedActions();
					if (!(actions === null || actions === void 0 ? void 0 : actions.get)) return {};
					return genCustomApi(actions === null || actions === void 0 ? void 0 : actions.get)(extraParams === null || extraParams === void 0 ? void 0 : extraParams.get);
				}
				const res = yield getNocobaseData({
					key: name || "",
					query: extraParams === null || extraParams === void 0 ? void 0 : extraParams.get,
					headers: getHeaders()
				});
				return (res === null || res === void 0 ? void 0 : res.data) || {};
			} else if (currentValue) return parseVariable === null || parseVariable === void 0 ? void 0 : parseVariable(currentValue, {});
			return {};
		})),
		update: useMemoizedFn(function() {
			var _ref3 = _asyncToGenerator(function* (values) {
				if (designMode === "design") {
					designModeToast();
					return Promise.reject();
				}
				if ((currentDataSource === null || currentDataSource === void 0 ? void 0 : currentDataSource.fromSettingMeta) || (currentDataSource === null || currentDataSource === void 0 ? void 0 : currentDataSource.fromDeviceSettingMeta)) return Promise.reject();
				if (isCustomApi) {
					const actions = getParsedActions();
					if (!actions.update) return {};
					return genCustomApi(actions === null || actions === void 0 ? void 0 : actions.update)(formatCreateUpdateParams(values));
				} else {
					const id = (extraParams === null || extraParams === void 0 ? void 0 : extraParams.filterByTk) || (values === null || values === void 0 ? void 0 : values.id);
					if (!id || !name) {
						PisellToast({ content: getText("pisell-action-get-data") });
						return Promise.reject();
					}
					try {
						return yield updateNocobaseData({
							key: name,
							data: formatCreateUpdateParams(values),
							headers: getHeaders(),
							query: _objectSpread2({ filterByTk: id }, extraParams === null || extraParams === void 0 ? void 0 : extraParams.update)
						});
					} catch (error) {
						return Promise.reject();
					}
				}
			});
			return function(_x3) {
				return _ref3.apply(this, arguments);
			};
		}()),
		list: useMemoizedFn(function() {
			var _ref4 = _asyncToGenerator(function* (params) {
				const formatParams = formatListParams(params);
				if (isCustomApi) {
					const actions = getParsedActions();
					if (!(actions === null || actions === void 0 ? void 0 : actions.list)) return [];
					return formatListResult(yield genCustomApi(actions === null || actions === void 0 ? void 0 : actions.list)(_objectSpread2(_objectSpread2({}, formatParams), (extraParams === null || extraParams === void 0 ? void 0 : extraParams.list) || {})));
				}
				if (!name) return {};
				return formatListResult(yield getNocobaseDataList({
					key: name,
					params: _objectSpread2(_objectSpread2({}, formatParams), (extraParams === null || extraParams === void 0 ? void 0 : extraParams.list) || {}),
					headers: getHeaders()
				}));
			});
			return function(_x4) {
				return _ref4.apply(this, arguments);
			};
		}()),
		destroy: useMemoizedFn(function() {
			var _ref5 = _asyncToGenerator(function* (id) {
				if (designMode === "design") {
					designModeToast();
					return Promise.reject();
				}
				if (isCustomApi) {
					const actions = getParsedActions();
					if (!actions.destroy) return {};
					return genCustomApi(actions === null || actions === void 0 ? void 0 : actions.destroy)({});
				}
				if (!name) return Promise.reject();
				return deleteNocobaseData(name, id, getHeaders());
			});
			return function(_x5) {
				return _ref5.apply(this, arguments);
			};
		}())
	};
};
//#endregion
export { useActions as default };
