import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { ModeEnum, PayStatus, StatusEnum } from "../const.js";
import { getPayParams } from "../helper.js";
import { updateCustom, updateNextStep, updateState, 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 React, { useEffect, useRef, useState } from "react";
import { Button } from "antd";
import { locales } from "@pisell/utils";
import { PisellModal } from "@pisell/materials";
import "./index.less";
//#region src/components/eftposPay/adyenPos/index.tsx
/**
* Adyen 常规支付组件
*
* 流程：
*   1. Init 状态 → 显示支付操作界面（由业务具体实现）
*   2. 用户确认后 → 调用 Adyen API 发起支付
*   3. Processing 普通 → 展示"处理中" + 取消按钮
*   4. Processing 签名中（signature_required）→ 展示"客户签名中"提示，禁用取消
*   5. 支付成功（无签名）→ dispatch updateNextStep + 回调 onChange('success')
*   6. 支付成功（有签名）→ 展示签名核查 UI，员工确认后回调 onChange('success')
*      - Accept：签名通过，直接走成功流程
*      - Decline：弹出二次确认，提示员工手动退款，确认后走成功流程
*   7. 支付失败 → useFail 处理跳转失败页
*/
const AdyenPos = ({ onChange, isNativeApp }) => {
	var _data$custom6, _data$custom7, _data$custom8;
	const data = useContextData();
	const dispatch = useDispatch();
	const { statusRef, modeRef, amountRef, orderIdRef, numRef, deviceRef, payRef, netRef } = useStoreRef();
	const fail = useFail(0);
	const failRef = useRef(fail);
	const initRef = useRef(false);
	const unloadRef = useRef(false);
	const clearRef = useRef(null);
	const [showDeclineModal, setShowDeclineModal] = useState(false);
	const payment = usePayment({
		paymentCode: "ADYEN_POS",
		paymentNum: numRef.current || "",
		shouldContinue: () => !(unloadRef.current || !netRef.current),
		callback: (_instance, response) => {
			console.log("response =>>>> ", response);
			const { status, data: responseData } = response || {};
			if (status === EPaymentStatus.Success) handleSuccess(responseData);
			else if (status === EPaymentStatus.Failed) handleFail(responseData);
			else if (status === EPaymentStatus.Processing) handleProcessing(responseData);
		}
	});
	useEffect(() => {
		failRef.current = fail;
	}, [fail]);
	useEffect(() => {
		return () => {
			unloadRef.current = true;
			if (clearRef.current) clearTimeout(clearRef.current);
		};
	}, []);
	useEffect(() => {
		if (statusRef.current === StatusEnum.Success || statusRef.current === StatusEnum.Fail) return;
		if (initRef.current) return;
		initRef.current = true;
		if (numRef.current) {
			console.log("payment.query");
			payment.query();
			return;
		}
		if (modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay) payment.run();
		else {
			var _data$custom;
			payment.run({ params: { adyenpos: { order_payment_id: data === null || data === void 0 || (_data$custom = data.custom) === null || _data$custom === void 0 ? void 0 : _data$custom.order_payment_id } } });
		}
	}, []);
	/**
	* 触发支付成功流程
	* - 若响应包含签名步骤（signature_required），暂停 onChange，展示签名核查 UI
	* - 否则直接走成功流程
	*/
	const handleSuccess = (responseData) => {
		var _responseData$data, _response$cvm_result;
		const _response = (responseData === null || responseData === void 0 || (_responseData$data = responseData.data) === null || _responseData$data === void 0 ? void 0 : _responseData$data.external_unified_response) || {};
		const signatureRequired = _response === null || _response === void 0 || (_response$cvm_result = _response.cvm_result) === null || _response$cvm_result === void 0 ? void 0 : _response$cvm_result.signature_required;
		dispatch(updateState({
			status: "success",
			title: locales.getText("page.eftpos-pay.text.successful")(modeRef.current)
		}));
		dispatch(updateNextStep());
		dispatch(updateCustom({
			card_reader_surcharge: 0,
			receipt: []
		}));
		const params = 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");
		const onChangeParams = _objectSpread2(_objectSpread2({}, params), {}, { receipt: [] });
		if (signatureRequired) dispatch(updateCustom({
			successParams: onChangeParams,
			signatureCheck: true
		}));
		else clearRef.current = setTimeout(() => {
			if (unloadRef.current) return;
			onChange("success", params);
		}, 1e3);
	};
	/**
	* 签名核查通过：直接走成功流程
	*/
	const handleSignatureAccept = () => {
		var _data$custom2;
		payLog.log("点击签名核查通过");
		if (data === null || data === void 0 || (_data$custom2 = data.custom) === null || _data$custom2 === void 0 ? void 0 : _data$custom2.successParams) {
			var _data$custom3;
			onChange("success", data === null || data === void 0 || (_data$custom3 = data.custom) === null || _data$custom3 === void 0 ? void 0 : _data$custom3.successParams);
			dispatch(updateCustom({
				successParams: null,
				signatureCheck: false
			}));
		}
	};
	/**
	* 拒绝签名：弹出二次确认，提示员工手动退款
	*/
	const handleSignatureDecline = () => {
		payLog.log("点击拒绝签名-弹出二次确认弹窗");
		setShowDeclineModal(true);
	};
	/**
	* 拒绝签名二次确认弹窗-点击确认
	*/
	const handleDeclineModalConfirm = () => {
		var _data$custom4;
		payLog.log("拒绝签名二次确认弹窗-点击确认");
		setShowDeclineModal(false);
		if (data === null || data === void 0 || (_data$custom4 = data.custom) === null || _data$custom4 === void 0 ? void 0 : _data$custom4.successParams) {
			var _data$custom5;
			onChange("success", data === null || data === void 0 || (_data$custom5 = data.custom) === null || _data$custom5 === void 0 ? void 0 : _data$custom5.successParams);
			dispatch(updateCustom({
				successParams: null,
				signatureCheck: false
			}));
		}
	};
	/**
	* 拒绝签名二次确认弹窗-点击取消
	*/
	const handleDeclineModalCancel = () => {
		payLog.log("拒绝签名二次确认弹窗-点击取消");
		setShowDeclineModal(false);
	};
	/**
	* 触发支付失败流程：交由 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
		}, false);
	};
	/**
	* 处理中逻辑：若刷卡机进入签名步骤，禁用取消按钮并展示提示
	*/
	const handleProcessing = (processingData) => {
		var _processingData$data, _response$cvm_result2;
		console.log("handleProcessing =>>>> ", processingData);
		const _response = (processingData === null || processingData === void 0 || (_processingData$data = processingData.data) === null || _processingData$data === void 0 ? void 0 : _processingData$data.external_unified_response) || {};
		if (_response === null || _response === void 0 || (_response$cvm_result2 = _response.cvm_result) === null || _response$cvm_result2 === void 0 ? void 0 : _response$cvm_result2.signature_required) dispatch(updateCustom({
			buttonDisabled: true,
			signingInProgress: true
		}));
	};
	/**
	* 取消按钮点击逻辑
	*/
	const onCancel = () => {
		payLog.log("点击取消按钮");
		payment.action({ action: "abort" });
		dispatch(updateCustom({ buttonDisabled: true }));
	};
	return /* @__PURE__ */ React.createElement("div", { className: "pisell-eftpos-pay-adyen" }, (data === null || data === void 0 ? void 0 : data.status) === StatusEnum.Success && (data === null || data === void 0 || (_data$custom6 = data.custom) === null || _data$custom6 === void 0 ? void 0 : _data$custom6.signatureCheck) && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, locales.getText("page.eftpos-pay.adyen.pos.signature.check.title")), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, locales.getText("page.eftpos-pay.adyen.pos.signature.check.text")), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item-btns" }, /* @__PURE__ */ React.createElement(Button, {
		block: true,
		className: "pisell-lowcode__eft-pay-step-item-btn",
		onClick: handleSignatureDecline
	}, locales.getText("page.eftpos-pay.adyen.pos.signature.declined")), /* @__PURE__ */ React.createElement(Button, {
		block: true,
		type: "primary",
		className: "pisell-lowcode__eft-pay-step-item-btn",
		onClick: handleSignatureAccept
	}, locales.getText("page.eftpos-pay.adyen.pos.signature.approved"))), /* @__PURE__ */ React.createElement(PisellModal, {
		open: showDeclineModal,
		title: locales.getText("page.eftpos-pay.adyen.pos.signature.declined.modal.title"),
		okText: locales.getText("page.eftpos-pay.adyen.pos.signature.declined.modal.ok"),
		cancelText: locales.getText("page.eftpos-pay.text.back"),
		onOk: handleDeclineModalConfirm,
		onCancel: handleDeclineModalCancel
	}, /* @__PURE__ */ React.createElement("div", {
		className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip",
		style: { paddingTop: "24px" }
	}, locales.getText("page.eftpos-pay.adyen.pos.signature.declined.modal.content")))), (data === null || data === void 0 ? void 0 : data.status) === StatusEnum.Loading && /* @__PURE__ */ React.createElement(React.Fragment, null, (data === null || data === void 0 || (_data$custom7 = data.custom) === null || _data$custom7 === void 0 ? void 0 : _data$custom7.signingInProgress) ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, locales.getText("page.eftpos-pay.adyen.pos.signature.signing")), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, locales.getText("page.eftpos-pay.adyen.pos.signature.signing.tip"))) : /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, locales.getText("page.eftpos-pay.text.processing")), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item-btns" }, /* @__PURE__ */ React.createElement(Button, {
		block: true,
		className: "pisell-lowcode__eft-pay-step-item-btn",
		onClick: onCancel,
		disabled: !!(data === null || data === void 0 || (_data$custom8 = data.custom) === null || _data$custom8 === void 0 ? void 0 : _data$custom8.buttonDisabled)
	}, locales.getText("page.eftpos-pay.text.cancel")))));
};
//#endregion
export { AdyenPos as default };
