const require_runtime = require("../../_virtual/_rolldown/runtime.js");
const require_locales = require("../../utils/locales.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");
const require_useEngineContext = require("../../hooks/useEngineContext.js");
const require_index = require("../../plus/noteModal/index.js");
const require_index$1 = require("../../pro/priceKeyboard/components/paymentKeyboard/index.js");
const require_index$2 = require("../../pro/priceKeyboard/components/discountKeyboard/index.js");
const require_locales$1 = require("./locales.js");
const require_index$3 = require("./components/SendPaymentLinkModal/index.js");
const require_index$4 = require("./components/AmountSummary/index.js");
const require_index$5 = require("./components/SavePayLaterHandler/index.js");
const require_usePaymentLogger = require("./hooks/usePaymentLogger.js");
const require_useActiveExecute = require("../ticketBooking/hooks/pisellos/useActiveExecute.js");
const require_constants = require("./constants.js");
const require_index$6 = require("./components/WalletPassModule/index.js");
const require_index$7 = require("./components/PaymentOptionsModule/index.js");
const require_index$8 = require("./components/CashPaymentModule/index.js");
const require_index$9 = require("./components/AdditionalModule/index.js");
const require_utils = require("./components/PaymentResultToast/utils.js");
const require_PaymentResultToastProvider = require("./components/PaymentResultToast/PaymentResultToastProvider.js");
const require_PaymentResultToastUtils = require("./utils/PaymentResultToastUtils.js");
const require_styles = require("./styles.js");
const require_index$10 = require("../pay/toB/paymentMethods/index.js");
const require_index$11 = require("./components/SearchAndClientModule/index.js");
const require_utils$1 = require("./utils.js");
const require_printer = require("../../hooks/printer.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let decimal_js = require("decimal.js");
decimal_js = require_runtime.__toESM(decimal_js);
let lodash = require("lodash");
let _pisell_materials = require("@pisell/materials");
let ahooks = require("ahooks");
let react_dom = require("react-dom");
react_dom = require_runtime.__toESM(react_dom);
let _pisell_icon = require("@pisell/icon");
require("./index.less");
//#region src/components/checkout/PaymentModal.tsx
const CheckoutHooks = {
	OnStateAmountChanged: "checkout:onStateAmountChanged",
	OnBalanceDueAmountChanged: "checkout:onBalanceDueAmountChanged",
	OnOrderSubmitStart: "checkout:onOrderSubmitStart",
	OnOrderSubmitEnd: "checkout:onOrderSubmitEnd",
	OnOrderSyncFailed: "checkout:onOrderSyncFailed",
	OnOrderPaymentAdded: "checkout:onPaymentItemAdded"
};
/**
* @description
* 根据 WalletPassUsage 配置，将传入的货币金额转换为 WalletPass 面额（points）。
*
* 对齐后端 PHP 逻辑：
* - 无有效 points / price 时：按 1:1 返回货币金额格式化字符串
* - 计算方式：currencyAmount / price (保留 6 位小数，直接截断) * points
* - 返回值：保留 2 位小数，第三位舍去（不四舍五入）
*/
function convertCurrencyAmountToWalletPassValue(params) {
	var _toDecimalOrNull, _params$walletPassUsa, _params$walletPassUsa2;
	const currencyDecimal = (_toDecimalOrNull = toDecimalOrNull(params.currencyAmount)) !== null && _toDecimalOrNull !== void 0 ? _toDecimalOrNull : new decimal_js.default(0);
	const pointsDecimal = toDecimalOrNull((_params$walletPassUsa = params.walletPassUsageUnit) === null || _params$walletPassUsa === void 0 ? void 0 : _params$walletPassUsa.points);
	const priceDecimal = toDecimalOrNull((_params$walletPassUsa2 = params.walletPassUsageUnit) === null || _params$walletPassUsa2 === void 0 ? void 0 : _params$walletPassUsa2.price);
	if (!pointsDecimal || !priceDecimal) return (0, _pisell_utils.formatAmount)(currencyDecimal.toNumber());
	if (pointsDecimal.eq(0) || priceDecimal.eq(0)) return (0, _pisell_utils.formatAmount)(currencyDecimal.toNumber());
	return currencyDecimal.div(priceDecimal).toDecimalPlaces(6, decimal_js.default.ROUND_DOWN).mul(pointsDecimal).toFixed(2, decimal_js.default.ROUND_DOWN);
}
/**
* @description
* 将任意输入安全转换为 Decimal
*/
function toDecimalOrNull(value) {
	if (value === null || value === void 0) return null;
	try {
		return new decimal_js.default(value);
	} catch (_unused) {
		return null;
	}
}
const PaymentContent = (0, react.forwardRef)(({ cartData, orderInfo, isModalOpen, onPaymentComplete, onPaymentCancel, onStatusChange, showingCashToastRef, onToastClose, orderNote, setOrderNote, setNoteModalSource, setNoteModalOpen, totalAmount = 0, moduleConfig: parentModuleConfig, onShowCashPaymentChange, showSuccessToast, dynamicMaxHeight = "600px", onOrderSyncFailed, generateActionButtons, paymentResultToastConfig, updateOrderInfo, setCurrentEditOrderId, paymentResultDisplayMode, shopDiscount, client, currentTotalPrice, onChangeShopDiscount, onChangeOrderNote, onDeleteOrderNote }, ref) => {
	var _parentModuleConfig$s;
	const { pisellos, getData, pisellosAllModule, interaction } = require_useEngineContext.default().appHelper.utils || {};
	const Toast = (0, _pisell_materials.useToast)();
	const { executeIfActive } = require_useActiveExecute.useActiveExecute();
	const checkoutRef = (0, react.useRef)(null);
	const savePayLaterHandlerRef = (0, react.useRef)(null);
	const [customAmount, setCustomAmount] = (0, react.useState)("");
	const [balanceDueAmount, setBalanceDueAmount] = (0, react.useState)("");
	const [balanceDueTotalAmount, setBalanceDueTotalAmount] = (0, react.useState)("");
	const [recommendAmounts, setRecommendAmounts] = (0, react.useState)([]);
	const [showSplitPaymentKeyboard, setShowSplitPaymentKeyboard] = (0, react.useState)(false);
	const paymentMethodsRef = (0, react.useRef)(null);
	const [paymentMethods, setPaymentMethods] = (0, react.useState)([]);
	const [showCashPayment, setShowCashPayment] = (0, react.useState)(false);
	const [paymentOptionsTitle, setPaymentOptionsTitle] = (0, react.useState)(_pisell_utils.locales.getText("cards.and.digitals") || "Cards & Digitals");
	const paymentOptionList = (0, react.useMemo)(() => {
		return paymentMethods.filter((item) => !(item.type === "app" && item.code === "EFTPOS_LINKLY") && (["custom"].includes(item.type) || require_index$7.SHOW_METHODS_CODE.includes(item.code)));
	}, [paymentMethods]);
	const clientChangedRef = (0, react.useRef)(false);
	const walletPassRef = (0, react.useRef)(null);
	const [paymentItems, setPaymentItems] = (0, react.useState)([]);
	const [walletPassData, setWalletPassData] = (0, react.useState)({});
	const { nativePrint } = require_printer.default();
	const [syncingLock, setSyncingLock] = (0, react.useState)(false);
	const isOrderFree = (0, react.useMemo)(() => {
		if (!customAmount) return false;
		return parseFloat(customAmount) <= 0;
	}, [customAmount]);
	const [paymentLinkModalOpen, setPaymentLinkModalOpen] = (0, react.useState)(false);
	const [showPriceAdjustModal, setShowPriceAdjustModal] = (0, react.useState)(false);
	const logger = require_usePaymentLogger.default();
	const currency = getData("shop_currency_code") || "USD";
	const open_deposit = getData("bookingv2_deposit") || 0;
	const checkoutModule = pisellos === null || pisellos === void 0 ? void 0 : pisellos.getModule("checkout");
	const walletPassDetail = (0, react.useMemo)(() => {
		return {
			map: paymentMethods.reduce((acc, item) => {
				if (require_constants.WALLET_PASS_CODE_ARRAY.includes(item.code)) acc[item.code] = item;
				return acc;
			}, {}),
			isShow: true
		};
	}, [paymentMethods]);
	const handleAddCashPayment = function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (result) {
			var _interaction$utils, _interaction$utils$po;
			const cashPaymentMethod = paymentMethods.find((method) => {
				var _method$name;
				return method.code === "CASHMANUAL" || method.type === "CASHMANUAL" || ((_method$name = method.name) === null || _method$name === void 0 ? void 0 : _method$name.toLowerCase().includes("cash"));
			});
			logger === null || logger === void 0 || logger.addLog({
				type: "info",
				title: "open_till",
				metadata: {}
			});
			interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || (_interaction$utils$po = _interaction$utils.postMessageToApp) === null || _interaction$utils$po === void 0 || _interaction$utils$po.call(_interaction$utils, {
				module: "till",
				key: "open_till",
				data: { type: "cash" }
			});
			yield checkoutModule === null || checkoutModule === void 0 ? void 0 : checkoutModule.addPaymentItemAsync({
				amount: result.amount,
				code: cashPaymentMethod === null || cashPaymentMethod === void 0 ? void 0 : cashPaymentMethod.code,
				id: cashPaymentMethod === null || cashPaymentMethod === void 0 ? void 0 : cashPaymentMethod.id,
				name: cashPaymentMethod === null || cashPaymentMethod === void 0 ? void 0 : cashPaymentMethod.name,
				type: cashPaymentMethod === null || cashPaymentMethod === void 0 ? void 0 : cashPaymentMethod.type,
				voucher_id: 0,
				rounding_amount: result.roundingAmount
			});
		});
		return function handleAddCashPayment(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	const processSurcharge = (surcharge) => {
		if (typeof surcharge === "string") {
			const match = surcharge.match(/\d+(?:\.\d+)?/);
			return match ? match[0] : void 0;
		}
		if (typeof surcharge === "number") return String(surcharge);
		return surcharge;
	};
	const onPaymentOptionClick = function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (method) {
			var _method$totalAmount;
			if (syncingLock) return;
			const { id, code, name, type } = method || {};
			const finalAmount = (_method$totalAmount = method.totalAmount) !== null && _method$totalAmount !== void 0 ? _method$totalAmount : customAmount;
			const eftposCodes = [
				"EFTPOS_LINKLY",
				"EFTPOS_PAYO",
				"EFTPOS_WINDCAVE",
				"EFTPOS_TYRO",
				"EFTPOS_HUIFU"
			];
			const mx51Code = "EFTPOS";
			let payType = "";
			if (eftposCodes.includes((method === null || method === void 0 ? void 0 : method.code) || "")) payType = "eftpos";
			if ((method === null || method === void 0 ? void 0 : method.code) === mx51Code) {
				var _paymentMethodsRef$cu;
				payType = "mx51";
				const orderId = yield checkoutModule.getCurrentOrderId();
				(_paymentMethodsRef$cu = paymentMethodsRef.current) === null || _paymentMethodsRef$cu === void 0 || _paymentMethodsRef$cu.onPay(payType, {
					source: "normal",
					data: {
						payMethod: {
							id,
							code,
							name,
							type
						},
						params: {
							orderId,
							symbol: getData("shop_symbol"),
							amount: finalAmount,
							surcharge: processSurcharge(method.surcharge)
						},
						mode: "pay"
					},
					callback: ({ status, data, msg }) => {
						console.log("eftpos_pay_result>>>>>>", status, data, msg);
						if (status === "success") {
							const payResultParams = {
								amount: Number(data === null || data === void 0 ? void 0 : data.amount),
								code,
								custom_payment_id: id,
								name,
								type,
								voucher_id: "",
								service_charge: {},
								metadata: { unique_payment_number: data === null || data === void 0 ? void 0 : data.uniquePaymentNumber }
							};
							if (payType === "mx51") if (Number((data === null || data === void 0 ? void 0 : data.surcharge) || 0) !== Number((method === null || method === void 0 ? void 0 : method.surcharge) || 0)) payResultParams.service_charge = {
								amount: (data === null || data === void 0 ? void 0 : data.surcharge) || "0",
								percentage: "0"
							};
							else payResultParams.service_charge = {
								amount: (method === null || method === void 0 ? void 0 : method.fixed) || "0",
								percentage: (method === null || method === void 0 ? void 0 : method.percentage) || "0"
							};
							checkoutModule === null || checkoutModule === void 0 || checkoutModule.addPaymentItemAsync(payResultParams);
						}
					}
				});
				return;
			}
			if (payType) {
				var _paymentMethodsRef$cu2;
				let data;
				if (!(yield checkoutModule.isCurrentOrderSynced())) {
					var _Toast$loading;
					Toast === null || Toast === void 0 || (_Toast$loading = Toast.loading) === null || _Toast$loading === void 0 || _Toast$loading.call(Toast, "", 0);
					data = yield checkoutModule.manualSyncOrderAsync();
				} else data = { orderId: yield checkoutModule.getCurrentOrderId() };
				(_paymentMethodsRef$cu2 = paymentMethodsRef.current) === null || _paymentMethodsRef$cu2 === void 0 || _paymentMethodsRef$cu2.onPay(payType, {
					source: "normal",
					data: {
						payMethod: {
							id,
							code,
							name,
							type
						},
						params: {
							orderId: data.orderId,
							symbol: getData("shop_symbol"),
							amount: finalAmount,
							surcharge: processSurcharge(method.surcharge),
							operator_type: "shop",
							platform: "pos"
						},
						mode: "pay"
					},
					callback: ({ status, data, msg }) => {
						console.log("eftpos_pay_result>>>>>>", status, data, msg);
						if (status === "success") {
							const payResultParams = {
								amount: Number(data === null || data === void 0 ? void 0 : data.amount),
								code,
								id,
								name,
								type,
								voucher_id: "",
								service_charge: {},
								metadata: { unique_payment_number: data === null || data === void 0 ? void 0 : data.uniquePaymentNumber }
							};
							if (payType === "eftpos") payResultParams.service_charge = {
								percentage: data === null || data === void 0 ? void 0 : data.surPercentRate,
								amount: data === null || data === void 0 ? void 0 : data.surMoney
							};
							else if (payType === "mx51") if (Number((data === null || data === void 0 ? void 0 : data.surcharge) || 0) !== Number((method === null || method === void 0 ? void 0 : method.surcharge) || 0)) payResultParams.service_charge = {
								amount: (data === null || data === void 0 ? void 0 : data.surcharge) || "0",
								percentage: "0"
							};
							else payResultParams.service_charge = {
								amount: (method === null || method === void 0 ? void 0 : method.fixed) || "0",
								percentage: (method === null || method === void 0 ? void 0 : method.percentage) || "0"
							};
							checkoutModule === null || checkoutModule === void 0 || checkoutModule.addPaymentItemAsync(payResultParams);
						}
					}
				});
			} else {
				var _method$metadata;
				let service_charge = null;
				if ((method === null || method === void 0 ? void 0 : method.fixed) || (method === null || method === void 0 ? void 0 : method.percentage)) service_charge = {
					amount: (method === null || method === void 0 ? void 0 : method.fixed) || "0",
					percentage: (method === null || method === void 0 ? void 0 : method.percentage) || "0"
				};
				if (method.type === "custom" && ((_method$metadata = method.metadata) === null || _method$metadata === void 0 ? void 0 : _method$metadata.order_open_cash_drawer)) {
					var _interaction$utils2, _interaction$utils2$p;
					logger === null || logger === void 0 || logger.addLog({
						type: "info",
						title: "open_till",
						metadata: {}
					});
					interaction === null || interaction === void 0 || (_interaction$utils2 = interaction.utils) === null || _interaction$utils2 === void 0 || (_interaction$utils2$p = _interaction$utils2.postMessageToApp) === null || _interaction$utils2$p === void 0 || _interaction$utils2$p.call(_interaction$utils2, {
						module: "till",
						key: "open_till",
						data: { type: "cash" }
					});
				}
				yield checkoutModule === null || checkoutModule === void 0 ? void 0 : checkoutModule.addPaymentItemAsync({
					amount: finalAmount,
					code: method.code,
					id: method.id,
					name: method.name,
					type: method.type,
					voucher_id: 0,
					service_charge
				});
			}
		});
		return function onPaymentOptionClick(_x2) {
			return _ref2.apply(this, arguments);
		};
	}();
	(0, react.useEffect)(() => {
		if (checkoutModule && orderInfo && isModalOpen) try {
			const currentAmount = checkoutModule.getStateAmount();
			if (currentAmount) {
				var _cartData$order_info;
				setCustomAmount(currentAmount);
				setBalanceDueAmount(currentAmount);
				setBalanceDueTotalAmount(orderInfo.totalAmount || "0");
				const currentNote = checkoutModule.getOrderNote();
				if (currentNote) setOrderNote(currentNote);
				else if (cartData === null || cartData === void 0 || (_cartData$order_info = cartData.order_info) === null || _cartData$order_info === void 0 ? void 0 : _cartData$order_info.order_note) setOrderNote(cartData.order_info.order_note);
			}
		} catch (error) {
			console.warn("Failed to get initial custom amount:", error);
		}
		if (checkoutModule && isModalOpen) {
			checkoutModule.getPaymentMethodsAsync().then(function() {
				var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (paymentMethods) {
					setPaymentMethods(yield require_utils$1.reorderPaymentMethodList(paymentMethods, interaction));
					const isShowCashPayment = paymentMethods.some((item) => item.code === "CASHMANUAL");
					setShowCashPayment(isShowCashPayment);
					onShowCashPaymentChange === null || onShowCashPaymentChange === void 0 || onShowCashPaymentChange(isShowCashPayment);
					if (!isShowCashPayment) setPaymentOptionsTitle(_pisell_utils.locales.getText("pisell2.checkout.payment.select-payment") || "Select Payment");
				});
				return function(_x3) {
					return _ref3.apply(this, arguments);
				};
			}());
			checkoutModule.getCurrentOrderPaymentItemsAsync().then((items) => {
				setPaymentItems(items);
			});
		}
	}, [checkoutModule, orderInfo]);
	(0, react.useEffect)(() => {
		if (customAmount && checkoutModule && currency && orderInfo && isModalOpen) try {
			setRecommendAmounts(checkoutModule.payment.cash.getRecommendedAmount(customAmount, currency));
		} catch (error) {
			console.warn("Failed to get recommended amounts:", error);
		}
	}, [
		customAmount,
		checkoutModule,
		currency,
		orderInfo
	]);
	(0, react.useEffect)(() => {
		if (checkoutModule && checkoutModule.core && isModalOpen) try {
			const core = checkoutModule.core;
			if (core.effects && typeof core.effects.on === "function") {
				const unsubscribe = core.effects.on(CheckoutHooks.OnStateAmountChanged, executeIfActive(function() {
					var _ref4 = require_asyncToGenerator._asyncToGenerator(function* (data) {
						console.log(`Amount changed from ${data.oldAmount} to ${data.newAmount}`);
						if (clientChangedRef.current) {
							clientChangedRef.current = false;
							if (data.newAmount !== data.oldAmount) {
								var _Toast$success;
								Toast === null || Toast === void 0 || (_Toast$success = Toast.success) === null || _Toast$success === void 0 || _Toast$success.call(Toast, _pisell_utils.locales.getText("pisell2.checkout.client-card.tip.wallet-updated"));
							} else {
								var _Toast$success2;
								Toast === null || Toast === void 0 || (_Toast$success2 = Toast.success) === null || _Toast$success2 === void 0 || _Toast$success2.call(Toast, _pisell_utils.locales.getText("pisell2.checkout.client-card.tip.client-changed"));
							}
						}
						setCustomAmount(data.newAmount);
						setPaymentItems(yield checkoutModule.getCurrentOrderPaymentItemsAsync());
					});
					return function(_x4) {
						return _ref4.apply(this, arguments);
					};
				}()));
				const amountChangedUnsubscribe = core.effects.on(CheckoutHooks.OnBalanceDueAmountChanged, executeIfActive((data) => {
					setBalanceDueAmount(data.newAmount);
					setBalanceDueTotalAmount(data.totalAmount || "0");
				}));
				const orderSubmitStartUnsubscribe = core.effects.on(CheckoutHooks.OnOrderSubmitStart, executeIfActive(() => {
					var _Toast$loading2;
					setSyncingLock(true);
					Toast === null || Toast === void 0 || (_Toast$loading2 = Toast.loading) === null || _Toast$loading2 === void 0 || _Toast$loading2.call(Toast, "", 0);
				}));
				const orderSubmitEndUnsubscribe = core.effects.on(CheckoutHooks.OnOrderSubmitEnd, executeIfActive((res) => {
					setSyncingLock(false);
					if (res.success) {
						var _Toast$hide;
						Toast === null || Toast === void 0 || (_Toast$hide = Toast.hide) === null || _Toast$hide === void 0 || _Toast$hide.call(Toast);
					} else {
						var _Toast$hide2;
						Toast === null || Toast === void 0 || (_Toast$hide2 = Toast.hide) === null || _Toast$hide2 === void 0 || _Toast$hide2.call(Toast);
						if (onOrderSyncFailed) onOrderSyncFailed();
						else Toast === null || Toast === void 0 || Toast.fail(_pisell_utils.locales.getText("pisell2.checkout.order-sync-failed") || "Order sync failed");
					}
				}));
				const orderPaymentAddedUnsubscribe = core.effects.on(CheckoutHooks.OnOrderPaymentAdded, executeIfActive(function() {
					var _ref5 = require_asyncToGenerator._asyncToGenerator(function* (data) {
						console.log("orderPaymentAddedUnsubscribe>>>>", data);
						const orderInfo = checkoutModule.getCurrentOrderInfo();
						updateOrderInfo === null || updateOrderInfo === void 0 || updateOrderInfo(orderInfo);
						const balanceDueAmount = checkoutModule.getBalanceDueAmount();
						if (Number(balanceDueAmount) > 0) {
							const autoCloseConfig = require_PaymentResultToastUtils.calculateAutoCloseConfig("partially_paid", false);
							const paymentItems = yield checkoutModule.getCurrentOrderPaymentItemsAsync();
							let totalAmount = new decimal_js.default(orderInfo.isDeposit ? orderInfo.depositAmount : orderInfo.totalAmount);
							if (paymentItems.length > 0 && paymentItems.filter((n) => n.isSynced).some((item) => item.service_charge || item.rounding_amount)) {
								const serviceChargeTotal = paymentItems.reduce((acc, item) => {
									var _item$service_charge, _item$service_charge2;
									const chargeAmount = new decimal_js.default(((_item$service_charge = item.service_charge) === null || _item$service_charge === void 0 ? void 0 : _item$service_charge.amount) || 0);
									const chargePercentage = new decimal_js.default(((_item$service_charge2 = item.service_charge) === null || _item$service_charge2 === void 0 ? void 0 : _item$service_charge2.percentage) || 0);
									const itemAmount = new decimal_js.default(item.amount || 0);
									let itemServiceCharge = chargeAmount.add(chargePercentage.mul(itemAmount));
									console.log(itemServiceCharge);
									return acc.add(itemServiceCharge);
								}, new decimal_js.default(0));
								totalAmount = totalAmount.add(serviceChargeTotal);
							}
							console.log(totalAmount, paymentItems);
							if (!(paymentResultDisplayMode !== "modal")) {
								autoCloseConfig.autoClose = false;
								autoCloseConfig.autoCloseDelay = 0;
								autoCloseConfig.maskClosable = false;
							}
							yield require_PaymentResultToastUtils.displayPaymentResultToast({
								paymentStatus: "partially_paid",
								orderTotalAmount: totalAmount.toNumber(),
								gapAmount: balanceDueAmount,
								failureReason: "",
								autoCloseConfig,
								actionButtons: generateActionButtons === null || generateActionButtons === void 0 ? void 0 : generateActionButtons("partially_paid")
							}, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, paymentResultToastConfig), {}, {
								onToastClose: () => {
									require_PaymentResultToastProvider.closePaymentResultToast();
								},
								onCountdownComplete: () => {
									require_PaymentResultToastProvider.closePaymentResultToast();
								}
							}));
						}
						const paymentMethodName = data.paymentMethodName || data.name || "";
						if (data.paymentMethodCode === "CASHMANUAL" || /现金|現金/i.test(paymentMethodName) || /cash/i.test(paymentMethodName)) {
							var _interaction$utils3, _interaction$utils3$p;
							logger === null || logger === void 0 || logger.addLog({
								type: "info",
								title: "open_till",
								metadata: {}
							});
							interaction === null || interaction === void 0 || (_interaction$utils3 = interaction.utils) === null || _interaction$utils3 === void 0 || (_interaction$utils3$p = _interaction$utils3.postMessageToApp) === null || _interaction$utils3$p === void 0 || _interaction$utils3$p.call(_interaction$utils3, {
								module: "till",
								key: "open_till",
								data: { type: "cash" }
							});
						}
					});
					return function(_x5) {
						return _ref5.apply(this, arguments);
					};
				}()));
				return () => {
					if (unsubscribe && typeof unsubscribe === "function") unsubscribe();
					if (orderSubmitStartUnsubscribe && typeof orderSubmitStartUnsubscribe === "function") orderSubmitStartUnsubscribe();
					if (orderSubmitEndUnsubscribe && typeof orderSubmitEndUnsubscribe === "function") orderSubmitEndUnsubscribe();
					if (amountChangedUnsubscribe && typeof amountChangedUnsubscribe === "function") amountChangedUnsubscribe();
					if (orderPaymentAddedUnsubscribe && typeof orderPaymentAddedUnsubscribe === "function") orderPaymentAddedUnsubscribe();
				};
			}
		} catch (error) {
			console.warn("Failed to subscribe to amount change events:", error);
		}
	}, [checkoutModule]);
	const handleAmountChange = (0, react.useCallback)(function() {
		var _ref6 = require_asyncToGenerator._asyncToGenerator(function* (newAmount) {
			if (checkoutModule) try {
				yield checkoutModule.setStateAmountAsync(newAmount);
				setCustomAmount(newAmount);
			} catch (error) {
				console.error("Failed to set custom amount:", error);
			}
		});
		return function(_x6) {
			return _ref6.apply(this, arguments);
		};
	}(), [checkoutModule]);
	const handleDepositStatusChange = (0, react.useCallback)(function() {
		var _ref7 = require_asyncToGenerator._asyncToGenerator(function* (isDeposit) {
			if (checkoutModule) try {
				const depositStatus = isDeposit ? 1 : 0;
				yield checkoutModule.updateOrderDepositStatusAsync(depositStatus);
				console.log(`Deposit status updated to: ${depositStatus} (${isDeposit ? "deposit" : "regular"})`);
			} catch (error) {
				console.error("Failed to update deposit status:", error);
			}
		});
		return function(_x7) {
			return _ref7.apply(this, arguments);
		};
	}(), [checkoutModule]);
	const handleWalletPassConfirmPay = function() {
		var _ref8 = require_asyncToGenerator._asyncToGenerator(function* (action) {
			if (action === "save-without-deduct") yield checkoutModule.updateVoucherPaymentItemsAsync([]);
			else if (action === "cancel") return;
			const result = yield checkoutModule.manualSyncOrderAsync();
			yield showSuccessToast === null || showSuccessToast === void 0 ? void 0 : showSuccessToast(result);
			if (result.success) {
				var _result$response;
				checkoutModule.core.effects.emit("checkout:onPaymentStarted", { paymentMethodCode: "" });
				const orderInfo = checkoutModule.getCurrentOrderInfo();
				setCurrentEditOrderId === null || setCurrentEditOrderId === void 0 || setCurrentEditOrderId(result.orderId);
				if (result.is_deposit && Number(orderInfo.depositAmount) < Number(orderInfo.totalAmount)) {
					updateOrderInfo === null || updateOrderInfo === void 0 || updateOrderInfo(orderInfo);
					return;
				}
				const responseData = (_result$response = result.response) === null || _result$response === void 0 ? void 0 : _result$response.data;
				console.log("print_order_onOrderSynced>>>>", result);
				try {
					var _responseData$payment;
					const params = {
						type: "99",
						data: {
							order_id: responseData.order_id,
							machine_code_print_info: responseData === null || responseData === void 0 ? void 0 : responseData.machine_code_print_info,
							small_ticket_data: responseData === null || responseData === void 0 || (_responseData$payment = responseData.payment_info) === null || _responseData$payment === void 0 ? void 0 : _responseData$payment.small_ticket_data,
							machine_code_print_info_v2: responseData === null || responseData === void 0 ? void 0 : responseData.machine_code_print_info_v2
						}
					};
					console.log("print_order_onOrderSynced_params>>>>", params);
					nativePrint(params, (res) => {
						console.log("print_order_onOrderSynced_res>>>>", res);
					});
				} catch (error) {
					console.error("print_order_onOrderSynced_error>>>>", error);
				}
				onPaymentCancel(true);
			}
		});
		return function handleWalletPassConfirmPay(_x8) {
			return _ref8.apply(this, arguments);
		};
	}();
	const handleSavePayLater = (0, react.useCallback)(function() {
		var _ref9 = require_asyncToGenerator._asyncToGenerator(function* (action) {
			if (action === "apply-deduct-now") console.log("立即应用并扣除钱包余额，然后保存稍后付款");
			else if (action === "save-without-deduct") {
				console.log("保存但不扣除钱包余额，稍后付款");
				yield checkoutModule.updateVoucherPaymentItemsAsync([]);
			} else if (action === "cancel") {
				console.log("取消保存稍后付款");
				return;
			}
			if (checkoutModule) {
				if ((yield checkoutModule.saveForLaterPaymentAsync()).success) onPaymentCancel(true);
			}
		});
		return function(_x9) {
			return _ref9.apply(this, arguments);
		};
	}(), [checkoutModule, onPaymentCancel]);
	const moduleConfig = {
		showWalletPass: walletPassDetail.isShow,
		showCashPayment: (_parentModuleConfig$s = parentModuleConfig === null || parentModuleConfig === void 0 ? void 0 : parentModuleConfig.showCashPayment) !== null && _parentModuleConfig$s !== void 0 ? _parentModuleConfig$s : true,
		showAdditionalModule: true,
		showPaymentOptions: true
	};
	const handleSearch = (0, react.useCallback)((keyword) => {
		if (walletPassRef.current) return walletPassRef.current.handleSearchIdentificationCode(keyword);
	}, []);
	const currentTotalPriceAfterDiscount = (0, react.useMemo)(() => {
		return new decimal_js.default(currentTotalPrice || 0).minus(shopDiscount || 0).toNumber();
	}, [shopDiscount, currentTotalPrice]);
	const handleSelectWalletChange = (0, ahooks.useMemoizedFn)(function() {
		var _ref10 = require_asyncToGenerator._asyncToGenerator(function* (select) {
			if (walletPassDetail.isShow) {
				const voucherItems = [];
				select.forEach((item) => {
					const mapCode = item.code ? require_constants.WALLET_PASS_CODE_MAP[item.code] : null;
					if (mapCode && walletPassDetail.map[mapCode]) {
						var _walletPassDetail$map, _walletPassDetail$map2, _walletPassDetail$map3, _walletPassDetail$map4;
						voucherItems.push({
							amount: item.amount,
							code: (_walletPassDetail$map = walletPassDetail.map[mapCode]) === null || _walletPassDetail$map === void 0 ? void 0 : _walletPassDetail$map.code,
							id: Number((_walletPassDetail$map2 = walletPassDetail.map[mapCode]) === null || _walletPassDetail$map2 === void 0 ? void 0 : _walletPassDetail$map2.id) || 0,
							name: (_walletPassDetail$map3 = walletPassDetail.map[mapCode]) === null || _walletPassDetail$map3 === void 0 ? void 0 : _walletPassDetail$map3.name,
							type: (_walletPassDetail$map4 = walletPassDetail.map[mapCode]) === null || _walletPassDetail$map4 === void 0 ? void 0 : _walletPassDetail$map4.type,
							voucher_id: item.voucher_id,
							wallet_pass_usage_unit: item.wallet_pass_usage_unit,
							wallet_pass_use_value: convertCurrencyAmountToWalletPassValue({
								currencyAmount: item.amount,
								walletPassUsageUnit: item.wallet_pass_usage_unit
							})
						});
					}
				});
				logger === null || logger === void 0 || logger.addLog({
					type: "info",
					title: "handleSelectWalletChange checkoutModule updateVoucherPaymentItemsAsync",
					metadata: {}
				});
				yield checkoutModule.updateVoucherPaymentItemsAsync(voucherItems);
				if (walletPassRef.current) setWalletPassData(walletPassRef.current.getWalletPassData(select));
			}
		});
		return function(_x10) {
			return _ref10.apply(this, arguments);
		};
	}());
	const handlePriceAdjustConfirm = function() {
		var _ref11 = require_asyncToGenerator._asyncToGenerator(function* (discountAmount) {
			try {
				if (checkoutModule && (orderInfo === null || orderInfo === void 0 ? void 0 : orderInfo.totalAmount)) onChangeShopDiscount === null || onChangeShopDiscount === void 0 || onChangeShopDiscount(discountAmount);
			} catch (error) {
				console.error("Failed to adjust price:", error);
			}
			setShowPriceAdjustModal(false);
		});
		return function handlePriceAdjustConfirm(_x11) {
			return _ref11.apply(this, arguments);
		};
	}();
	const handleButtonClick = function() {
		var _ref12 = require_asyncToGenerator._asyncToGenerator(function* (key) {
			console.log("handleButtonClick", key);
			switch (key) {
				case "order-note":
					setNoteModalOpen(true);
					break;
				case "send-link":
					setPaymentLinkModalOpen(true);
					break;
				case "split-payment":
					setShowSplitPaymentKeyboard(true);
					break;
				case "print-receipt":
					let data;
					if (!(yield checkoutModule.isCurrentOrderSynced())) data = yield checkoutModule.manualSyncOrderAsync();
					else data = { orderId: yield checkoutModule.getCurrentOrderId() };
					console.log("handleButtonClick_print-receipt_data>>>>", data);
					if (data.orderId) {
						const params = {
							type: "0",
							data: { order_id: data.orderId }
						};
						try {
							nativePrint(params, (res) => {
								console.log("handleButtonClick_print-receipt_res>>>>", res);
								if (!(res === null || res === void 0 ? void 0 : res.result)) Toast === null || Toast === void 0 || Toast.error((res === null || res === void 0 ? void 0 : res.msg) || "");
							});
						} catch (error) {
							console.error("handleButtonClick_print-receipt_error>>>>", error);
						}
					}
					break;
				case "manual-discount":
					if (!(orderInfo === null || orderInfo === void 0 ? void 0 : orderInfo.totalAmount)) {
						Toast === null || Toast === void 0 || Toast.fail(_pisell_utils.locales.getText("pisell2.checkout.manual-discount.no-amount"));
						return;
					}
					const paymentItems = yield checkoutModule.getCurrentOrderPaymentItemsAsync();
					if (paymentItems === null || paymentItems === void 0 ? void 0 : paymentItems.length) {
						Toast === null || Toast === void 0 || Toast.fail(_pisell_utils.locales.getText("pisell2.checkout.manual-discount.has-payment-items"));
						return;
					}
					if (Number(customAmount) <= 0 && Number(orderInfo === null || orderInfo === void 0 ? void 0 : orderInfo.totalAmount) >= 0) {
						Toast === null || Toast === void 0 || Toast.fail(_pisell_utils.locales.getText("pisell2.checkout.manual-discount.no-amount"));
						return;
					}
					setShowPriceAdjustModal(true);
					break;
				case "save-pay-later":
					var _savePayLaterHandlerR;
					(_savePayLaterHandlerR = savePayLaterHandlerRef.current) === null || _savePayLaterHandlerR === void 0 || _savePayLaterHandlerR.handleSavePayLaterClick();
					break;
			}
		});
		return function handleButtonClick(_x12) {
			return _ref12.apply(this, arguments);
		};
	}();
	(0, react.useImperativeHandle)(ref, () => ({ handleButtonClick }));
	const getCustomerInfo = () => {
		var _client$contacts;
		const getValidName = (value) => {
			return value !== void 0 && value !== null && String(value).trim() !== "" ? String(value).trim() : null;
		};
		const displayName = getValidName(client === null || client === void 0 ? void 0 : client.display_name) || getValidName(client === null || client === void 0 ? void 0 : client.name) || _pisell_utils.locales.getText("pisell2.checkout.customer.default-name") || "Customer";
		console.log("🔍 PaymentModal final displayName:", displayName);
		return {
			id: client === null || client === void 0 ? void 0 : client.id,
			nickname: (client === null || client === void 0 ? void 0 : client.nickname) || _pisell_utils.locales.getText("pisell2.checkout.customer.default-name"),
			display_name: displayName,
			email: (client === null || client === void 0 ? void 0 : client.email) || (client === null || client === void 0 || (_client$contacts = client.contacts) === null || _client$contacts === void 0 ? void 0 : _client$contacts.email) || ""
		};
	};
	const handleSendCustomerPaymentLink = function() {
		var _ref13 = require_asyncToGenerator._asyncToGenerator(function* (data) {
			if (checkoutModule.getCurrentOrderInfo().isDeposit) {
				const stateAmount = checkoutModule.getStateAmount();
				yield checkoutModule.setDepositAmountAsync(stateAmount);
			}
			if (!checkoutModule.isCurrentOrderSynced()) yield checkoutModule.manualSyncOrderAsync();
			const res = yield checkoutModule.sendCustomerPayLinkAsync({
				emails: data.emails,
				order_ids: [checkoutModule.getCurrentOrderId()]
			});
			if (res.success) {
				Toast === null || Toast === void 0 || Toast.success(_pisell_utils.locales.getText("pisell2.checkout.send-payment-link.success"));
				onPaymentCancel === null || onPaymentCancel === void 0 || onPaymentCancel(true);
			} else Toast === null || Toast === void 0 || Toast.error(res.message || _pisell_utils.locales.getText("pisell2.checkout.send-payment-link.error"));
		});
		return function handleSendCustomerPaymentLink(_x13) {
			return _ref13.apply(this, arguments);
		};
	}();
	const searchAndClientProps = (0, react.useMemo)(() => {
		if ((paymentItems === null || paymentItems === void 0 ? void 0 : paymentItems.length) > 0) return { disabledSwitch: true };
		return {};
	}, [paymentItems]);
	const roundingFunction = function() {
		var _ref14 = require_asyncToGenerator._asyncToGenerator(function* (amount) {
			return yield checkoutModule.roundAmountAsync(amount);
		});
		return function roundingFunction(_x14) {
			return _ref14.apply(this, arguments);
		};
	}();
	const handleModalClick = (0, react.useCallback)((event) => {
		if (paymentResultDisplayMode !== "modal") require_utils.closeAllPaymentResultToasts();
	}, []);
	return /* @__PURE__ */ react.default.createElement("div", require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({ ref: checkoutRef }, { onClick: handleModalClick }), {}, { style: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, require_styles.checkoutStyles.container), {}, { maxHeight: dynamicMaxHeight }) }), /* @__PURE__ */ react.default.createElement("div", { style: {
		padding: "12px 16px",
		border: "1px solid #d0d5dd",
		borderRadius: 8
	} }, /* @__PURE__ */ react.default.createElement(require_index$11.default, require_objectSpread2._objectSpread2({
		onClientChange: () => {
			clientChangedRef.current = true;
		},
		onSearch: handleSearch
	}, searchAndClientProps)), moduleConfig.showWalletPass && /* @__PURE__ */ react.default.createElement(require_index$6.default, {
		clientId: client === null || client === void 0 ? void 0 : client.id,
		customAmount: balanceDueAmount,
		orderInfo: orderInfo || void 0,
		ref: walletPassRef,
		paymentItems,
		onSelectChange: handleSelectWalletChange
	})), /* @__PURE__ */ react.default.createElement(require_index$4.default, {
		amountSymbol: getData("shop_symbol"),
		orderInfo: orderInfo || void 0,
		cartData,
		open_deposit,
		customAmount,
		balanceDueAmount,
		paymentItems,
		walletPassData,
		clientInfo: client,
		onAmountChange: handleAmountChange,
		onDepositStatusChange: handleDepositStatusChange,
		onBalanceDueAmountClick: handleButtonClick,
		onConfirm: handleWalletPassConfirmPay,
		totalAmount
	}), /* @__PURE__ */ react.default.createElement("div", { className: showCashPayment ? "payment-grid-layout" : "payment-flex-layout" }, showCashPayment && /* @__PURE__ */ react.default.createElement("div", { style: showCashPayment ? {
		gridColumn: "1",
		gridRow: (paymentOptionList === null || paymentOptionList === void 0 ? void 0 : paymentOptionList.length) === 1 ? "span 2" : "1"
	} : {} }, /* @__PURE__ */ react.default.createElement(require_index$8.default, {
		disabled: isOrderFree,
		isModalOpen,
		syncingLock,
		amountSymbol: getData("shop_symbol"),
		orderInfo: orderInfo || void 0,
		onPaymentComplete: handleAddCashPayment,
		amountButtons: recommendAmounts,
		customAmount,
		roundingFunction,
		balanceDueAmount,
		balanceDueTotalAmount,
		shortcutsSize: (paymentOptionList === null || paymentOptionList === void 0 ? void 0 : paymentOptionList.length) === 3 || (paymentOptionList === null || paymentOptionList === void 0 ? void 0 : paymentOptionList.length) === 1 ? "large" : "default"
	})), moduleConfig.showPaymentOptions && (paymentOptionList === null || paymentOptionList === void 0 ? void 0 : paymentOptionList.length) > 0 && /* @__PURE__ */ react.default.createElement("div", {
		className: showCashPayment ? "" : "payment-options-module-container",
		style: showCashPayment ? {
			gridColumn: "2",
			gridRow: (paymentOptionList === null || paymentOptionList === void 0 ? void 0 : paymentOptionList.length) > 3 ? "1 / 3" : "1"
		} : {}
	}, /* @__PURE__ */ react.default.createElement(require_index$7.default, {
		amountSymbol: getData("shop_symbol"),
		orderInfo: orderInfo || void 0,
		onClick: onPaymentOptionClick,
		paymentMethods,
		customAmount,
		title: paymentOptionsTitle,
		disabled: isOrderFree,
		showCashPayment
	})), moduleConfig.showAdditionalModule && /* @__PURE__ */ react.default.createElement("div", {
		className: showCashPayment ? "" : "additional-module-container",
		style: showCashPayment ? {
			gridColumn: (paymentOptionList === null || paymentOptionList === void 0 ? void 0 : paymentOptionList.length) > 3 ? "1" : (paymentOptionList === null || paymentOptionList === void 0 ? void 0 : paymentOptionList.length) <= 1 ? "2" : "span 2",
			gridRow: (paymentOptionList === null || paymentOptionList === void 0 ? void 0 : paymentOptionList.length) === 0 ? "1" : "2"
		} : {}
	}, /* @__PURE__ */ react.default.createElement(require_index$9.default, {
		orderInfo: orderInfo || void 0,
		customAmount,
		handleButtonClick,
		hasOrderNote: !!orderNote && orderNote.trim().length > 0,
		disabled: isOrderFree,
		showCashPayment,
		isFullWidth: !((paymentOptionList === null || paymentOptionList === void 0 ? void 0 : paymentOptionList.length) > 3 || (paymentOptionList === null || paymentOptionList === void 0 ? void 0 : paymentOptionList.length) <= 1),
		showMore: !(showCashPayment && (paymentOptionList === null || paymentOptionList === void 0 ? void 0 : paymentOptionList.length) === 0)
	}))), /* @__PURE__ */ react.default.createElement(require_index$10.default, {
		ref: paymentMethodsRef,
		dynamicMaxHeight,
		isWebPos: true
	}), paymentLinkModalOpen && /* @__PURE__ */ react.default.createElement(require_index$3.default, {
		balanceAmount: customAmount,
		customerEmail: getCustomerInfo().email,
		customerName: getCustomerInfo().display_name || getCustomerInfo().nickname,
		customerId: getCustomerInfo().id,
		onClose: () => setPaymentLinkModalOpen(false),
		sendPaymentLink: handleSendCustomerPaymentLink
	}), /* @__PURE__ */ react.default.createElement(require_index$2.default, {
		containerProps: {
			renderType: "modal",
			open: showPriceAdjustModal,
			onCancel: () => setShowPriceAdjustModal(false)
		},
		tips: _pisell_utils.locales.getText("pisell2.checkout.modal.price-adjustment-tips") || "Changing amount will update order total",
		selectType: "dark",
		originalValue: currentTotalPrice,
		defaultValue: currentTotalPriceAfterDiscount,
		resetText: _pisell_utils.locales.getText("pisell2.checkout.modal.reset-price-adjustment"),
		onEnter: handlePriceAdjustConfirm
	}), /* @__PURE__ */ react.default.createElement(require_index$5.default, {
		ref: savePayLaterHandlerRef,
		amountSymbol: getData("shop_symbol"),
		walletPassData,
		onSavePayLater: handleSavePayLater
	}), /* @__PURE__ */ react.default.createElement(require_index$1.default, {
		containerProps: {
			renderType: "modal",
			open: showSplitPaymentKeyboard,
			onCancel: () => setShowSplitPaymentKeyboard(false)
		},
		paymentOriginalValue: balanceDueAmount,
		paymentDefaultValue: String(customAmount || 0),
		enableExceedMaxAmount: false,
		payment: { enable: true },
		surcharge: { enable: false },
		surchargeDefaultValue: {
			percent: "0",
			fixed: "0"
		},
		selectType: "light",
		onChange: (value) => {
			console.log(value);
		},
		doneText: _pisell_utils.locales.getText("confirm") || "确认",
		onPay: (args) => {
			console.log(args);
			setShowSplitPaymentKeyboard(false);
			handleAmountChange(String(args.amount));
		}
	}));
});
const PaymentModal = ({ open, data, callback, onClose, setEditCartMode, editOrderId, paymentResultDisplayMode, shopDiscount, client, currentTotalPrice, onChangeShopDiscount, onChangeOrderNote, onDeleteOrderNote }) => {
	var _context$appHelper$ut, _context$appHelper$ut2, _context$appHelper$ut3, _context$appHelper$ut4, _context$appHelper;
	const context = require_useEngineContext.default();
	_pisell_utils.locales.init(require_locales$1.default, ((_context$appHelper$ut = context.appHelper.utils) === null || _context$appHelper$ut === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut.getApp) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut2.call(_context$appHelper$ut)) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut2.locales) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut3 = _context$appHelper$ut2.getLocale) === null || _context$appHelper$ut3 === void 0 ? void 0 : _context$appHelper$ut3.call(_context$appHelper$ut2)) || ((_context$appHelper$ut4 = context.appHelper.utils) === null || _context$appHelper$ut4 === void 0 || (_context$appHelper$ut4 = _context$appHelper$ut4.storage) === null || _context$appHelper$ut4 === void 0 ? void 0 : _context$appHelper$ut4.get("umi_locale")) || "en");
	const { pisellos, getData, interaction, isWebPos } = (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const [orderInfo, setOrderInfo] = (0, react.useState)(null);
	const [totalAmount, setTotalAmount] = (0, react.useState)(0);
	const [actualShowCashPayment, setActualShowCashPayment] = (0, react.useState)(true);
	const [windowHeight, setWindowHeight] = (0, react.useState)(0);
	const [showRetryModal, setShowRetryModal] = (0, react.useState)(false);
	const [showCreateErrorModal, setShowCreateErrorModal] = (0, react.useState)(false);
	const [currentEditOrderId, setCurrentEditOrderId] = (0, react.useState)(editOrderId || 0);
	const { executeIfActive } = require_useActiveExecute.useActiveExecute();
	const Toast = (0, _pisell_materials.useToast)();
	const { nativePrint } = require_printer.default();
	const handleRetry = function() {
		var _ref15 = require_asyncToGenerator._asyncToGenerator(function* () {
			const checkoutModule = pisellos === null || pisellos === void 0 ? void 0 : pisellos.getModule("checkout");
			const res = yield checkoutModule === null || checkoutModule === void 0 ? void 0 : checkoutModule.manualSyncOrderAsync();
			console.log(res);
			if (res.success) {
				setShowRetryModal(false);
				yield showSuccessToast === null || showSuccessToast === void 0 ? void 0 : showSuccessToast(res);
			}
		});
		return function handleRetry() {
			return _ref15.apply(this, arguments);
		};
	}();
	(0, react.useEffect)(() => {
		const updateHeight = () => {
			if (typeof window !== "undefined") setWindowHeight(window.innerHeight);
		};
		updateHeight();
		window.addEventListener("resize", updateHeight);
		window.addEventListener("orientationchange", updateHeight);
		return () => {
			window.removeEventListener("resize", updateHeight);
			window.removeEventListener("orientationchange", updateHeight);
		};
	}, []);
	(0, react.useEffect)(() => {
		var _interaction$utils5;
		const initTillButtonData = function() {
			var _ref16 = require_asyncToGenerator._asyncToGenerator(function* () {
				console.log("准备获取tillButton数据");
				try {
					var _interaction$utils4, _interaction$utils4$a;
					const tillButtonData = yield interaction === null || interaction === void 0 || (_interaction$utils4 = interaction.utils) === null || _interaction$utils4 === void 0 || (_interaction$utils4$a = _interaction$utils4.asyncDataManager) === null || _interaction$utils4$a === void 0 ? void 0 : _interaction$utils4$a.call(_interaction$utils4, {
						module: "get",
						key: "till_button"
					});
					console.log("获取tillButton数据成功", tillButtonData);
					if (tillButtonData) {
						require_PaymentResultToastProvider.setTillButton(tillButtonData);
						console.log("PaymentModal: tillButton data set successfully", tillButtonData);
					}
				} catch (error) {
					console.error("PaymentModal: Failed to get till_button from asyncDataManager:", error);
				}
			});
			return function initTillButtonData() {
				return _ref16.apply(this, arguments);
			};
		}();
		if (interaction === null || interaction === void 0 || (_interaction$utils5 = interaction.utils) === null || _interaction$utils5 === void 0 ? void 0 : _interaction$utils5.asyncDataManager) initTillButtonData();
	}, [interaction]);
	const dynamicMaxHeight = (0, react.useMemo)(() => {
		if (windowHeight === 0) return "600px";
		const bodyTransform = getComputedStyle(document.body).transform;
		let scaleY = 1;
		if (bodyTransform !== "none") scaleY = new DOMMatrix(bodyTransform).d;
		return `${Math.floor(windowHeight * .9 / scaleY)}px`;
	}, [windowHeight]);
	const moduleConfig = { showCashPayment: true };
	const handleShowCashPaymentChange = (0, react.useCallback)((show) => {
		setActualShowCashPayment(show);
	}, []);
	const [noteModalOpen, setNoteModalOpen] = (0, react.useState)(false);
	const [orderNote, setOrderNote] = (0, react.useState)("");
	const [noteModalSource, setNoteModalSource] = (0, react.useState)("payment-content");
	const handleNoteConfirm = function() {
		var _ref17 = require_asyncToGenerator._asyncToGenerator(function* (noteValue) {
			if (noteModalSource === "payment-result-toast") {
				const checkoutModule = pisellos === null || pisellos === void 0 ? void 0 : pisellos.getModule("checkout");
				const orderId = checkoutModule === null || checkoutModule === void 0 ? void 0 : checkoutModule.getCurrentOrderId();
				if (checkoutModule) {
					var _checkoutModule$editO;
					(_checkoutModule$editO = checkoutModule.editOrderNoteByOrderIdAsync) === null || _checkoutModule$editO === void 0 || _checkoutModule$editO.call(checkoutModule, orderId, noteValue);
					setOrderNote(noteValue);
					Toast === null || Toast === void 0 || Toast.success(_pisell_utils.locales.getText("pisell2.checkout.order-note.updated-successfully"));
				}
				setNoteModalOpen(false);
				return;
			}
			try {
				const checkoutModule = pisellos === null || pisellos === void 0 ? void 0 : pisellos.getModule("checkout");
				if (checkoutModule) {
					var _checkoutModule$updat;
					yield (_checkoutModule$updat = checkoutModule.updateOrderNoteAsync) === null || _checkoutModule$updat === void 0 ? void 0 : _checkoutModule$updat.call(checkoutModule, noteValue);
					setOrderNote(noteValue);
					Toast === null || Toast === void 0 || Toast.success(_pisell_utils.locales.getText("pisell2.checkout.order-note.updated-successfully"));
				}
				onChangeOrderNote === null || onChangeOrderNote === void 0 || onChangeOrderNote(noteValue);
				if (noteModalSource === "payment-result-toast") console.log("Note added from payment result toast");
				else if (noteModalSource === "payment-content") console.log("Note added from payment content");
			} catch (error) {
				console.error("Failed to update order note:", error);
				Toast === null || Toast === void 0 || Toast.error(_pisell_utils.locales.getText("pisell2.checkout.order-note.update-failed"));
			}
			setNoteModalOpen(false);
		});
		return function handleNoteConfirm(_x15) {
			return _ref17.apply(this, arguments);
		};
	}();
	const handleNoteDelete = function() {
		var _ref18 = require_asyncToGenerator._asyncToGenerator(function* () {
			try {
				const checkoutModule = pisellos === null || pisellos === void 0 ? void 0 : pisellos.getModule("checkout");
				if (checkoutModule) {
					var _checkoutModule$updat2;
					yield (_checkoutModule$updat2 = checkoutModule.updateOrderNoteAsync) === null || _checkoutModule$updat2 === void 0 ? void 0 : _checkoutModule$updat2.call(checkoutModule, "");
					setOrderNote("");
					Toast === null || Toast === void 0 || Toast.success(_pisell_utils.locales.getText("pisell2.checkout.order-note.deleted-successfully"));
				}
				onDeleteOrderNote === null || onDeleteOrderNote === void 0 || onDeleteOrderNote();
			} catch (error) {
				console.error("Failed to delete order note:", error);
				Toast === null || Toast === void 0 || Toast.error(_pisell_utils.locales.getText("pisell2.checkout.order-note.delete-failed"));
			}
			setNoteModalOpen(false);
		});
		return function handleNoteDelete() {
			return _ref18.apply(this, arguments);
		};
	}();
	const handleNoteCancel = () => {
		setNoteModalOpen(false);
	};
	const showingCashToastRef = (0, react.useRef)(false);
	const currentPaymentResultRef = react.default.useRef(null);
	const paymentContentRef = react.default.useRef(null);
	const handleOrderNoteClickFromToast = () => {
		var _context$appHelper$ut5, _context$appHelper$ut6, _context$appHelper$ut7, _context$appHelper$ut8;
		const modalContainer = document.createElement("div");
		document.body.appendChild(modalContainer);
		const showToast = (type, message) => {
			if (Toast && Toast[type]) Toast[type](message);
			else if (type === "success") console.log("✅ Success:", message);
			else console.error("❌ Error:", message);
		};
		const handleNoteConfirm = function() {
			var _ref19 = require_asyncToGenerator._asyncToGenerator(function* (noteValue) {
				try {
					const checkoutModule = pisellos === null || pisellos === void 0 ? void 0 : pisellos.getModule("checkout");
					const orderId = checkoutModule === null || checkoutModule === void 0 ? void 0 : checkoutModule.getCurrentOrderId();
					if (checkoutModule && orderId) {
						var _checkoutModule$editO2;
						yield (_checkoutModule$editO2 = checkoutModule.editOrderNoteByOrderIdAsync) === null || _checkoutModule$editO2 === void 0 ? void 0 : _checkoutModule$editO2.call(checkoutModule, orderId, noteValue);
						setOrderNote(noteValue);
						showToast("success", _pisell_utils.locales.getText("pisell2.checkout.order-note.updated-successfully"));
					}
				} catch (error) {
					console.error("Failed to update order note:", error);
					showToast("error", _pisell_utils.locales.getText("pisell2.checkout.order-note.update-failed"));
				}
				react_dom.default.unmountComponentAtNode(modalContainer);
				if (document.body.contains(modalContainer)) document.body.removeChild(modalContainer);
			});
			return function handleNoteConfirm(_x16) {
				return _ref19.apply(this, arguments);
			};
		}();
		const handleNoteDelete = function() {
			var _ref20 = require_asyncToGenerator._asyncToGenerator(function* () {
				try {
					const checkoutModule = pisellos === null || pisellos === void 0 ? void 0 : pisellos.getModule("checkout");
					const orderId = checkoutModule === null || checkoutModule === void 0 ? void 0 : checkoutModule.getCurrentOrderId();
					if (checkoutModule && orderId) {
						var _checkoutModule$editO3;
						yield (_checkoutModule$editO3 = checkoutModule.editOrderNoteByOrderIdAsync) === null || _checkoutModule$editO3 === void 0 ? void 0 : _checkoutModule$editO3.call(checkoutModule, orderId, "");
						setOrderNote("");
						showToast("success", _pisell_utils.locales.getText("pisell2.checkout.order-note.deleted-successfully"));
					}
				} catch (error) {
					console.error("Failed to delete order note:", error);
					showToast("error", _pisell_utils.locales.getText("pisell2.checkout.order-note.delete-failed"));
				}
				react_dom.default.unmountComponentAtNode(modalContainer);
				if (document.body.contains(modalContainer)) document.body.removeChild(modalContainer);
			});
			return function handleNoteDelete() {
				return _ref20.apply(this, arguments);
			};
		}();
		const handleNoteCancel = () => {
			react_dom.default.unmountComponentAtNode(modalContainer);
			if (document.body.contains(modalContainer)) document.body.removeChild(modalContainer);
		};
		const currentLocale = ((_context$appHelper$ut5 = context.appHelper.utils) === null || _context$appHelper$ut5 === void 0 || (_context$appHelper$ut6 = _context$appHelper$ut5.getApp) === null || _context$appHelper$ut6 === void 0 || (_context$appHelper$ut6 = _context$appHelper$ut6.call(_context$appHelper$ut5)) === null || _context$appHelper$ut6 === void 0 || (_context$appHelper$ut6 = _context$appHelper$ut6.locales) === null || _context$appHelper$ut6 === void 0 || (_context$appHelper$ut7 = _context$appHelper$ut6.getLocale) === null || _context$appHelper$ut7 === void 0 ? void 0 : _context$appHelper$ut7.call(_context$appHelper$ut6)) || ((_context$appHelper$ut8 = context.appHelper.utils) === null || _context$appHelper$ut8 === void 0 || (_context$appHelper$ut8 = _context$appHelper$ut8.storage) === null || _context$appHelper$ut8 === void 0 ? void 0 : _context$appHelper$ut8.get("umi_locale")) || "en";
		const EngineContextProvider = ({ children }) => {
			var _context$engine;
			const tempEngineContext = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, context), {}, { engine: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, context.engine), {}, { props: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, (_context$engine = context.engine) === null || _context$engine === void 0 ? void 0 : _context$engine.props), {}, { locale: currentLocale }) }) });
			const TempContext = react.default.createContext(tempEngineContext);
			const originalContext = window.__injectedContext;
			window.__injectedContext = tempEngineContext;
			react.default.useEffect(() => {
				return () => {
					window.__injectedContext = originalContext;
				};
			}, []);
			return /* @__PURE__ */ react.default.createElement(TempContext.Provider, { value: tempEngineContext }, children);
		};
		let orderNote = "";
		try {
			orderNote = (pisellos === null || pisellos === void 0 ? void 0 : pisellos.getModule("checkout")).getOrderNote();
		} catch (error) {
			console.warn("Failed to get initial custom amount:", error);
		}
		react_dom.default.render(/* @__PURE__ */ react.default.createElement(EngineContextProvider, null, /* @__PURE__ */ react.default.createElement(_pisell_materials.ConfigProvider, {
			prefixCls: "pisell-lowcode",
			theme: { token: { colorPrimary: "#7F56DA" } }
		}, /* @__PURE__ */ react.default.createElement(require_index.default, {
			open: true,
			title: _pisell_utils.locales.getText("pisell2.text.add-order-notes"),
			value: orderNote,
			onConfirm: handleNoteConfirm,
			onDelete: handleNoteDelete,
			onCancel: handleNoteCancel
		}))), modalContainer);
	};
	const translation = (key, fallback) => {
		const umiLocale = require_locales.getLocale();
		const currentLang = _pisell_utils.locales.formatLocale(umiLocale);
		try {
			const langPack = require_locales$1.default[currentLang];
			const checkoutText = langPack === null || langPack === void 0 ? void 0 : langPack[key];
			if (checkoutText) return checkoutText;
		} catch (error) {
			console.error("本地语言包访问错误:", error);
		}
		const globalResult = _pisell_utils.locales.getText(key) || fallback;
		console.log("全局语言包结果:", globalResult);
		return globalResult;
	};
	const handlePaymentComplete = (result) => {
		currentPaymentResultRef.current = result;
	};
	const handleToastClose = () => {
		console.log("PaymentModal - Toast closed, executing payment completion callback");
		if (currentPaymentResultRef.current) callback === null || callback === void 0 || callback(currentPaymentResultRef.current);
	};
	const handleModalClose = () => {
		console.log("PaymentModal - Modal closing independently");
		onClose === null || onClose === void 0 || onClose(true);
	};
	const handlePaymentCancel = (reset) => {
		console.log("Payment cancelled");
		callback === null || callback === void 0 || callback({ status: "cancelled" });
		pisellos.getModule("checkout").cancelCurrentOrderAsync();
		onClose === null || onClose === void 0 || onClose(reset || false);
	};
	const handleSetEditCartMode = function() {
		var _ref21 = require_asyncToGenerator._asyncToGenerator(function* (closeModal = false) {
			const checkout = pisellos.getModule("checkout");
			const orderId = checkout.getCurrentOrderId();
			const paymentData = yield checkout.getCurrentOrderPaymentItemsAsync();
			const paidAmount = paymentData.reduce((total, item) => {
				return total + Number(item.amount);
			}, 0);
			const paidAmountWithoutSurcharge = paymentData.reduce((total, item) => {
				var _item$service_charge3;
				return total + Number(item.amount) - Number(((_item$service_charge3 = item.service_charge) === null || _item$service_charge3 === void 0 ? void 0 : _item$service_charge3.amount) || 0);
			}, 0);
			console.log("paidAmount>>>>", paidAmount, paidAmountWithoutSurcharge);
			checkout.updateVoucherPaymentItemsAsync([]);
			setEditCartMode === null || setEditCartMode === void 0 || setEditCartMode(orderId, {
				paidAmount,
				paidAmountWithoutSurcharge
			}, closeModal);
		});
		return function handleSetEditCartMode() {
			return _ref21.apply(this, arguments);
		};
	}();
	const CustomHeader = () => /* @__PURE__ */ react.default.createElement("div", { className: "payment-modal-custom-header" }, /* @__PURE__ */ react.default.createElement("div", { className: "header__left" }, /* @__PURE__ */ react.default.createElement(antd.Button, {
		icon: /* @__PURE__ */ react.default.createElement(_pisell_materials.Icon, {
			type: "pisell2-arrow-left",
			size: 24
		}),
		size: "small",
		type: "text",
		onClick: () => {
			var _checkout$getCurrentO;
			const checkout = pisellos.getModule("checkout");
			console.log("checkout.getCurrentOrderInfo()>>>>", checkout.getCurrentOrderInfo());
			if (checkout.isCurrentOrderSynced() && ((_checkout$getCurrentO = checkout.getCurrentOrderInfo()) === null || _checkout$getCurrentO === void 0 ? void 0 : _checkout$getCurrentO.paymentStatus) !== "unpaid") handleSetEditCartMode(true);
			else handlePaymentCancel(false);
		}
	})), /* @__PURE__ */ react.default.createElement("div", { className: "header__center" }, translation("order.total"), "：", require_PaymentResultToastUtils.formatCurrency(totalAmount, getData("shop_symbol"))), /* @__PURE__ */ react.default.createElement("div", { className: "header__right" }, /* @__PURE__ */ react.default.createElement(antd.Button, {
		size: "small",
		type: "link",
		onClick: () => handlePaymentCancel(true)
	}, _pisell_utils.locales.getText("order.start-new-order"))));
	(0, react.useEffect)(() => {
		var _data$order_info;
		if (data === null || data === void 0 || (_data$order_info = data.order_info) === null || _data$order_info === void 0 ? void 0 : _data$order_info.order_note) setOrderNote(data.order_info.order_note);
	}, [data]);
	const logger = require_usePaymentLogger.default();
	const isLocalOrderCreated = (0, react.useRef)(void 0);
	const unsubscribeRef = (0, react.useRef)(void 0);
	(0, react.useEffect)(() => {
		const initCheckoutData = function() {
			var _ref23 = require_asyncToGenerator._asyncToGenerator(function* () {
				try {
					const checkout = pisellos === null || pisellos === void 0 ? void 0 : pisellos.getModule("checkout");
					if (checkout && data && !isLocalOrderCreated.current) {
						var _getData;
						isLocalOrderCreated.current = true;
						const shop_wallet_pass_id = yield require_utils$1.getShopWalletPassId(interaction);
						checkout.setOtherParams({
							is_price_include_tax: (_getData = getData("is_price_include_tax")) !== null && _getData !== void 0 ? _getData : 1,
							tax_rate: getData("tax_rate") || "10",
							surcharge_list: getData("surcharge_list"),
							currency_format: getData("currency_format"),
							tax_title: getData("tax_title") || "GST",
							tax_country_code: getData("tax_country_code"),
							currency_code: getData("shop_currency_code"),
							currency_symbol: getData("shop_symbol"),
							order_rounding_setting: getData("order_rounding_setting"),
							shop_wallet_pass_id
						});
						const newData = (0, lodash.cloneDeep)(data);
						if (editOrderId || currentEditOrderId) {
							var _newData$subtotal_inf;
							yield checkout.updateLocalOrderAsync({
								orderId: editOrderId || currentEditOrderId,
								orderData: newData.order_info,
								cartSummary: (_newData$subtotal_inf = newData.subtotal_info) === null || _newData$subtotal_inf === void 0 ? void 0 : _newData$subtotal_inf.subTotalList,
								autoPayment: true,
								totalInfo: newData.subtotal_info
							});
						} else {
							var _newData$subtotal_inf2;
							logger === null || logger === void 0 || logger.addLog({
								type: "info",
								title: "正常创建 createLocalOrderAsync",
								metadata: { data }
							});
							yield checkout.createLocalOrderAsync({
								orderData: newData.order_info,
								cartSummary: (_newData$subtotal_inf2 = newData.subtotal_info) === null || _newData$subtotal_inf2 === void 0 ? void 0 : _newData$subtotal_inf2.subTotalList,
								autoPayment: true,
								totalInfo: newData.subtotal_info
							});
						}
						const orderInfo = checkout.getCurrentOrderInfo();
						console.log(orderInfo);
						if (orderInfo && orderInfo.totalAmount) setTotalAmount(orderInfo.totalAmount);
						setOrderInfo(orderInfo);
						if (unsubscribeRef.current) {
							logger === null || logger === void 0 || logger.addLog({
								type: "info",
								title: "有重复的checkout:onOrderSynced，清空",
								metadata: {}
							});
							unsubscribeRef.current();
							unsubscribeRef.current = void 0;
						}
						unsubscribeRef.current = checkout.core.effects.on("checkout:onOrderSynced", executeIfActive(function() {
							var _ref22 = require_asyncToGenerator._asyncToGenerator(function* (data) {
								var _data$response, _responseData$payment2;
								setCurrentEditOrderId(checkout.getCurrentOrderId());
								const responseData = (_data$response = data.response) === null || _data$response === void 0 ? void 0 : _data$response.data;
								const paymentStatus = responseData === null || responseData === void 0 ? void 0 : responseData.payment_status;
								if (data.isManual) return;
								handlePaymentComplete(data);
								if (showingCashToastRef.current) return;
								const orderTotalAmount = Number((responseData === null || responseData === void 0 ? void 0 : responseData.total_amount) || 0);
								const gapAmount = Number((responseData === null || responseData === void 0 ? void 0 : responseData.amount_gap) || 0);
								const currentChangeGivenAmount = Number(responseData === null || responseData === void 0 || (_responseData$payment2 = responseData.payment_info) === null || _responseData$payment2 === void 0 ? void 0 : _responseData$payment2.current_change_given_amount);
								const failureReason = responseData === null || responseData === void 0 ? void 0 : responseData.failure_reason;
								if (paymentStatus) {
									console.log("print_order_onOrderSynced>>>>", responseData);
									logger === null || logger === void 0 || logger.addLog({
										type: "info",
										title: "print_order_onOrderSynced",
										metadata: { responseData }
									});
									try {
										var _responseData$payment3;
										const params = {
											type: "99",
											data: {
												order_id: responseData.order_id,
												machine_code_print_info: responseData === null || responseData === void 0 ? void 0 : responseData.machine_code_print_info,
												small_ticket_data: responseData === null || responseData === void 0 || (_responseData$payment3 = responseData.payment_info) === null || _responseData$payment3 === void 0 ? void 0 : _responseData$payment3.small_ticket_data,
												machine_code_print_info_v2: responseData === null || responseData === void 0 ? void 0 : responseData.machine_code_print_info_v2
											}
										};
										console.log("print_order_onOrderSynced_params>>>>", params);
										logger === null || logger === void 0 || logger.addLog({
											type: "info",
											title: "print_order_onOrderSynced_params",
											metadata: { params }
										});
										nativePrint(params, (res) => {
											console.log("print_order_onOrderSynced_res>>>>", res);
											logger === null || logger === void 0 || logger.addLog({
												type: "info",
												title: "print_order_onOrderSynced_res",
												metadata: { res }
											});
										});
									} catch (error) {
										console.error("print_order_onOrderSynced_error>>>>", error);
										logger === null || logger === void 0 || logger.addLog({
											type: "info",
											title: "print_order_onOrderSynced_error",
											metadata: { error }
										});
									}
									require_PaymentResultToastUtils.calculateStatusClassName(paymentStatus);
									const autoCloseConfig = require_PaymentResultToastUtils.calculateAutoCloseConfig(paymentStatus, !!currentChangeGivenAmount);
									let enabledAutoPrint = false;
									if (isWebPos) enabledAutoPrint = false;
									else {
										var _interaction$utils6, _interaction$utils6$a;
										enabledAutoPrint = yield interaction === null || interaction === void 0 || (_interaction$utils6 = interaction.utils) === null || _interaction$utils6 === void 0 || (_interaction$utils6$a = _interaction$utils6.asyncDataManager) === null || _interaction$utils6$a === void 0 ? void 0 : _interaction$utils6$a.call(_interaction$utils6, {
											module: "get",
											key: "auto_print_receipt"
										});
									}
									const orderInfo = checkout.getCurrentOrderInfo();
									if (!(paymentResultDisplayMode !== "modal")) {
										autoCloseConfig.autoClose = false;
										autoCloseConfig.autoCloseDelay = 0;
										autoCloseConfig.maskClosable = false;
									}
									yield require_PaymentResultToastUtils.displayPaymentResultToast({
										paymentStatus,
										orderTotalAmount: orderInfo.isDeposit ? orderInfo.depositAmount : orderTotalAmount,
										gapAmount: paymentStatus === "partially_paid" ? gapAmount : currentChangeGivenAmount,
										failureReason,
										autoCloseConfig,
										actionButtons: generateActionButtons(paymentStatus, enabledAutoPrint)
									}, paymentResultToastConfig);
									if (paymentStatus === "paid") handleModalClose();
									handlePaymentComplete(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, data), {}, { toastInfo: {
										status: paymentStatus,
										amount: orderTotalAmount,
										gapAmount: currentChangeGivenAmount,
										failureReason
									} }));
								} else handlePaymentComplete(data);
							});
							return function(_x17) {
								return _ref22.apply(this, arguments);
							};
						}()));
					} else if (isLocalOrderCreated.current) {
						console.log("🔄 PaymentModal: data changed, updating checkout data...");
						isLocalOrderCreated.current = false;
						yield checkout.cancelCurrentOrderAsync();
						if (editOrderId || currentEditOrderId) {
							var _data$subtotal_info;
							yield checkout.updateLocalOrderAsync({
								orderId: editOrderId || currentEditOrderId,
								orderData: data === null || data === void 0 ? void 0 : data.order_info,
								cartSummary: data === null || data === void 0 || (_data$subtotal_info = data.subtotal_info) === null || _data$subtotal_info === void 0 ? void 0 : _data$subtotal_info.subTotalList,
								autoPayment: true,
								totalInfo: data === null || data === void 0 ? void 0 : data.subtotal_info
							});
						} else {
							var _data$subtotal_info2;
							logger === null || logger === void 0 || logger.addLog({
								type: "info",
								title: "含有 localOrderCreate, 调用 createLocalOrderAsync",
								metadata: { data }
							});
							yield checkout.createLocalOrderAsync({
								orderData: data === null || data === void 0 ? void 0 : data.order_info,
								cartSummary: data === null || data === void 0 || (_data$subtotal_info2 = data.subtotal_info) === null || _data$subtotal_info2 === void 0 ? void 0 : _data$subtotal_info2.subTotalList,
								autoPayment: true,
								totalInfo: data === null || data === void 0 ? void 0 : data.subtotal_info
							});
						}
						const orderInfo = checkout.getCurrentOrderInfo();
						if (orderInfo && orderInfo.totalAmount) setTotalAmount(orderInfo.totalAmount);
						setOrderInfo(orderInfo);
						isLocalOrderCreated.current = true;
					} else throw new Error("pisellos is not available");
				} catch (error) {
					console.error("Failed to initialize checkout data:", error);
					const domain = window.location.hostname;
					logger === null || logger === void 0 || logger.addLog({
						type: "error",
						title: `${domain}: Failed to initialize checkout data`,
						metadata: { error }
					});
					setShowCreateErrorModal(true);
				}
			});
			return function initCheckoutData() {
				return _ref23.apply(this, arguments);
			};
		}();
		if (data) initCheckoutData();
	}, [data]);
	(0, react.useEffect)(() => {
		return () => {
			if (typeof unsubscribeRef.current === "function") {
				var _unsubscribeRef$curre;
				(_unsubscribeRef$curre = unsubscribeRef.current) === null || _unsubscribeRef$curre === void 0 || _unsubscribeRef$curre.call(unsubscribeRef);
				unsubscribeRef.current = void 0;
			}
		};
	}, []);
	const paymentResultToastConfig = {
		context,
		pisellos,
		getData,
		interaction,
		Toast,
		onToastClose: handleToastClose
	};
	const generateActionButtons = (paymentStatus, enabledAutoPrint = false) => {
		const getClassName = (suffix) => `payment-result-toast-${suffix}`;
		const handleDetailsClick = function() {
			var _ref24 = require_asyncToGenerator._asyncToGenerator(function* () {
				var _context$appHelper2;
				setTimeout(() => {
					require_PaymentResultToastProvider.closePaymentResultToast();
				}, 0);
				const { isTerminal, isWebPos } = (_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.utils;
				if (isTerminal === null || isTerminal === void 0 ? void 0 : isTerminal()) {
					const orderId = yield pisellos.getModule("checkout").getCurrentOrderId();
					return interaction.utils.postMessageToApp({
						module: "booking",
						key: "view_order",
						data: { order_id: orderId },
						origin: "/booking"
					});
				}
			});
			return function handleDetailsClick() {
				return _ref24.apply(this, arguments);
			};
		}();
		const handlePrintReceiptClick = function() {
			var _ref25 = require_asyncToGenerator._asyncToGenerator(function* () {
				setTimeout(() => {
					require_PaymentResultToastProvider.closePaymentResultToast();
				}, 0);
				const checkoutModule = pisellos === null || pisellos === void 0 ? void 0 : pisellos.getModule("checkout");
				if (!checkoutModule) return;
				let data;
				if (!(yield checkoutModule.isCurrentOrderSynced())) data = yield checkoutModule.manualSyncOrderAsync();
				else data = { orderId: yield checkoutModule.getCurrentOrderId() };
				if (data.orderId) {
					const params = {
						type: "0",
						data: { order_id: data.orderId }
					};
					try {
						nativePrint(params, (res) => {
							console.log("handleButtonClick_print-receipt_res>>>>", res);
							if (!(res === null || res === void 0 ? void 0 : res.result)) Toast === null || Toast === void 0 || Toast.error((res === null || res === void 0 ? void 0 : res.msg) || "");
						});
					} catch (error) {
						console.error("handleButtonClick_print-receipt_error>>>>", error);
					}
				}
			});
			return function handlePrintReceiptClick() {
				return _ref25.apply(this, arguments);
			};
		}();
		const handleRetryClick = () => {
			console.log(_pisell_utils.locales.getText("payment.result.actions.retryClicked"));
		};
		const handleChangePaymentClick = () => {
			console.log(_pisell_utils.locales.getText("payment.result.actions.changePaymentClicked"));
		};
		const handleSaveAsPartialPaidClick = () => {
			var _paymentContentRef$cu;
			(_paymentContentRef$cu = paymentContentRef.current) === null || _paymentContentRef$cu === void 0 || _paymentContentRef$cu.handleButtonClick("save-pay-later");
		};
		const handleContinuePaymentClick = () => {
			console.log(_pisell_utils.locales.getText("payment.result.actions.continuePaymentClicked"));
			require_PaymentResultToastProvider.closePaymentResultToast();
		};
		const handleOrderNoteClick = () => {
			setTimeout(() => {
				require_PaymentResultToastProvider.closePaymentResultToast();
			}, 0);
			console.log(_pisell_utils.locales.getText("payment.result.actions.orderNoteClicked"));
			if (handleOrderNoteClickFromToast) handleOrderNoteClickFromToast();
		};
		const handleRefundClick = () => {
			console.log(_pisell_utils.locales.getText("payment.result.actions.refundClicked"));
		};
		switch (paymentStatus) {
			case "paid": return [[enabledAutoPrint ? {
				id: "details",
				buttonProps: {
					className: getClassName("action-button"),
					onClick: handleDetailsClick,
					icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.FileCheck02, { className: getClassName("action-icon") }),
					children: _pisell_utils.locales.getText("payment.result.details")
				}
			} : {
				id: "print",
				buttonProps: {
					className: getClassName("action-button"),
					onClick: handlePrintReceiptClick,
					icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.Printer, { className: getClassName("action-icon") }),
					children: _pisell_utils.locales.getText("payment.result.printReceipt")
				}
			}, {
				id: "more",
				isMore: true,
				menuData: [{
					key: "orderNote",
					label: _pisell_utils.locales.getText("payment.result.orderNote"),
					icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.MessageTextSquare02, { className: getClassName("menu-icon") }),
					onClick: handleOrderNoteClick
				}, enabledAutoPrint ? {
					key: "print",
					label: _pisell_utils.locales.getText("payment.result.printReceipt"),
					icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.Printer, { className: getClassName("action-icon") }),
					onClick: handlePrintReceiptClick
				} : {
					key: "details",
					label: _pisell_utils.locales.getText("payment.result.details"),
					icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.FileCheck02, { className: getClassName("action-icon") }),
					onClick: handleDetailsClick
				}],
				buttonProps: {
					className: getClassName("action-button"),
					icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.DotsVertical, { className: getClassName("action-icon") })
				}
			}]];
			case "partially_paid": return [[enabledAutoPrint ? {
				id: "details",
				buttonProps: {
					className: getClassName("action-button"),
					onClick: handleDetailsClick,
					icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.FileCheck02, { className: getClassName("action-icon") }),
					children: _pisell_utils.locales.getText("payment.result.details")
				}
			} : {
				id: "print",
				buttonProps: {
					className: getClassName("action-button"),
					onClick: handlePrintReceiptClick,
					icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.Printer, { className: getClassName("action-icon") }),
					children: _pisell_utils.locales.getText("payment.result.printReceipt")
				}
			}, {
				id: "more",
				isMore: true,
				menuData: [{
					key: "orderNote",
					label: _pisell_utils.locales.getText("payment.result.orderNote"),
					icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.MessageTextSquare02, { className: getClassName("menu-icon") }),
					onClick: handleOrderNoteClick
				}, enabledAutoPrint ? {
					key: "print",
					label: _pisell_utils.locales.getText("payment.result.printReceipt"),
					icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.Printer, { className: getClassName("action-icon") }),
					onClick: handlePrintReceiptClick
				} : {
					key: "details",
					label: _pisell_utils.locales.getText("payment.result.details"),
					icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.FileCheck02, { className: getClassName("action-icon") }),
					onClick: handleDetailsClick
				}],
				buttonProps: {
					className: getClassName("action-button"),
					icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.DotsVertical, { className: getClassName("action-icon") })
				}
			}]];
			case "failed": return [[
				{
					id: "retry",
					buttonProps: {
						className: getClassName("action-button retry-button"),
						onClick: handleRetryClick,
						icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.RefreshCw05, { className: getClassName("action-icon") }),
						children: _pisell_utils.locales.getText("payment.result.retry")
					}
				},
				{
					id: "changePayment",
					buttonProps: {
						className: getClassName("action-button change-payment-button"),
						onClick: handleChangePaymentClick,
						icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.CreditCard02, { className: getClassName("action-icon") }),
						children: _pisell_utils.locales.getText("payment.result.changePayment")
					}
				},
				{
					id: "more",
					isMore: true,
					menuData: [{
						key: "orderNote",
						label: _pisell_utils.locales.getText("payment.result.orderNote"),
						icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.MessageTextSquare02, { className: getClassName("menu-icon") }),
						onClick: handleOrderNoteClick
					}, {
						key: "refund",
						label: _pisell_utils.locales.getText("payment.result.refund"),
						icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.ArrowLeft, { className: getClassName("menu-icon") }),
						onClick: handleRefundClick
					}],
					buttonProps: {
						className: getClassName("action-button"),
						icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.DotsVertical, { className: getClassName("action-icon") })
					}
				}
			]];
			case "wallet-pass-failed": return [[
				{
					id: "savePartial",
					buttonProps: {
						className: getClassName("action-button primary-button"),
						onClick: handleSaveAsPartialPaidClick,
						children: _pisell_utils.locales.getText("payment.result.saveAsPartialPaid")
					}
				},
				{
					id: "continuePayment",
					buttonProps: {
						className: getClassName("action-button primary-button"),
						onClick: handleContinuePaymentClick,
						children: _pisell_utils.locales.getText("payment.result.continuePayment")
					}
				},
				{
					id: "more",
					isMore: true,
					menuData: [
						{
							key: "details",
							label: _pisell_utils.locales.getText("payment.result.details"),
							icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.FileCheck02, { className: getClassName("menu-icon") }),
							onClick: handleDetailsClick
						},
						{
							key: "print",
							label: _pisell_utils.locales.getText("payment.result.printReceipt"),
							icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.Printer, { className: getClassName("menu-icon") }),
							onClick: handlePrintReceiptClick
						},
						{
							key: "orderNote",
							label: _pisell_utils.locales.getText("payment.result.orderNote"),
							icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.MessageTextSquare02, { className: getClassName("menu-icon") }),
							onClick: handleOrderNoteClick
						},
						{
							key: "refund",
							label: _pisell_utils.locales.getText("payment.result.refund"),
							icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.ArrowLeft, { className: getClassName("menu-icon") }),
							onClick: handleRefundClick
						}
					],
					buttonProps: {
						className: getClassName("action-button"),
						icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.DotsVertical, { className: getClassName("action-icon") })
					}
				}
			]];
			default: return [];
		}
	};
	const showSuccessToast = require_PaymentResultToastUtils.createShowSuccessToast(paymentResultToastConfig, generateActionButtons);
	return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellContainer, {
		renderType: "modal",
		props: {
			open,
			onCancel: () => {
				handlePaymentCancel(false);
			},
			title: /* @__PURE__ */ react.default.createElement(CustomHeader, null),
			width: 880,
			destroyOnClose: false,
			maskClosable: false,
			footer: null,
			closeIcon: false,
			wrapClassName: `payment-modal-wrapper ${!actualShowCashPayment ? "no-cash-payment" : ""}`,
			size: "large",
			style: { height: "auto" },
			bodyStyle: {
				maxHeight: "100%",
				overflowY: "auto",
				padding: 16,
				display: "flex",
				flexDirection: "column"
			}
		}
	}, /* @__PURE__ */ react.default.createElement(PaymentContent, {
		ref: paymentContentRef,
		isModalOpen: open,
		cartData: (0, lodash.cloneDeep)(data),
		orderInfo,
		onPaymentComplete: handlePaymentComplete,
		onPaymentCancel: handlePaymentCancel,
		paymentResultDisplayMode,
		shopDiscount,
		client,
		currentTotalPrice,
		onChangeShopDiscount,
		onChangeOrderNote,
		onDeleteOrderNote,
		showingCashToastRef,
		onToastClose: handleToastClose,
		orderNote,
		setOrderNote,
		setNoteModalSource,
		setNoteModalOpen,
		totalAmount,
		moduleConfig,
		onShowCashPaymentChange: handleShowCashPaymentChange,
		showSuccessToast,
		dynamicMaxHeight,
		onOrderSyncFailed: () => setShowRetryModal(true),
		generateActionButtons,
		paymentResultToastConfig,
		updateOrderInfo: (orderInfo) => setOrderInfo(orderInfo),
		setCurrentEditOrderId: (orderId) => setCurrentEditOrderId(orderId)
	})), noteModalOpen && (0, react_dom.createPortal)(/* @__PURE__ */ react.default.createElement("div", null, /* @__PURE__ */ react.default.createElement(require_index.default, {
		open: noteModalOpen,
		title: _pisell_utils.locales.getText("pisell2.text.add-order-notes"),
		value: orderNote,
		onConfirm: handleNoteConfirm,
		onDelete: handleNoteDelete,
		onCancel: handleNoteCancel
	})), document.body), /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellContainer, {
		renderType: "modal",
		props: {
			open: showRetryModal,
			title: _pisell_utils.locales.getText("pisell2.checkout.tips"),
			footer: null,
			keyboard: false,
			onCancel: () => {
				setShowRetryModal(false);
			}
		}
	}, /* @__PURE__ */ react.default.createElement("div", { style: {
		textAlign: "center",
		padding: "20px"
	} }, /* @__PURE__ */ react.default.createElement("div", { style: {
		marginBottom: "16px",
		fontSize: "16px"
	} }, _pisell_utils.locales.getText("pisell2.checkout.sync-retry-hint") || "请点击重试按钮重新同步订单"), /* @__PURE__ */ react.default.createElement(antd.Button, {
		type: "primary",
		size: "large",
		onClick: handleRetry,
		style: {
			width: "100%",
			marginTop: "80px"
		}
	}, _pisell_utils.locales.getText("retry") || "重试"))), /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellContainer, {
		renderType: "modal",
		props: {
			open: showCreateErrorModal,
			title: _pisell_utils.locales.getText("pisell2.checkout.tips"),
			footer: null,
			keyboard: false,
			onCancel: () => {
				setShowCreateErrorModal(false);
			}
		}
	}, /* @__PURE__ */ react.default.createElement("div", { style: {
		textAlign: "center",
		padding: "20px"
	} }, /* @__PURE__ */ react.default.createElement("div", { style: {
		marginBottom: "16px",
		fontSize: "16px"
	} }, _pisell_utils.locales.getText("pisell2.checkout.order-create-failed")), /* @__PURE__ */ react.default.createElement(antd.Button, {
		type: "primary",
		size: "large",
		onClick: () => {
			setShowCreateErrorModal(false);
			window.location.reload();
		},
		style: {
			width: "100%",
			marginTop: "80px"
		}
	}, _pisell_utils.locales.getText("confirm") || "确认"))));
};
//#endregion
exports.default = PaymentModal;
