const require_runtime = require("../../_virtual/_rolldown/runtime.js");
const require_asyncToGenerator = require("../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_model = require("../booking/info/model.js");
const require_useEngineContext = require("../../hooks/useEngineContext.js");
const require_useLogger = require("../../hooks/useLogger.js");
const require_index = require("../../utils/index.js");
const require_PaymentModal = require("./PaymentModal.js");
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_materials = require("@pisell/materials");
//#region src/components/checkout/plugin.tsx
function getPluginOrderId(engineProps) {
	var _ref, _engineProps$order$id, _engineProps$order;
	return (_ref = (_engineProps$order$id = (_engineProps$order = engineProps.order) === null || _engineProps$order === void 0 ? void 0 : _engineProps$order.id) !== null && _engineProps$order$id !== void 0 ? _engineProps$order$id : engineProps.order_id) !== null && _ref !== void 0 ? _ref : engineProps.orderId;
}
function hasPluginOrderId(orderId) {
	return orderId !== void 0 && orderId !== null && String(orderId).trim() !== "";
}
function getPluginBaseSalesModuleName(engineProps, orderId) {
	return engineProps.baseSalesModuleName || (hasPluginOrderId(orderId) ? "baseSales" : "");
}
function getErrorMessage(error) {
	return error instanceof Error ? error.message : String(error || "Unknown error");
}
function getBaseSalesLoadedOrderId(module) {
	var _module$getOrderSnaps, _identity$orderId;
	const snapshot = module === null || module === void 0 || (_module$getOrderSnaps = module.getOrderSnapshot) === null || _module$getOrderSnaps === void 0 ? void 0 : _module$getOrderSnaps.call(module);
	const identity = (snapshot === null || snapshot === void 0 ? void 0 : snapshot.identity) || {};
	const tempOrder = (snapshot === null || snapshot === void 0 ? void 0 : snapshot.tempOrder) || {};
	return (_identity$orderId = identity.orderId) !== null && _identity$orderId !== void 0 ? _identity$orderId : tempOrder.order_id;
}
const PaymentModalContent = () => {
	var _context$engine;
	const context = require_useEngineContext.default();
	const Toast = (0, _pisell_materials.useToast)();
	const logger = require_useLogger.default();
	const engineProps = ((_context$engine = context.engine) === null || _context$engine === void 0 ? void 0 : _context$engine.props) || {};
	const orderId = getPluginOrderId(engineProps);
	const baseSalesModuleName = getPluginBaseSalesModuleName(engineProps, orderId);
	const { pisellos, pisellosAllModule, businessUtils } = context.appHelper.utils || {};
	const { BaseSalesImpl } = pisellosAllModule || {};
	require_index.request.setRequest(context.appHelper.utils.request);
	const initialBaseSalesModule = (0, react.useMemo)(() => {
		var _pisellos$getModule;
		if (!baseSalesModuleName) return null;
		return (pisellos === null || pisellos === void 0 || (_pisellos$getModule = pisellos.getModule) === null || _pisellos$getModule === void 0 ? void 0 : _pisellos$getModule.call(pisellos, baseSalesModuleName)) || null;
	}, [baseSalesModuleName, pisellos]);
	const [baseSalesModule, setBaseSalesModule] = (0, react.useState)(initialBaseSalesModule);
	const [isLoadingFallbackModule, setIsLoadingFallbackModule] = (0, react.useState)(false);
	const [loadedOrderId, setLoadedOrderId] = (0, react.useState)("");
	(0, react.useEffect)(() => {
		setBaseSalesModule(initialBaseSalesModule);
	}, [initialBaseSalesModule]);
	(0, react.useEffect)(() => {
		var _pisellos$getModule2;
		if (!baseSalesModuleName) {
			var _logger$addLog, _Toast$error, _engineProps$callback;
			logger === null || logger === void 0 || (_logger$addLog = logger.addLog) === null || _logger$addLog === void 0 || _logger$addLog.call(logger, {
				metadata: { engineProps },
				title: "打开支付弹窗失败-缺少 baseSalesModuleName 和 orderId"
			});
			Toast === null || Toast === void 0 || (_Toast$error = Toast.error) === null || _Toast$error === void 0 || _Toast$error.call(Toast, "Missing baseSalesModuleName or orderId");
			(_engineProps$callback = engineProps.callback) === null || _engineProps$callback === void 0 || _engineProps$callback.call(engineProps, {
				type: "error",
				error: "missing_base_sales_module_name"
			});
			return;
		}
		const existingModule = (pisellos === null || pisellos === void 0 || (_pisellos$getModule2 = pisellos.getModule) === null || _pisellos$getModule2 === void 0 ? void 0 : _pisellos$getModule2.call(pisellos, baseSalesModuleName)) || baseSalesModule;
		if (existingModule) {
			let isCancelled = false;
			let hasOpenedPaymentModal = false;
			const currentOrderId = getBaseSalesLoadedOrderId(existingModule);
			const shouldReloadOrder = hasPluginOrderId(orderId) && String(currentOrderId || "") !== String(orderId);
			(function() {
				var _ref3 = require_asyncToGenerator._asyncToGenerator(function* () {
					var _ref2, _getBaseSalesLoadedOr, _Toast$hide;
					if (shouldReloadOrder) {
						setIsLoadingFallbackModule(true);
						yield existingModule.loadSalesDetail(orderId);
					}
					if (isCancelled) return;
					setBaseSalesModule(existingModule);
					setLoadedOrderId(String((_ref2 = (_getBaseSalesLoadedOr = getBaseSalesLoadedOrderId(existingModule)) !== null && _getBaseSalesLoadedOr !== void 0 ? _getBaseSalesLoadedOr : orderId) !== null && _ref2 !== void 0 ? _ref2 : ""));
					window.isPaymentModalPluginOpen = true;
					hasOpenedPaymentModal = true;
					Toast === null || Toast === void 0 || (_Toast$hide = Toast.hide) === null || _Toast$hide === void 0 || _Toast$hide.call(Toast);
					setIsLoadingFallbackModule(false);
				});
				return function openWithExistingModule() {
					return _ref3.apply(this, arguments);
				};
			})()().catch((error) => {
				var _logger$addLog2, _Toast$error2, _engineProps$callback2;
				if (isCancelled) return;
				const message = getErrorMessage(error);
				logger === null || logger === void 0 || (_logger$addLog2 = logger.addLog) === null || _logger$addLog2 === void 0 || _logger$addLog2.call(logger, {
					metadata: {
						baseSalesModuleName,
						orderId,
						error
					},
					title: "打开支付弹窗失败-切换 BaseSales 订单失败"
				});
				Toast === null || Toast === void 0 || (_Toast$error2 = Toast.error) === null || _Toast$error2 === void 0 || _Toast$error2.call(Toast, message);
				(_engineProps$callback2 = engineProps.callback) === null || _engineProps$callback2 === void 0 || _engineProps$callback2.call(engineProps, {
					type: "error",
					error: "switch_base_sales_order_failed",
					data: {
						baseSalesModuleName,
						orderId,
						message
					}
				});
				setIsLoadingFallbackModule(false);
			});
			return () => {
				isCancelled = true;
				if (hasOpenedPaymentModal) window.isPaymentModalPluginOpen = false;
			};
		}
		if (!hasPluginOrderId(orderId) || !BaseSalesImpl || !(pisellos === null || pisellos === void 0 ? void 0 : pisellos.registerModule)) {
			var _logger$addLog3, _Toast$error3, _engineProps$callback3;
			logger === null || logger === void 0 || (_logger$addLog3 = logger.addLog) === null || _logger$addLog3 === void 0 || _logger$addLog3.call(logger, {
				metadata: {
					baseSalesModuleName,
					orderId,
					hasBaseSalesImpl: !!BaseSalesImpl
				},
				title: "打开支付弹窗失败-BaseSales 模块不存在"
			});
			Toast === null || Toast === void 0 || (_Toast$error3 = Toast.error) === null || _Toast$error3 === void 0 || _Toast$error3.call(Toast, "BaseSales module not found");
			(_engineProps$callback3 = engineProps.callback) === null || _engineProps$callback3 === void 0 || _engineProps$callback3.call(engineProps, {
				type: "error",
				error: "base_sales_module_not_found",
				data: { baseSalesModuleName }
			});
			return;
		}
		let isCancelled = false;
		let hasOpenedPaymentModal = false;
		(function() {
			var _ref5 = require_asyncToGenerator._asyncToGenerator(function* () {
				setIsLoadingFallbackModule(true);
				try {
					var _businessUtils$getApp, _ref4, _getBaseSalesLoadedOr2, _Toast$hide2;
					const fallbackModule = new BaseSalesImpl(baseSalesModuleName);
					yield pisellos.registerModule(fallbackModule, {
						initialState: {},
						otherParams: {
							cacheId: baseSalesModuleName,
							platform: "shop",
							isFranchisee: businessUtils === null || businessUtils === void 0 || (_businessUtils$getApp = businessUtils.getAppByModal) === null || _businessUtils$getApp === void 0 ? void 0 : _businessUtils$getApp.call(businessUtils, "franchisee")
						}
					});
					yield fallbackModule.loadSalesDetail(orderId);
					if (isCancelled) return;
					setBaseSalesModule(fallbackModule);
					setLoadedOrderId(String((_ref4 = (_getBaseSalesLoadedOr2 = getBaseSalesLoadedOrderId(fallbackModule)) !== null && _getBaseSalesLoadedOr2 !== void 0 ? _getBaseSalesLoadedOr2 : orderId) !== null && _ref4 !== void 0 ? _ref4 : ""));
					window.isPaymentModalPluginOpen = true;
					hasOpenedPaymentModal = true;
					Toast === null || Toast === void 0 || (_Toast$hide2 = Toast.hide) === null || _Toast$hide2 === void 0 || _Toast$hide2.call(Toast);
				} catch (error) {
					var _logger$addLog4, _Toast$error4, _engineProps$callback4;
					if (isCancelled) return;
					const message = getErrorMessage(error);
					logger === null || logger === void 0 || (_logger$addLog4 = logger.addLog) === null || _logger$addLog4 === void 0 || _logger$addLog4.call(logger, {
						metadata: {
							baseSalesModuleName,
							orderId,
							error
						},
						title: "打开支付弹窗失败-兜底加载 BaseSales 订单失败"
					});
					Toast === null || Toast === void 0 || (_Toast$error4 = Toast.error) === null || _Toast$error4 === void 0 || _Toast$error4.call(Toast, message);
					(_engineProps$callback4 = engineProps.callback) === null || _engineProps$callback4 === void 0 || _engineProps$callback4.call(engineProps, {
						type: "error",
						error: "fallback_base_sales_load_failed",
						data: {
							baseSalesModuleName,
							orderId,
							message
						}
					});
				} finally {
					if (!isCancelled) setIsLoadingFallbackModule(false);
				}
			});
			return function bootstrapFallbackModule() {
				return _ref5.apply(this, arguments);
			};
		})()();
		return () => {
			isCancelled = true;
			if (hasOpenedPaymentModal) window.isPaymentModalPluginOpen = false;
		};
	}, [
		BaseSalesImpl,
		Toast,
		baseSalesModule,
		baseSalesModuleName,
		businessUtils,
		engineProps,
		logger,
		orderId,
		pisellos
	]);
	if (!baseSalesModuleName || !baseSalesModule || isLoadingFallbackModule) return null;
	return /* @__PURE__ */ react.default.createElement(require_PaymentModal.default, {
		key: `${baseSalesModuleName}-${loadedOrderId}`,
		open: true,
		baseSalesModuleName,
		paymentResultDisplayMode: engineProps.paymentResultDisplayMode || "toast",
		config: engineProps.config,
		onCustomerChange: engineProps.onCustomerChange,
		onClose: (reset) => {
			var _engineProps$callback5;
			window.isPaymentModalPluginOpen = false;
			(_engineProps$callback5 = engineProps.callback) === null || _engineProps$callback5 === void 0 || _engineProps$callback5.call(engineProps, {
				type: "close",
				reset
			});
		},
		callback: (result) => {
			var _engineProps$callback6;
			if (result === null || result === void 0 ? void 0 : result.isCallbackFromToast) return;
			(_engineProps$callback6 = engineProps.callback) === null || _engineProps$callback6 === void 0 || _engineProps$callback6.call(engineProps, {
				type: "callback",
				data: result
			});
			window.isPaymentModalPluginOpen = false;
		}
	});
};
const PaymentModalPlugin = require_model.Provider(PaymentModalContent);
//#endregion
exports.default = PaymentModalPlugin;
