require("../../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
let react = require("react");
let ahooks = require("ahooks");
//#region src/components/pay/toC/PaymentMethods/hooks/index.tsx
/**
* 支付跳转 Hook
* 用于处理跳转到外部支付页面的逻辑，包括：
* 1. 保存跳转标记到 history state
* 2. 跳转到外部支付页面
* 3. 监听页面返回事件
* 4. 返回后更新状态
*/
const usePaymentRedirect = (options) => {
	const { orderId, paymentType, onAfterReturn } = options;
	const [isReturned, setIsReturned] = (0, react.useState)(false);
	/**
	* 执行跳转
	*/
	const handleRedirect = (0, ahooks.useMemoizedFn)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (url) {
			try {
				const currentState = window.history.state || {};
				window.history.replaceState(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, currentState), {}, {
					paymentRedirected: true,
					paymentType,
					orderId,
					timestamp: Date.now()
				}), "", window.location.href);
				window.location.href = url;
			} catch (error) {
				throw error;
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}());
	/**
	* 重置状态
	*/
	const resetState = (0, ahooks.useMemoizedFn)(() => {
		setIsReturned(false);
	});
	/**
	* 监听页面显示事件（包括浏览器返回按钮）
	*/
	(0, react.useEffect)(() => {
		const handlePageShow = (event) => {
			if (!orderId) return;
			const historyState = window.history.state;
			if ((historyState === null || historyState === void 0 ? void 0 : historyState.paymentRedirected) && (historyState === null || historyState === void 0 ? void 0 : historyState.paymentType) === paymentType && (historyState === null || historyState === void 0 ? void 0 : historyState.orderId) === orderId) {
				console.log(`检测到从 ${paymentType} 返回, event.persisted:`, event.persisted);
				setIsReturned(true);
				if (onAfterReturn) onAfterReturn();
				const newState = require_objectSpread2._objectSpread2({}, historyState);
				delete newState.paymentRedirected;
				delete newState.paymentType;
				delete newState.timestamp;
				delete newState.orderId;
				window.history.replaceState(newState, "", window.location.href);
			}
		};
		handlePageShow({ persisted: false });
		window.addEventListener("pageshow", handlePageShow);
		return () => {
			window.removeEventListener("pageshow", handlePageShow);
		};
	}, [orderId, paymentType]);
	return {
		isReturned,
		handleRedirect,
		resetState
	};
};
//#endregion
exports.usePaymentRedirect = usePaymentRedirect;
