import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import { request } from "../../../utils/index.js";
import { PayStatus, StatusEnum } from "../const.js";
import { getPayParams } from "../helper.js";
import { updateCustom, updateNextStep, updateState, updateStatus, useContextData, useDispatch } from "../store/index.js";
import { useFail, useStoreRef } from "../hooks.js";
import payLog from "../utils/payLog.js";
import { EPaymentStatus } from "../aggregatePayment/types.js";
import { usePayment } from "../aggregatePayment/hooks/usePayment.js";
import { CANCEL_ACTION_TIMEOUT, EButtonKeyType } from "./types.js";
import { parseMX51Params } from "./utils.js";
import Action from "./Action.js";
import { getInitState } from "../manufacturer.js";
import React, { useEffect, useRef, useState } from "react";
import { locales } from "@pisell/utils";
import { PisellModal, PisellToast } from "@pisell/materials";
//#region src/components/eftposPay/mx51/index.tsx
const AggregatePayment = ({ onChange }) => {
	const utils = useEngineContext().appHelper.utils || {};
	request.setRequest(utils === null || utils === void 0 ? void 0 : utils.request);
	const { title, custom, status, eftpos, mode, name, symbol, amount, order_id } = useContextData();
	const { statusRef, numRef, netRef, modeRef, deviceRef, orderIdRef, amountRef, payRef } = useStoreRef();
	const dispatch = useDispatch();
	const fail = useFail(0);
	const failRef = useRef(fail);
	const [receiptModalShow, setReceiptModalShow] = useState(false);
	const [receiptModalData, setReceiptModalData] = useState(null);
	const [cancelDisabled, setCancelDisabled] = useState(false);
	const actionTimeoutRef = useRef(null);
	const clearRef = useRef(null);
	useEffect(() => {
		failRef.current = fail;
	}, [fail]);
	const initRef = useRef(false);
	const unloadRef = useRef(false);
	/**
	* 更新到加载状态
	*/
	const updateToLoading = (title) => {
		dispatch(updateStatus(StatusEnum.Loading));
		dispatch(updateState({ title: title || locales.getText("page.eftpos-pay.text.loading")(modeRef.current) }));
	};
	const payment = usePayment({
		paymentCode: "EFTPOS_MX51",
		paymentNum: numRef.current || "",
		shouldContinue: () => !(unloadRef.current || !netRef.current),
		config: {
			hasQueryInterval: false,
			globalQueryTimeout: 1e3 * 60 * 2,
			requestDelaySeconds: 130
		},
		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 = parseMX51Params(transaction, status, data);
			console.log("event_transformedData =>>>>>> ", transformedData);
			dispatch(updateCustom({ customAction: transformedData }));
			let needClearActionTimeout = true;
			if (status === EPaymentStatus.Processing) if (action === "signature") {
				var _transformedData$auto;
				dispatch(updateStatus(StatusEnum.Question));
				dispatch(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 === EPaymentStatus.Success) handleSuccess(data);
			else if (status === EPaymentStatus.Failed) if (transformedData) {
				dispatch(updateStatus("fail"));
				dispatch(updateState({ title: (transformedData === null || transformedData === void 0 ? void 0 : transformedData.message) || "" }));
			} else handleFail(data);
			if (needClearActionTimeout) {
				if (actionTimeoutRef.current) {
					payLog.log("清除操作行为超时定时器");
					clearTimeout(actionTimeoutRef.current);
					actionTimeoutRef.current = null;
				}
			}
		}
	});
	useEffect(() => {
		console.log("mx51页面初始化", statusRef.current);
		if (statusRef.current === StatusEnum.Success || statusRef.current === StatusEnum.Fail || statusRef.current === StatusEnum.Question) return;
		if (initRef.current) return;
		initRef.current = true;
		if (numRef.current) {
			console.log("payment.query");
			payment.query();
			return;
		}
		payment.run();
	}, []);
	useEffect(() => {
		return () => {
			console.log("页面卸载");
			unloadRef.current = true;
			if (actionTimeoutRef.current) {
				clearTimeout(actionTimeoutRef.current);
				actionTimeoutRef.current = null;
			}
			if (clearRef.current) {
				clearTimeout(clearRef.current);
				clearRef.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 || ""}` || 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
		}, true);
	};
	/**
	* 处理支付成功流程
	* 1. 判定设置中是否需要打印商户收据和客户收据，如果需要则自动打印
	* 2. 展示success页面，构建成功参数，并在1秒触发成功回调
	*/
	const handleSuccess = (res) => {
		var _res$data, _deviceRef$current;
		const receipt = [];
		const { transaction, external_service_fee } = (res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.external_unified_response) || {};
		const { merchant_receipt, customer_receipt } = transaction || {};
		const card_reader_surcharge = 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 && merchant_receipt) receipt.push(merchant_receipt);
		if (!isEftposPrintCustomerReceipt && customer_receipt) receipt.push(customer_receipt);
		dispatch(updateNextStep());
		dispatch(updateCustom({
			card_reader_surcharge,
			receipt
		}));
		dispatch(updateState({
			status: "success",
			title: locales.getText("page.eftpos-pay.text.successful")(modeRef.current)
		}));
		clearRef.current = setTimeout(() => {
			onChange("success", _objectSpread2(_objectSpread2({}, 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 }));
		}, 1e3);
	};
	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;
			payLog.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: PayStatus.Timeout }, true);
		}, 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(updateState(getInitState(eftpos, _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 === EPaymentStatus.Success) {
			var _response$data, _deviceRef$current2;
			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$current2 = deviceRef.current) === null || _deviceRef$current2 === void 0 ? void 0 : _deviceRef$current2.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", _objectSpread2(_objectSpread2({}, 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: _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);
		payLog.log(`点击${(element === null || element === void 0 ? void 0 : element.key) || "未知"}按钮`);
		switch (element.key) {
			case EButtonKeyType.CancelTransaction:
				onCancel(element);
				break;
			case EButtonKeyType.DeclineSignature:
				onDecline(element);
				break;
			case EButtonKeyType.ApproveSignature:
				onAccept(element);
				break;
			case EButtonKeyType.PrintMerchantReceipt:
				onPrintMerchantReceipt(element);
				break;
			case EButtonKeyType.PrintCustomerReceipt:
				onPrintCustomerReceipt(element);
				break;
			case EButtonKeyType.RetryTransaction:
				onRetry(element);
				break;
			case EButtonKeyType.TransactionComplete:
				onTransactionComplete(element);
				break;
			case EButtonKeyType.SubmitToAPI:
				onSubmitToAPI(element, extra);
				break;
			case EButtonKeyType.CallTestFunction:
				PisellToast({ content: "Test" });
				break;
			default:
				onNormalClick(element);
				break;
		}
	};
	const onCloseReceiptModal = () => {
		setReceiptModalShow(false);
		setReceiptModalData(null);
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-body" }, status === StatusEnum.Question ? /* @__PURE__ */ React.createElement("div", {
		className: "pisell-lowcode__eft-pay-title",
		style: { textAlign: "center" }
	}, title) : null, status !== StatusEnum.Success ? /* @__PURE__ */ React.createElement(Action, {
		data: custom === null || custom === void 0 ? void 0 : custom.customAction,
		showMessage: status === StatusEnum.Loading,
		onClick: onElementClick,
		cancelDisabled
	}) : null), receiptModalShow ? /* @__PURE__ */ React.createElement(PisellModal, {
		open: receiptModalShow,
		onCancel: onCloseReceiptModal,
		maskClosable: true,
		footer: null
	}, /* @__PURE__ */ React.createElement("div", { style: {
		padding: "16px",
		display: "flex",
		alignItems: "center",
		justifyContent: "center"
	} }, /* @__PURE__ */ React.createElement("span", { style: {
		display: "inline-block",
		whiteSpace: "pre-wrap",
		fontFamily: "monospace",
		backgroundColor: "#fff"
	} }, receiptModalData))) : null);
};
//#endregion
export { AggregatePayment as default };
