import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _objectWithoutProperties } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import PisellModal from "../../pisellModal/index.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import { _asyncToGenerator } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import Form from "../../form/index.js";
import useDataSource from "../hooks/useDataSource.js";
import { getDeviceSettingMetaData, getFormSettingMetaData } from "./serve.js";
import { transformFormObjToArrayWithUntouched } from "./utils.js";
import PageHeader from "../../page-header/index.js";
import useCtxActions from "../hooks/useCtxActions.js";
import FormSettingProvider from "./provider/formSetting/FormSettingProvider.js";
import useFormSettingParams from "../hooks/useFormSettingParams.js";
import React, { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
import { isArr } from "@pisell/utils";
import classNames from "classnames";
import { useDeepCompareEffect, useMemoizedFn } from "ahooks";
import "./index.less";
//#region src/components/dataSourceComponents/dataSourceForm/BaseForm.tsx
const _excluded = [
	"title",
	"description",
	"dataSource",
	"showTitle",
	"showDescription",
	"groupInfoPosition",
	"variables",
	"renderMode",
	"children",
	"currentValue",
	"className",
	"onDataSourceFinish",
	"onDataSourceLoaded",
	"formatSubmitValues",
	"formatInitialValues",
	"customSubmit",
	"beforeSubmit",
	"leaveConfirmConfig",
	"scene",
	"sceneRequestId"
];
/**
* @title: 数据源表单组件
* @description: 基于数据源动态生成表单，支持编辑、查看、禁用三种模式
*/
const BaseForm = forwardRef((props, ref) => {
	var _context$pageContext, _context$appHelper;
	const { title, description, dataSource, showTitle, showDescription, groupInfoPosition, variables, renderMode, children, currentValue, className, onDataSourceFinish, onDataSourceLoaded, formatSubmitValues, formatInitialValues, customSubmit, beforeSubmit, leaveConfirmConfig, scene, sceneRequestId } = props, others = _objectWithoutProperties(props, _excluded);
	const context = useEngineContext();
	console.log("context_pageProps", context === null || context === void 0 || (_context$pageContext = context.pageContext) === null || _context$pageContext === void 0 ? void 0 : _context$pageContext.props);
	const { setBeforeClose } = useCtxActions();
	const { getApp } = (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
	const { scope, target } = useFormSettingParams();
	const formRef = useRef(null);
	const { get } = useDataSource();
	useEffect(() => {
		if (props.__designMode === "design") {
			var _formRef$current;
			(_formRef$current = formRef.current) === null || _formRef$current === void 0 || _formRef$current.resetFields();
		}
	}, [dataSource, props.__designMode]);
	useEffect(() => {
		document.body.id = "body";
	}, []);
	useImperativeHandle(ref, () => formRef.current);
	useDeepCompareEffect(() => {
		if (["edit", "view"].includes(renderMode || "") && dataSource) {
			if ((dataSource === null || dataSource === void 0 ? void 0 : dataSource.fromSettingMeta) || (dataSource === null || dataSource === void 0 ? void 0 : dataSource.fromDeviceSettingMeta)) {
				var _dataSource$fields, _dataSource$fields2;
				if (props.__designMode === "design") return;
				((dataSource === null || dataSource === void 0 ? void 0 : dataSource.fromDeviceSettingMeta) ? getDeviceSettingMetaData({
					scene,
					sceneRequestId: sceneRequestId || "",
					items: (dataSource === null || dataSource === void 0 || (_dataSource$fields = dataSource.fields) === null || _dataSource$fields === void 0 ? void 0 : _dataSource$fields.map((field) => field.name)) || []
				}) : getFormSettingMetaData({
					sectionCodes: Array.from(new Set(dataSource === null || dataSource === void 0 || (_dataSource$fields2 = dataSource.fields) === null || _dataSource$fields2 === void 0 ? void 0 : _dataSource$fields2.map((field) => field.name.split(".").shift()))),
					scope,
					target
				})).then((res) => {
					var _dataSource$fields3, _formRef$current2;
					const formattedValues = formatInitialValues ? formatInitialValues(res.data) : res.data || {};
					const fieldNames = new Set((dataSource === null || dataSource === void 0 || (_dataSource$fields3 = dataSource.fields) === null || _dataSource$fields3 === void 0 ? void 0 : _dataSource$fields3.map((field) => field.name)) || []);
					const filteredValues = Object.keys(formattedValues).reduce((acc, key) => {
						if (fieldNames.has(key)) acc[key] = formattedValues[key];
						return acc;
					}, {});
					(_formRef$current2 = formRef.current) === null || _formRef$current2 === void 0 || _formRef$current2.setFields(transformFormObjToArrayWithUntouched(_objectSpread2({}, filteredValues)));
					onDataSourceLoaded === null || onDataSourceLoaded === void 0 || onDataSourceLoaded(filteredValues, res);
				}).catch((error) => {
					console.error("获取formSettingMeta数据失败:", error);
				});
				return;
			}
			get === null || get === void 0 || get.runAsync().then((res) => {
				var _formRef$current3;
				const formattedValues = formatInitialValues ? formatInitialValues(res) : res;
				let values = formattedValues;
				if (isArr(dataSource === null || dataSource === void 0 ? void 0 : dataSource.fields)) {
					var _dataSource$fields4;
					const fieldNames = new Set((dataSource === null || dataSource === void 0 || (_dataSource$fields4 = dataSource.fields) === null || _dataSource$fields4 === void 0 ? void 0 : _dataSource$fields4.map((field) => field.name)) || []);
					values = Object.keys(formattedValues).reduce((acc, key) => {
						if (fieldNames.has(key)) acc[key] = formattedValues[key];
						return acc;
					}, {});
				}
				(_formRef$current3 = formRef.current) === null || _formRef$current3 === void 0 || _formRef$current3.setFields(transformFormObjToArrayWithUntouched(values));
				onDataSourceLoaded === null || onDataSourceLoaded === void 0 || onDataSourceLoaded(values, res);
			});
		}
	}, [renderMode, dataSource]);
	const checkFormClose = useMemoizedFn(_asyncToGenerator(function* () {
		var _formRef$current4;
		if ((_formRef$current4 = formRef.current) === null || _formRef$current4 === void 0 ? void 0 : _formRef$current4.isFieldsTouched()) return new Promise((resolve) => {
			PisellModal.confirm({
				title: leaveConfirmConfig === null || leaveConfirmConfig === void 0 ? void 0 : leaveConfirmConfig.title,
				content: leaveConfirmConfig === null || leaveConfirmConfig === void 0 ? void 0 : leaveConfirmConfig.content,
				okText: leaveConfirmConfig === null || leaveConfirmConfig === void 0 ? void 0 : leaveConfirmConfig.okText,
				cancelText: leaveConfirmConfig === null || leaveConfirmConfig === void 0 ? void 0 : leaveConfirmConfig.cancelText,
				onOk: () => {
					var _formRef$current5;
					(_formRef$current5 = formRef.current) === null || _formRef$current5 === void 0 || _formRef$current5.resetFields();
					resolve(true);
				},
				onCancel: () => {
					resolve(false);
				}
			});
		});
		return true;
	}));
	useEffect(() => {
		if (leaveConfirmConfig === null || leaveConfirmConfig === void 0 ? void 0 : leaveConfirmConfig.enable) setBeforeClose === null || setBeforeClose === void 0 || setBeforeClose(checkFormClose);
	}, [leaveConfirmConfig]);
	useEffect(() => {
		if (leaveConfirmConfig === null || leaveConfirmConfig === void 0 ? void 0 : leaveConfirmConfig.enable) {
			var _getApp;
			const history = getApp === null || getApp === void 0 || (_getApp = getApp()) === null || _getApp === void 0 || (_getApp = _getApp.history) === null || _getApp === void 0 ? void 0 : _getApp.instance;
			let unblock = history === null || history === void 0 ? void 0 : history.block((location, action) => {
				var _formRef$current6;
				if ((_formRef$current6 = formRef.current) === null || _formRef$current6 === void 0 ? void 0 : _formRef$current6.isFieldsTouched()) {
					PisellModal.confirm({
						title: leaveConfirmConfig.title,
						content: leaveConfirmConfig.content,
						okText: leaveConfirmConfig.okText,
						cancelText: leaveConfirmConfig.cancelText,
						onOk: () => {
							unblock === null || unblock === void 0 || unblock();
							if (action === "PUSH") history.push(location);
							else if (action === "POP") history.go(-1);
							else if (action === "REPLACE") history.replace(location);
						},
						onCancel: () => {}
					});
					return false;
				}
				return true;
			});
			return () => {
				unblock === null || unblock === void 0 || unblock();
			};
		}
	}, []);
	return /* @__PURE__ */ React.createElement(FormSettingProvider, {
		renderMode,
		groupInfoPosition,
		currentValue,
		size: others.size,
		onDataSourceFinish,
		formatSubmitValues,
		formatInitialValues,
		customSubmit,
		beforeSubmit,
		scene,
		sceneRequestId
	}, /* @__PURE__ */ React.createElement(Form, _objectSpread2(_objectSpread2({}, others), {}, {
		className: classNames("pisell-lowcode-data-source-form", className),
		ref: formRef,
		preserve: true
	}), /* @__PURE__ */ React.createElement(PageHeader, {
		title,
		showTitle,
		subTitle: description,
		showSubTitle: showDescription
	}), children));
});
//#endregion
export { BaseForm as default };
