const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_serve = require("../../serve.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
let ahooks = require("ahooks");
//#region src/plus/saasTeamMembers/components/MemberDrawer/ExtensionFormTabContent.tsx
const FORM_MESSAGE_TYPES = {
	LOADED: "form_loaded",
	RECORD_UPDATE_SUCCESS: "form_record_update_success",
	RECORD_UPDATE_FAILED: "form_record_update_failed",
	RECORD_CREATE_SUCCESS: "form_record_create_success",
	RECORD_CREATE_FAILED: "form_record_create_failed",
	CANCELED: "form_canceled",
	VALUES_CHANGE: "form_values_change",
	RESET: "form_reset"
};
const ExtensionFormTabContent = react.default.forwardRef(({ formId, domain, token, locale, tenantAccountId, onDirtyChange, onLoad, onCancel, getText, tabLabel, prefix, relationList, refreshRelationList }, ref) => {
	const iframeRef = (0, react.useRef)(null);
	const [loading, setLoading] = (0, react.useState)(true);
	const [relationRecord, setRelationRecord] = (0, react.useState)(null);
	const [isBinding, setIsBinding] = (0, react.useState)(false);
	const [bindModalVisible, setBindModalVisible] = (0, react.useState)(false);
	const [selectedRecordId, setSelectedRecordId] = (0, react.useState)(void 0);
	const [recordKeyword, setRecordKeyword] = (0, react.useState)("");
	const [modal, contextHolder] = antd.Modal.useModal();
	(0, react.useEffect)(() => {
		setRelationRecord((relationList || []).find((r) => (r === null || r === void 0 ? void 0 : r.form_id) === formId) || null);
	}, [relationList, formId]);
	const { data: recordsData, loading: recordsLoading, run: runGetRecords } = (0, ahooks.useRequest)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (kw) {
			return yield require_serve.getFormRecords({
				form_id: formId,
				keyword: kw || "",
				skip: 1,
				num: 50,
				with_relation_record_by_type: 1
			});
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}(), {
		manual: true,
		debounceWait: 300
	});
	(0, react.useEffect)(() => {
		if (bindModalVisible) runGetRecords(recordKeyword);
	}, [
		bindModalVisible,
		recordKeyword,
		runGetRecords
	]);
	const _recordOptions = (0, react.useMemo)(() => {
		const options = ((recordsData === null || recordsData === void 0 ? void 0 : recordsData.list) || []).map((item) => {
			const disabled = Array.isArray(item === null || item === void 0 ? void 0 : item.relation_record) && item.relation_record.length > 0 && item.form_record_id != (relationRecord === null || relationRecord === void 0 ? void 0 : relationRecord.form_record_id);
			return {
				label: item.main_field,
				value: item.form_record_id,
				disabled
			};
		});
		const current = relationRecord === null || relationRecord === void 0 ? void 0 : relationRecord.form_record;
		const hasCurrent = ((recordsData === null || recordsData === void 0 ? void 0 : recordsData.list) || []).some((i) => i.form_record_id == (relationRecord === null || relationRecord === void 0 ? void 0 : relationRecord.form_record_id)) || options.some((o) => o.value === (relationRecord === null || relationRecord === void 0 ? void 0 : relationRecord.form_record_id));
		if (current && !hasCurrent) options.push({
			label: current.main_field,
			value: relationRecord.form_record_id,
			disabled: false
		});
		return options;
	}, [recordsData, relationRecord]);
	const iframeUrl = react.default.useMemo(() => {
		const url = new URL(`https://${domain}/admin/form/view/${formId}`);
		url.searchParams.set("scene", "1005");
		url.searchParams.set("locale", locale);
		url.searchParams.set("token", `bearer ${token}`);
		url.searchParams.set("footer", "fixed");
		url.searchParams.set("mode", "edit");
		if (relationRecord === null || relationRecord === void 0 ? void 0 : relationRecord.form_record_id) url.searchParams.set("form_record_id", String(relationRecord === null || relationRecord === void 0 ? void 0 : relationRecord.form_record_id));
		return url.toString();
	}, [
		domain,
		formId,
		locale,
		token,
		relationRecord === null || relationRecord === void 0 ? void 0 : relationRecord.form_record_id
	]);
	(0, react.useEffect)(() => {
		if (iframeUrl) try {
			(0, _pisell_utils.sendWarningLog)({
				title: "View Member Role Form",
				content: [
					{
						key: "currentLocation",
						value: window.location.href
					},
					{
						key: "UTC Time",
						value: (/* @__PURE__ */ new Date()).toISOString()
					},
					{
						key: "iframeUrl",
						value: iframeUrl
					}
				]
			});
		} catch (e) {}
	}, [iframeUrl]);
	const upsertRelationRecord = (0, react.useCallback)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (rid) {
			if (!rid || !tenantAccountId) return;
			try {
				setIsBinding(true);
				if (!relationRecord) yield require_serve.bindRelationRecord({
					relation_type: "tenant_account",
					relation_id: tenantAccountId,
					form_id: formId,
					form_record_id: rid
				});
				else if (relationRecord.form_record_id !== rid) yield require_serve.updateRelationRecord(relationRecord.id, { form_record_id: rid });
				yield refreshRelationList === null || refreshRelationList === void 0 ? void 0 : refreshRelationList();
			} catch (e) {} finally {
				setIsBinding(false);
			}
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}(), [
		tenantAccountId,
		formId,
		relationRecord,
		refreshRelationList
	]);
	const syncRelationRecord = (0, react.useCallback)(function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (rid) {
			if (!rid) return;
			yield upsertRelationRecord(rid);
		});
		return function(_x3) {
			return _ref3.apply(this, arguments);
		};
	}(), [upsertRelationRecord]);
	const handleMessage = (0, react.useCallback)((event) => {
		const expectedOrigin = new URL(iframeUrl).origin;
		if (event.origin !== expectedOrigin) return;
		try {
			const msg = typeof event.data === "string" ? JSON.parse(event.data) : event.data;
			const data = msg === null || msg === void 0 ? void 0 : msg.data;
			if ((data === null || data === void 0 ? void 0 : data.form_id) !== formId) return;
			switch (msg.type) {
				case FORM_MESSAGE_TYPES.VALUES_CHANGE:
					onDirtyChange === null || onDirtyChange === void 0 || onDirtyChange(true);
					break;
				case FORM_MESSAGE_TYPES.LOADED:
					setLoading(false);
					onLoad === null || onLoad === void 0 || onLoad();
					break;
				case FORM_MESSAGE_TYPES.RECORD_CREATE_SUCCESS:
				case FORM_MESSAGE_TYPES.RECORD_UPDATE_SUCCESS:
					onDirtyChange === null || onDirtyChange === void 0 || onDirtyChange(false);
					syncRelationRecord(data === null || data === void 0 ? void 0 : data.form_record_id);
					break;
				case FORM_MESSAGE_TYPES.CANCELED:
					onCancel === null || onCancel === void 0 || onCancel();
					break;
				default: break;
			}
		} catch (error) {}
	}, [
		iframeUrl,
		onDirtyChange,
		onLoad,
		onCancel,
		formId,
		syncRelationRecord
	]);
	(0, react.useEffect)(() => {
		window.addEventListener("message", handleMessage);
		return () => {
			window.removeEventListener("message", handleMessage);
		};
	}, [handleMessage]);
	const sendMessage = (0, react.useCallback)((message) => {
		var _iframeRef$current;
		if ((_iframeRef$current = iframeRef.current) === null || _iframeRef$current === void 0 ? void 0 : _iframeRef$current.contentWindow) iframeRef.current.contentWindow.postMessage(JSON.stringify(message), new URL(iframeUrl).origin);
	}, [iframeUrl]);
	(0, react.useImperativeHandle)(ref, () => ({ reset: () => {
		onDirtyChange === null || onDirtyChange === void 0 || onDirtyChange(false);
		sendMessage({
			type: FORM_MESSAGE_TYPES.RESET,
			data: { form_id: formId }
		});
	} }), [
		formId,
		onDirtyChange,
		sendMessage
	]);
	const handleIframeLoad = (0, react.useCallback)(() => {
		setTimeout(() => {
			setLoading(false);
		}, 1e3);
	}, []);
	const openBindModal = (0, react.useCallback)(() => {
		setBindModalVisible(true);
		setSelectedRecordId(relationRecord === null || relationRecord === void 0 ? void 0 : relationRecord.form_record_id);
		setRecordKeyword("");
	}, [relationRecord]);
	const openBindWithConfirm = (0, react.useCallback)(() => {
		if (relationRecord) {
			modal.confirm({
				title: getText("pisell2.saas.team-members.bind.confirm.rebind-title"),
				content: getText("pisell2.saas.team-members.bind.confirm.rebind-content"),
				okText: getText("pisell2.saas.team-members.bind.modal.ok"),
				cancelText: getText("pisell2.saas.team-members.bind.modal.cancel"),
				onOk: () => openBindModal()
			});
			return;
		}
		openBindModal();
	}, [
		relationRecord,
		getText,
		openBindModal
	]);
	const handleBindConfirm = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (!tenantAccountId || !selectedRecordId) return;
		if (selectedRecordId == (relationRecord === null || relationRecord === void 0 ? void 0 : relationRecord.form_record_id)) return;
		yield upsertRelationRecord(selectedRecordId);
		setBindModalVisible(false);
	}), [
		tenantAccountId,
		selectedRecordId,
		relationRecord === null || relationRecord === void 0 ? void 0 : relationRecord.form_record_id,
		upsertRelationRecord
	]);
	const handleUnbind = (0, react.useCallback)(() => {
		if (!relationRecord) return;
		modal.confirm({
			title: getText("pisell2.saas.team-members.bind.confirm.unbind-title"),
			content: getText("pisell2.saas.team-members.bind.confirm.unbind-content"),
			okText: getText("pisell2.saas.team-members.drawer.save"),
			cancelText: getText("pisell2.saas.team-members.drawer.cancel"),
			onOk: function() {
				var _ref4 = require_asyncToGenerator._asyncToGenerator(function* () {
					setIsBinding(true);
					try {
						yield require_serve.unbindRelationRecord(relationRecord.id);
						setRelationRecord(null);
						yield refreshRelationList === null || refreshRelationList === void 0 ? void 0 : refreshRelationList();
					} catch (e) {}
					setIsBinding(false);
				});
				return function onOk() {
					return _ref4.apply(this, arguments);
				};
			}()
		});
	}, [
		relationRecord,
		getText,
		refreshRelationList
	]);
	const menuItems = relationRecord ? [{
		key: "bind",
		icon: /* @__PURE__ */ react.default.createElement(_pisell_materials.Icon, {
			type: "pisell2-link-01",
			size: 16
		}),
		label: getText("pisell2.saas.team-members.bind.menu.bind"),
		onClick: openBindWithConfirm
	}, {
		key: "unbind",
		icon: /* @__PURE__ */ react.default.createElement(_pisell_materials.Icon, {
			type: "pisell2-link-broken-02",
			size: 16
		}),
		label: getText("pisell2.saas.team-members.bind.menu.unbind"),
		onClick: handleUnbind
	}] : [{
		key: "bind",
		icon: /* @__PURE__ */ react.default.createElement(_pisell_materials.Icon, {
			type: "pisell2-link-01",
			size: 16
		}),
		label: getText("pisell2.saas.team-members.bind.menu.bind"),
		onClick: openBindWithConfirm
	}];
	return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement("div", { className: `${prefix}_extension-tab-content` }, /* @__PURE__ */ react.default.createElement("div", { className: `${prefix}_section-header` }, /* @__PURE__ */ react.default.createElement("div", { className: `${prefix}_section-header-title` }, getText("pisell2.saas.team-members.tab.extended-fields").replace("{roleName}", tabLabel)), /* @__PURE__ */ react.default.createElement("div", { className: `${prefix}_section-header-subtitle` }, getText("pisell2.saas.team-members.form.extend-fields-subtitle").replace("{roleName}", tabLabel)), /* @__PURE__ */ react.default.createElement("div", { className: `${prefix}_section-header-actions` }, /* @__PURE__ */ react.default.createElement(_pisell_materials.Dropdown, {
		menu: { items: menuItems },
		trigger: ["click"]
	}, /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
		type: "text",
		icon: /* @__PURE__ */ react.default.createElement(_pisell_materials.Icon, {
			type: "pisell2-dots-vertical",
			size: 18
		})
	})))), /* @__PURE__ */ react.default.createElement("div", { className: "extension-form-iframe-container" }, (loading || isBinding) && /* @__PURE__ */ react.default.createElement("div", { className: "extension-form-iframe-loading" }, /* @__PURE__ */ react.default.createElement(antd.Spin, { size: "large" })), /* @__PURE__ */ react.default.createElement("iframe", {
		ref: iframeRef,
		src: iframeUrl,
		title: `Extension Form ${formId}`,
		className: "extension-form-iframe",
		onLoad: handleIframeLoad,
		style: {
			width: "100%",
			height: "100%",
			border: "none",
			opacity: loading ? 0 : 1,
			transition: "opacity 0.3s ease"
		}
	})), /* @__PURE__ */ react.default.createElement(antd.Modal, {
		open: bindModalVisible,
		title: getText("pisell2.saas.team-members.bind.modal.title"),
		onOk: handleBindConfirm,
		onCancel: () => {
			setBindModalVisible(false);
			setRecordKeyword("");
		},
		okText: getText("pisell2.saas.team-members.bind.modal.ok"),
		cancelText: getText("pisell2.saas.team-members.bind.modal.cancel"),
		styles: { header: { padding: "0px 0px 8px 0px" } },
		okButtonProps: { disabled: !selectedRecordId || selectedRecordId === (relationRecord === null || relationRecord === void 0 ? void 0 : relationRecord.form_record_id) }
	}, /* @__PURE__ */ react.default.createElement("div", { style: {
		marginBottom: 16,
		color: "#7a7d80"
	} }, getText("pisell2.saas.team-members.bind.modal.description")), /* @__PURE__ */ react.default.createElement("div", { className: `${prefix}_bind-modal-label` }, getText("pisell2.saas.team-members.bind.modal.select-record")), /* @__PURE__ */ react.default.createElement("div", { style: { display: "flex" } }, /* @__PURE__ */ react.default.createElement(_pisell_materials.Select, {
		size: "large",
		style: { flex: 1 },
		placeholder: getText("pisell2.saas.team-members.bind.modal.placeholder"),
		allowClear: true,
		loading: recordsLoading,
		value: selectedRecordId,
		onChange: (val) => setSelectedRecordId(val),
		showSearch: true,
		filterOption: false,
		onSearch: (kw) => setRecordKeyword(kw),
		options: _recordOptions
	})))), /* @__PURE__ */ react.default.createElement(antd.ConfigProvider, { prefixCls: "pisell-lowcode" }, contextHolder));
});
//#endregion
exports.default = ExtensionFormTabContent;
