require("../../../_virtual/_rolldown/runtime.js");
const require_asyncToGenerator = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../../hooks/useEngineContext.js");
let react = require("react");
let ahooks = require("ahooks");
//#region src/plus/salesSdk/hooks/useSalesSdkTempOrderSync.ts
const TEMP_ORDER_SYNC_MESSAGE_TYPE = "sales_sdk_temp_order_sync";
function createSourceId() {
	return `sales-sdk-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function getPayload(event) {
	var _event$data;
	const payload = event === null || event === void 0 || (_event$data = event.data) === null || _event$data === void 0 || (_event$data = _event$data.payload) === null || _event$data === void 0 ? void 0 : _event$data.data;
	if ((payload === null || payload === void 0 ? void 0 : payload.type) !== TEMP_ORDER_SYNC_MESSAGE_TYPE) return null;
	return payload;
}
/**
* SalesSdk tempOrder 双屏同步：
* 主屏在快照刷新后发布 tempOrder；isActive 从 false → true 时再推送一次当前 tempOrder。
* 副屏接收后写回 OS 并刷新 React 快照。
*/
function useSalesSdkTempOrderSync({ enabled, isActive = true, osKey, bookingTicket, refreshRootSnapshot }) {
	var _context$appHelper, _context$appHelper$ge, _app$getPlugin, _unifiedCommunication;
	const context = require_useEngineContext.default();
	const app = context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 || (_context$appHelper$ge = _context$appHelper.getApp) === null || _context$appHelper$ge === void 0 ? void 0 : _context$appHelper$ge.call(_context$appHelper);
	const unifiedCommunication = app === null || app === void 0 || (_app$getPlugin = app.getPlugin) === null || _app$getPlugin === void 0 ? void 0 : _app$getPlugin.call(app, "unifiedCommunication");
	const { runtime } = (unifiedCommunication === null || unifiedCommunication === void 0 || (_unifiedCommunication = unifiedCommunication.useRuntime) === null || _unifiedCommunication === void 0 ? void 0 : _unifiedCommunication.call(unifiedCommunication)) || {};
	const isSecondaryScreen = (runtime === null || runtime === void 0 ? void 0 : runtime.role) === "secondary-screen";
	const sourceIdRef = (0, react.useRef)(createSourceId());
	const prevIsActiveRef = (0, react.useRef)(isActive);
	const { run: debouncedPublish } = (0, ahooks.useDebounceFn)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (tempOrder) {
			if (!enabled || isSecondaryScreen || !tempOrder) return;
			try {
				var _unifiedCommunication2, _unifiedCommunication3;
				yield unifiedCommunication === null || unifiedCommunication === void 0 || (_unifiedCommunication2 = unifiedCommunication.sdk) === null || _unifiedCommunication2 === void 0 || (_unifiedCommunication3 = _unifiedCommunication2.publishData) === null || _unifiedCommunication3 === void 0 ? void 0 : _unifiedCommunication3.call(_unifiedCommunication2, {
					target: { type: "secondary-screen" },
					data: {
						type: TEMP_ORDER_SYNC_MESSAGE_TYPE,
						osKey,
						sourceId: sourceIdRef.current,
						timestamp: Date.now(),
						tempOrder
					},
					meta: {}
				});
			} catch (error) {
				console.warn("[SalesSdk] tempOrder 同步到副屏失败", error);
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}(), {
		wait: 500,
		leading: true,
		trailing: true
	});
	const publishTempOrder = (0, ahooks.useMemoizedFn)((tempOrder) => {
		if (!enabled || isSecondaryScreen || !tempOrder) return;
		debouncedPublish(tempOrder);
	});
	(0, react.useEffect)(() => {
		if (!enabled || isSecondaryScreen) {
			prevIsActiveRef.current = isActive;
			return;
		}
		if (isActive && !prevIsActiveRef.current) {
			var _bookingTicket$getTem, _bookingTicket$getTem2;
			publishTempOrder((_bookingTicket$getTem = bookingTicket === null || bookingTicket === void 0 || (_bookingTicket$getTem2 = bookingTicket.getTempOrder) === null || _bookingTicket$getTem2 === void 0 ? void 0 : _bookingTicket$getTem2.call(bookingTicket)) !== null && _bookingTicket$getTem !== void 0 ? _bookingTicket$getTem : null);
		}
		prevIsActiveRef.current = isActive;
	}, [
		isActive,
		enabled,
		isSecondaryScreen,
		bookingTicket,
		publishTempOrder
	]);
	const { run: debouncedApply } = (0, ahooks.useDebounceFn)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (tempOrder) {
			if (!(bookingTicket === null || bookingTicket === void 0 ? void 0 : bookingTicket.replaceTempOrder)) {
				console.warn("[SalesSdk] 当前 BookingTicket 不支持 replaceTempOrder，已跳过副屏同步");
				return;
			}
			try {
				yield bookingTicket.replaceTempOrder(tempOrder);
				refreshRootSnapshot();
			} catch (error) {
				console.warn("[SalesSdk] 副屏应用 tempOrder 同步失败", error);
			}
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}(), { wait: 100 });
	(0, react.useEffect)(() => {
		var _unifiedCommunication4, _unifiedCommunication5;
		if (!enabled || !isSecondaryScreen || !bookingTicket) return;
		const handleMessage = (event) => {
			const payload = getPayload(event);
			if (!payload) return;
			if (payload.osKey !== osKey) return;
			if (payload.sourceId === sourceIdRef.current) return;
			if (!payload.tempOrder) return;
			debouncedApply(payload.tempOrder);
		};
		const listenerHandle = unifiedCommunication === null || unifiedCommunication === void 0 || (_unifiedCommunication4 = unifiedCommunication.sdk) === null || _unifiedCommunication4 === void 0 || (_unifiedCommunication5 = _unifiedCommunication4.onMessage) === null || _unifiedCommunication5 === void 0 ? void 0 : _unifiedCommunication5.call(_unifiedCommunication4, handleMessage);
		return () => {
			if (listenerHandle && typeof listenerHandle.then === "function") listenerHandle.then((handle) => {
				var _handle$remove;
				return handle === null || handle === void 0 || (_handle$remove = handle.remove) === null || _handle$remove === void 0 ? void 0 : _handle$remove.call(handle);
			}).catch(() => {});
			else {
				var _remove;
				listenerHandle === null || listenerHandle === void 0 || (_remove = listenerHandle.remove) === null || _remove === void 0 || _remove.call(listenerHandle);
			}
		};
	}, [
		enabled,
		isSecondaryScreen,
		bookingTicket,
		osKey,
		debouncedApply,
		unifiedCommunication
	]);
	return {
		publishTempOrder,
		isSecondaryScreen
	};
}
//#endregion
exports.useSalesSdkTempOrderSync = useSalesSdkTempOrderSync;
