const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_useEngineContext = require("../../../hooks/useEngineContext.js");
const require_index = require("../../../utils/index.js");
const require_const = require("../const.js");
const require_helper = require("../helper.js");
const require_index$1 = require("../store/index.js");
const require_hooks = require("../hooks.js");
const require_payLog = require("../utils/payLog.js");
const require_types = require("../aggregatePayment/types.js");
const require_usePayment = require("../aggregatePayment/hooks/usePayment.js");
const require_types$1 = require("./types.js");
const require_utils = require("./utils.js");
const require_Action = require("./Action.js");
const require_manufacturer = require("../manufacturer.js");
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
//#region src/components/eftposPay/mx51/index.tsx
const AggregatePayment = ({ onChange }) => {
	const utils = require_useEngineContext.default().appHelper.utils || {};
	require_index.request.setRequest(utils === null || utils === void 0 ? void 0 : utils.request);
	const { title, custom, status, eftpos, mode, name, symbol, amount, order_id } = require_index$1.useContextData();
	const { statusRef, numRef, netRef, modeRef, deviceRef, orderIdRef, amountRef, payRef } = require_hooks.useStoreRef();
	const dispatch = require_index$1.useDispatch();
	const fail = require_hooks.useFail(0);
	const failRef = (0, react.useRef)(fail);
	const [receiptModalShow, setReceiptModalShow] = (0, react.useState)(false);
	const [receiptModalData, setReceiptModalData] = (0, react.useState)(null);
	const [cancelDisabled, setCancelDisabled] = (0, react.useState)(false);
	const actionTimeoutRef = (0, react.useRef)(null);
	(0, react.useEffect)(() => {
		failRef.current = fail;
	}, [fail]);
	const initRef = (0, react.useRef)(false);
	const unloadRef = (0, react.useRef)(false);
	/**
	* 更新到加载状态
	*/
	const updateToLoading = (title) => {
		dispatch(require_index$1.updateStatus(require_const.StatusEnum.Loading));
		dispatch(require_index$1.updateState({ title: title || _pisell_utils.locales.getText("page.eftpos-pay.text.loading")(modeRef.current) }));
	};
	const payment = require_usePayment.usePayment({
		paymentCode: "EFTPOS_MX51",
		paymentNum: numRef.current || "",
		shouldContinue: () => !(unloadRef.current || !netRef.current),
		config: {
			hasQueryInterval: false,
			globalQueryTimeout: 1e3 * 60,
			requestDelaySeconds: 70
		},
		callback: (_instance, response) => {
			var _data$data;
			console.log("callback  =>>>>>> ", response);
			const { status, data } = response || {};
			const { transaction, action } = (data === null || data === void 0 || (_data$data = data.data) === null || _data$data === void 0 ? void 0 : _data$data.external_unified_response) || {};
			const transformedData = require_utils.parseMX51Params(transaction, status, data);
			console.log("event_transformedData =>>>>>> ", transformedData);
			dispatch(require_index$1.updateCustom({ customAction: transformedData }));
			let needClearActionTimeout = true;
			if (status === require_types.EPaymentStatus.Processing) if (action === "signature") {
				var _transformedData$auto;
				dispatch(require_index$1.updateStatus(require_const.StatusEnum.Question));
				dispatch(require_index$1.updateState({ title: (transformedData === null || transformedData === void 0 ? void 0 : transformedData.message) || "" }));
				_instance.stop();
				if (transformedData === null || transformedData === void 0 || (_transformedData$auto = transformedData.autoAction) === null || _transformedData$auto === void 0 ? void 0 : _transformedData$auto.includes("PRINT_MERCHANT_RECEIPT")) {
					const merchantReceipt = (transformedData === null || transformedData === void 0 ? void 0 : transformedData.merchantReceipt) || "";
					onChange("print", merchantReceipt ? [merchantReceipt] : []);
				}
			} else {
				needClearActionTimeout = false;
				updateToLoading();
			}
			else if (status === require_types.EPaymentStatus.Success) {
				dispatch(require_index$1.updateStatus("success"));
				dispatch(require_index$1.updateState({ title: (transformedData === null || transformedData === void 0 ? void 0 : transformedData.message) || "" }));
			} else if (status === require_types.EPaymentStatus.Failed) if (transformedData) {
				dispatch(require_index$1.updateStatus("fail"));
				dispatch(require_index$1.updateState({ title: (transformedData === null || transformedData === void 0 ? void 0 : transformedData.message) || "" }));
			} else handleFail(data);
			if (needClearActionTimeout) {
				if (actionTimeoutRef.current) {
					require_payLog.default.log("清除操作行为超时定时器");
					clearTimeout(actionTimeoutRef.current);
					actionTimeoutRef.current = null;
				}
			}
		}
	});
	(0, react.useEffect)(() => {
		console.log("mx51页面初始化", statusRef.current);
		if (statusRef.current === require_const.StatusEnum.Success || statusRef.current === require_const.StatusEnum.Fail || statusRef.current === require_const.StatusEnum.Question) return;
		if (initRef.current) return;
		initRef.current = true;
		if (numRef.current) {
			console.log("payment.query");
			payment.query();
			return;
		}
		payment.run();
	}, []);
	(0, react.useEffect)(() => {
		return () => {
			console.log("页面卸载");
			unloadRef.current = true;
			if (actionTimeoutRef.current) {
				clearTimeout(actionTimeoutRef.current);
				actionTimeoutRef.current = null;
			}
		};
	}, []);
	/**
	* 触发支付失败流程：交由 useFail 统一处理失败/重试逻辑
	*/
	const handleFail = (errorData) => {
		var _errorData$data, _failRef$current;
		const { message, response_code } = (errorData === null || errorData === void 0 || (_errorData$data = errorData.data) === null || _errorData$data === void 0 ? void 0 : _errorData$data.external_unified_response) || {};
		const _code = `${response_code || ""}` || require_const.PayStatus.PaymentFailed;
		const _message = message || (errorData === null || errorData === void 0 ? void 0 : errorData.message) || "";
		console.log("handleFail =>>>> ", errorData, _code, _message);
		(_failRef$current = failRef.current) === null || _failRef$current === void 0 || _failRef$current.call(failRef, {
			code: _code,
			message: _message
		}, false);
	};
	const onCancel = (element) => {
		console.log("onCancel", element);
		setCancelDisabled(true);
		payment.action({ submit_url: element === null || element === void 0 ? void 0 : element.submitUrl });
		actionTimeoutRef.current = setTimeout(() => {
			var _payment$_instance, _payment$_instance$st, _failRef$current2;
			require_payLog.default.log("取消操作超时，前往标记支付");
			payment === null || payment === void 0 || (_payment$_instance = payment._instance) === null || _payment$_instance === void 0 || (_payment$_instance$st = _payment$_instance.stop) === null || _payment$_instance$st === void 0 || _payment$_instance$st.call(_payment$_instance);
			(_failRef$current2 = failRef.current) === null || _failRef$current2 === void 0 || _failRef$current2.call(failRef, { code: require_const.PayStatus.Timeout }, true);
		}, require_types$1.CANCEL_ACTION_TIMEOUT);
	};
	const onDecline = (element) => {
		console.log("onDecline", element);
		updateToLoading();
		payment.action({ submit_url: element === null || element === void 0 ? void 0 : element.submitUrl });
	};
	const onAccept = (element) => {
		console.log("onAccept", element);
		updateToLoading();
		payment.action({ submit_url: element === null || element === void 0 ? void 0 : element.submitUrl });
	};
	const onPrintMerchantReceipt = (element) => {
		console.log("onPrintMerchantReceipt", element);
		onChange("print", (element === null || element === void 0 ? void 0 : element.receipt) ? [element === null || element === void 0 ? void 0 : element.receipt] : []);
		setReceiptModalShow(true);
		setReceiptModalData(element === null || element === void 0 ? void 0 : element.receipt);
	};
	const onPrintCustomerReceipt = (element) => {
		console.log("onPrintCustomerReceipt", element);
		onChange("print", (element === null || element === void 0 ? void 0 : element.receipt) ? [element === null || element === void 0 ? void 0 : element.receipt] : []);
		setReceiptModalShow(true);
		setReceiptModalData(element === null || element === void 0 ? void 0 : element.receipt);
	};
	const onRetry = (element) => {
		console.log("onRetry", element);
		onChange("page", "pay");
		dispatch(require_index$1.updateState(require_manufacturer.getInitState(eftpos, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, custom || {}), {}, {
			mode,
			name,
			symbol,
			amount,
			order_id,
			number: ""
		}))));
	};
	const onTransactionComplete = (element) => {
		console.log("onTransactionComplete", element);
		const { paymentStatus, response, merchantReceipt, customerReceipt } = element._extra || {};
		if (paymentStatus === require_types.EPaymentStatus.Success) {
			var _response$data, _deviceRef$current;
			const receipt = [];
			const card_reader_surcharge = (response === null || response === void 0 || (_response$data = response.data) === null || _response$data === void 0 || (_response$data = _response$data.external_unified_response) === null || _response$data === void 0 ? void 0 : _response$data.external_service_fee) || 0;
			const deviceSetting = (_deviceRef$current = deviceRef.current) === null || _deviceRef$current === void 0 ? void 0 : _deviceRef$current.setting;
			const isEftposPrintMerchantReceipt = deviceSetting === null || deviceSetting === void 0 ? void 0 : deviceSetting.print_merchant_receipt;
			const isEftposPrintCustomerReceipt = deviceSetting === null || deviceSetting === void 0 ? void 0 : deviceSetting.prompt_customer_receipt;
			if (!isEftposPrintMerchantReceipt && merchantReceipt) receipt.push(merchantReceipt);
			if (!isEftposPrintCustomerReceipt && customerReceipt) receipt.push(customerReceipt);
			onChange("success", require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, require_helper.getPayParams({
				mode: modeRef.current,
				amount: amountRef.current,
				order_id: orderIdRef.current,
				number: numRef.current,
				device: deviceRef.current,
				pay: payRef.current,
				custom: {
					card_reader_surcharge,
					receipt
				}
			}, "success")), {}, { receipt }));
		} else onChange("fail", {
			order_id: orderIdRef.current,
			number: numRef.current,
			uniquePaymentNumber: numRef.current,
			device: deviceRef.current
		});
	};
	const onSubmitToAPI = (element, extra) => {
		updateToLoading();
		const inputValues = (extra === null || extra === void 0 ? void 0 : extra.inputValues) || {};
		payment.action({
			submit_url: element === null || element === void 0 ? void 0 : element.submitUrl,
			payload: require_objectSpread2._objectSpread2({}, inputValues)
		}, { needResponse: true });
	};
	const onNormalClick = (element, config) => {
		if (element === null || element === void 0 ? void 0 : element.submitUrl) {
			console.log("onNormalClick_submit_url", element === null || element === void 0 ? void 0 : element.submitUrl);
			updateToLoading();
			payment.action({ submit_url: element === null || element === void 0 ? void 0 : element.submitUrl }, config);
		} else console.log("onNormalClick_no_submit_url", element);
	};
	const onElementClick = (element, extra) => {
		console.log("onElementClick", element, extra);
		require_payLog.default.log(`点击${(element === null || element === void 0 ? void 0 : element.key) || "未知"}按钮`);
		switch (element.key) {
			case require_types$1.EButtonKeyType.CancelTransaction:
				onCancel(element);
				break;
			case require_types$1.EButtonKeyType.DeclineSignature:
				onDecline(element);
				break;
			case require_types$1.EButtonKeyType.ApproveSignature:
				onAccept(element);
				break;
			case require_types$1.EButtonKeyType.PrintMerchantReceipt:
				onPrintMerchantReceipt(element);
				break;
			case require_types$1.EButtonKeyType.PrintCustomerReceipt:
				onPrintCustomerReceipt(element);
				break;
			case require_types$1.EButtonKeyType.RetryTransaction:
				onRetry(element);
				break;
			case require_types$1.EButtonKeyType.TransactionComplete:
				onTransactionComplete(element);
				break;
			case require_types$1.EButtonKeyType.SubmitToAPI:
				onSubmitToAPI(element, extra);
				break;
			case require_types$1.EButtonKeyType.CallTestFunction:
				(0, _pisell_materials.PisellToast)({ content: "Test" });
				break;
			default:
				onNormalClick(element);
				break;
		}
	};
	const onCloseReceiptModal = () => {
		setReceiptModalShow(false);
		setReceiptModalData(null);
	};
	return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__eft-pay-body" }, status === require_const.StatusEnum.Question ? /* @__PURE__ */ react.default.createElement("div", {
		className: "pisell-lowcode__eft-pay-title",
		style: { textAlign: "center" }
	}, title) : null, /* @__PURE__ */ react.default.createElement(require_Action.default, {
		data: custom === null || custom === void 0 ? void 0 : custom.customAction,
		showMessage: status === require_const.StatusEnum.Loading,
		onClick: onElementClick,
		cancelDisabled
	})), receiptModalShow ? /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellModal, {
		open: receiptModalShow,
		onCancel: onCloseReceiptModal,
		maskClosable: true,
		footer: null
	}, /* @__PURE__ */ react.default.createElement("div", { style: {
		padding: "16px",
		display: "flex",
		alignItems: "center",
		justifyContent: "center"
	} }, /* @__PURE__ */ react.default.createElement("span", { style: {
		display: "inline-block",
		whiteSpace: "pre-wrap",
		fontFamily: "monospace",
		backgroundColor: "#fff"
	} }, receiptModalData))) : null);
};
//#endregion
exports.default = AggregatePayment;
