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_const = require("../const.js");
const require_helper = require("../helper.js");
const require_index = require("../store/index.js");
const require_hooks = require("../hooks.js");
const require_types = require("../aggregatePayment/types.js");
const require_usePayment = require("../aggregatePayment/hooks/usePayment.js");
const require_Action = require("./Action.js");
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
require("./index.less");
//#region src/components/eftposPay/adyenScan/index.tsx
const ADYEN_SCAN_PAYMENT_CODE_MAP = {
	[require_const.EftposEnum.AdyenAlipay]: "EFTPOS_ADYENALIPAY",
	[require_const.EftposEnum.AdyenWechat]: "EFTPOS_ADYENWECHAT"
};
/**
* Adyen 扫码支付组件（商家被扫模式）
*/
const AdyenScan = ({ onChange, isNativeApp }) => {
	var _context$appHelper;
	const data = require_index.useContextData();
	const { interaction } = ((_context$appHelper = require_useEngineContext.default().appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const dispatch = require_index.useDispatch();
	const { statusRef, modeRef, amountRef, orderIdRef, numRef, deviceRef, payRef, netRef, eftposRef } = require_hooks.useStoreRef();
	const fail = require_hooks.useFail(0);
	const failRef = (0, react.useRef)(fail);
	const initRef = (0, react.useRef)(false);
	const unloadRef = (0, react.useRef)(false);
	const clearRef = (0, react.useRef)(null);
	const [loading, setLoading] = (0, react.useState)(false);
	const [qrCode, setQrCode] = (0, react.useState)("");
	const qrCodeRef = (0, react.useRef)("");
	/** 支付方式类型 */
	const [payMethodType, setPayMethodType] = (0, react.useState)("");
	const payment = require_usePayment.usePayment({
		paymentCode: ADYEN_SCAN_PAYMENT_CODE_MAP[eftposRef.current],
		paymentNum: numRef.current || "",
		config: { globalQueryTimeout: modeRef.current === require_const.ModeEnum.Pay || modeRef.current === require_const.ModeEnum.FullPay ? 1e3 * 60 * 5 : 1e3 * 60 * 2 },
		shouldContinue: () => !(unloadRef.current || !netRef.current),
		callback: (_instance, response) => {
			console.log("response =>>>> ", response);
			const { status, data } = response || {};
			let needHideLoading = true;
			if (status === require_types.EPaymentStatus.Processing) {
				var _data$data;
				const { url, paymentMethodType, qrCodeData } = (data === null || data === void 0 || (_data$data = data.data) === null || _data$data === void 0 || (_data$data = _data$data.external_unified_response) === null || _data$data === void 0 ? void 0 : _data$data.action) || {};
				const _qrCode = url || qrCodeData;
				if (!_qrCode) needHideLoading = false;
				if (_qrCode && _qrCode !== qrCodeRef.current) {
					qrCodeRef.current = _qrCode;
					setQrCode(_qrCode);
					setPayMethodType(paymentMethodType);
				}
			} else if (status === require_types.EPaymentStatus.Success) handleSuccess();
			else if (status === require_types.EPaymentStatus.Failed) handleFail(data);
			if (needHideLoading) setLoading(false);
		}
	});
	(0, react.useEffect)(() => {
		failRef.current = fail;
	}, [fail]);
	(0, react.useEffect)(() => {
		if (statusRef.current === require_const.StatusEnum.Success || statusRef.current === require_const.StatusEnum.Fail) return;
		if (initRef.current) return;
		initRef.current = true;
		if (numRef.current) {
			console.log("payment.query");
			payment.query();
			return;
		}
		const isPay = modeRef.current === require_const.ModeEnum.Pay || modeRef.current === require_const.ModeEnum.FullPay;
		setLoading(true);
		updateToLoading();
		if (isPay) payment.run({ params: { adyenscan: { return_url: "https://aa269b.mypisell-dev.cn/" } } });
		else {
			var _data$custom;
			payment.run({ params: { adyenscan: { order_payment_id: data === null || data === void 0 || (_data$custom = data.custom) === null || _data$custom === void 0 ? void 0 : _data$custom.order_payment_id } } });
		}
	}, []);
	(0, react.useEffect)(() => {
		if (isNativeApp && (data === null || data === void 0 ? void 0 : data.status) === require_const.StatusEnum.Init) {
			var _interaction$utils, _interaction$utils$po;
			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: "pos",
				key: "other",
				data: { key: "show_close_button" }
			});
		}
	}, [isNativeApp, data === null || data === void 0 ? void 0 : data.status]);
	(0, react.useEffect)(() => {
		return () => {
			unloadRef.current = true;
			if (clearRef.current) clearTimeout(clearRef.current);
		};
	}, []);
	/**
	* 进入 Loading 态
	* 在该步骤展示QRCode给用户扫码，不能直接关闭支付弹窗
	*/
	const updateToLoading = () => {
		if (isNativeApp) {
			var _interaction$utils2, _interaction$utils2$p;
			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: "pos",
				key: "other",
				data: { key: "hide_close_button" }
			});
		}
		dispatch(require_index.updateStatus(require_const.StatusEnum.Loading));
		dispatch(require_index.updateState({ title: _pisell_utils.locales.getText("page.eftpos-pay.text.loading")(modeRef.current) }));
	};
	/**
	* 触发支付成功流程：更新 store 状态 → 延迟回调外部 onChange
	*/
	const handleSuccess = () => {
		dispatch(require_index.updateNextStep());
		dispatch(require_index.updateCustom({
			card_reader_surcharge: 0,
			receipt: []
		}));
		dispatch(require_index.updateState({
			status: "success",
			title: _pisell_utils.locales.getText("page.eftpos-pay.text.successful")(modeRef.current)
		}));
		clearRef.current = setTimeout(() => {
			if (unloadRef.current) return;
			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: 0,
					receipt: []
				}
			}, "success")), {}, { receipt: [] }));
		}, 1e3);
	};
	/**
	* 触发支付失败流程：交由 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 handleClose = () => {
		onChange("fail", {
			number: data.number,
			uniquePaymentNumber: data.number,
			order_id: data.order_id
		});
	};
	/**
	* 在二维码展示阶段点击取消：
	* 弹出确认弹窗，防止顾客已扫码支付后商家误操作导致重复收款。
	* 确认后：停止轮询、销毁支付实例，并通知外层关闭当前支付流。
	*/
	const handleCancelModalOk = () => {
		payment.reset();
		handleClose();
	};
	return /* @__PURE__ */ react.default.createElement("div", { className: "pisell-eftpos-pay-adyen-scan" }, (data === null || data === void 0 ? void 0 : data.status) === require_const.StatusEnum.Loading ? /* @__PURE__ */ react.default.createElement(require_Action.AdyenScanQrcode, {
		loading,
		qrCode,
		payMethodType,
		onCancelPay: handleCancelModalOk,
		isPay: modeRef.current === require_const.ModeEnum.Pay || modeRef.current === require_const.ModeEnum.FullPay,
		message: _pisell_utils.locales.getText("page.eftpos-pay.text.processing")
	}) : null);
};
//#endregion
exports.default = AdyenScan;
