import { _asyncToGenerator } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { bindRelationRecord, getFormRecords, unbindRelationRecord, updateRelationRecord } from "../../serve.js";
import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { ConfigProvider, Modal, Spin } from "antd";
import { sendWarningLog } from "@pisell/utils";
import { Button as Button$1, Dropdown as Dropdown$1, Icon, Select as Select$1 } from "@pisell/materials";
import { useRequest } from "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.forwardRef(({ formId, domain, token, locale, tenantAccountId, onDirtyChange, onLoad, onCancel, getText, tabLabel, prefix, relationList, refreshRelationList }, ref) => {
	const iframeRef = useRef(null);
	const [loading, setLoading] = useState(true);
	const [relationRecord, setRelationRecord] = useState(null);
	const [isBinding, setIsBinding] = useState(false);
	const [bindModalVisible, setBindModalVisible] = useState(false);
	const [selectedRecordId, setSelectedRecordId] = useState(void 0);
	const [recordKeyword, setRecordKeyword] = useState("");
	const [modal, contextHolder] = Modal.useModal();
	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 } = useRequest(function() {
		var _ref = _asyncToGenerator(function* (kw) {
			return yield 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
	});
	useEffect(() => {
		if (bindModalVisible) runGetRecords(recordKeyword);
	}, [
		bindModalVisible,
		recordKeyword,
		runGetRecords
	]);
	const _recordOptions = 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.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
	]);
	useEffect(() => {
		if (iframeUrl) try {
			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 = useCallback(function() {
		var _ref2 = _asyncToGenerator(function* (rid) {
			if (!rid || !tenantAccountId) return;
			try {
				setIsBinding(true);
				if (!relationRecord) yield bindRelationRecord({
					relation_type: "tenant_account",
					relation_id: tenantAccountId,
					form_id: formId,
					form_record_id: rid
				});
				else if (relationRecord.form_record_id !== rid) yield 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 = useCallback(function() {
		var _ref3 = _asyncToGenerator(function* (rid) {
			if (!rid) return;
			yield upsertRelationRecord(rid);
		});
		return function(_x3) {
			return _ref3.apply(this, arguments);
		};
	}(), [upsertRelationRecord]);
	const handleMessage = 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
	]);
	useEffect(() => {
		window.addEventListener("message", handleMessage);
		return () => {
			window.removeEventListener("message", handleMessage);
		};
	}, [handleMessage]);
	const sendMessage = 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]);
	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 = useCallback(() => {
		setTimeout(() => {
			setLoading(false);
		}, 1e3);
	}, []);
	const openBindModal = useCallback(() => {
		setBindModalVisible(true);
		setSelectedRecordId(relationRecord === null || relationRecord === void 0 ? void 0 : relationRecord.form_record_id);
		setRecordKeyword("");
	}, [relationRecord]);
	const openBindWithConfirm = 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 = useCallback(_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 = 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 = _asyncToGenerator(function* () {
					setIsBinding(true);
					try {
						yield 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.createElement(Icon, {
			type: "pisell2-link-01",
			size: 16
		}),
		label: getText("pisell2.saas.team-members.bind.menu.bind"),
		onClick: openBindWithConfirm
	}, {
		key: "unbind",
		icon: /* @__PURE__ */ React.createElement(Icon, {
			type: "pisell2-link-broken-02",
			size: 16
		}),
		label: getText("pisell2.saas.team-members.bind.menu.unbind"),
		onClick: handleUnbind
	}] : [{
		key: "bind",
		icon: /* @__PURE__ */ React.createElement(Icon, {
			type: "pisell2-link-01",
			size: 16
		}),
		label: getText("pisell2.saas.team-members.bind.menu.bind"),
		onClick: openBindWithConfirm
	}];
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: `${prefix}_extension-tab-content` }, /* @__PURE__ */ React.createElement("div", { className: `${prefix}_section-header` }, /* @__PURE__ */ React.createElement("div", { className: `${prefix}_section-header-title` }, getText("pisell2.saas.team-members.tab.extended-fields").replace("{roleName}", tabLabel)), /* @__PURE__ */ React.createElement("div", { className: `${prefix}_section-header-subtitle` }, getText("pisell2.saas.team-members.form.extend-fields-subtitle").replace("{roleName}", tabLabel)), /* @__PURE__ */ React.createElement("div", { className: `${prefix}_section-header-actions` }, /* @__PURE__ */ React.createElement(Dropdown$1, {
		menu: { items: menuItems },
		trigger: ["click"]
	}, /* @__PURE__ */ React.createElement(Button$1, {
		type: "text",
		icon: /* @__PURE__ */ React.createElement(Icon, {
			type: "pisell2-dots-vertical",
			size: 18
		})
	})))), /* @__PURE__ */ React.createElement("div", { className: "extension-form-iframe-container" }, (loading || isBinding) && /* @__PURE__ */ React.createElement("div", { className: "extension-form-iframe-loading" }, /* @__PURE__ */ React.createElement(Spin, { size: "large" })), /* @__PURE__ */ React.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.createElement(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.createElement("div", { style: {
		marginBottom: 16,
		color: "#7a7d80"
	} }, getText("pisell2.saas.team-members.bind.modal.description")), /* @__PURE__ */ React.createElement("div", { className: `${prefix}_bind-modal-label` }, getText("pisell2.saas.team-members.bind.modal.select-record")), /* @__PURE__ */ React.createElement("div", { style: { display: "flex" } }, /* @__PURE__ */ React.createElement(Select$1, {
		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.createElement(ConfigProvider, { prefixCls: "pisell-lowcode" }, contextHolder));
});
//#endregion
export { ExtensionFormTabContent as default };
