import { _asyncToGenerator } from "../../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useEngineContext from "../../../../../../hooks/useEngineContext.js";
import { getPayGroupParamsFromStorage, setPayNumber } from "../../../payGroup.js";
import { Context } from "../../../model.js";
import { fastPayNew } from "../List/serve.js";
import ThreedsLoading from "./ThreedsLoading/index.js";
import { cancelCurrentPayment, startPayment } from "../tds2.js";
import React, { forwardRef, useContext, useEffect, useImperativeHandle, useRef, useState } from "react";
import { Button } from "antd";
import { locales } from "@pisell/utils";
import { PisellModal } from "@pisell/materials";
import "./index.less";
//#region src/components/pay/toC/PaymentMethods/MWCreditCard/TDSPay/index.tsx
/**
* @title: 3ds验证
* @description:
* @param {TDSPayProps} props
* @param {React} ref
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-08-16 11:15
*/
const TDSPay = (props, ref) => {
	var _engineContext$appHel;
	const { onChange, closeAll } = props;
	const [open, setOpen] = useState(false);
	const [showCloseConfirm, setShowCloseConfirm] = useState(false);
	/**
	* 递增会话 ID：每次 init 递增，旧流程通过比对 ID 判断自身是否已被取代。
	* 解决了旧 cancelledRef 的缺陷——旧方案用单一 boolean，新 init 的 reset 会误将
	* 上一次仍在运行的 startPayment 重新"激活"。
	*/
	const sessionIdRef = useRef(0);
	const payingRef = useRef(false);
	const { state } = useContext(Context);
	const { token } = ((_engineContext$appHel = useEngineContext().appHelper) === null || _engineContext$appHel === void 0 ? void 0 : _engineContext$appHel.utils) || {};
	/** 组件卸载时：递增 sessionId 使旧流程的 isCancelled 失效 + 清理残留的 message 监听器 */
	useEffect(() => {
		return () => {
			sessionIdRef.current += 1;
			cancelCurrentPayment();
		};
	}, []);
	/**
	* @title: 创建绑定当前会话的回调
	* @description: 回调内部比对 sessionId，若已被新会话取代则忽略调用。
	*              hideModal 为中间态回调（不释放锁）；其他 key 为终态（释放锁 + 通知外部）。
	*/
	const createSessionCallback = (session) => (res) => {
		if (sessionIdRef.current !== session) return;
		setOpen(false);
		setShowCloseConfirm(false);
		payingRef.current = false;
		if (res.key === "hideModal") return;
		onChange === null || onChange === void 0 || onChange(res);
	};
	/**
	* @title: 初始化 3DS 支付流程
	* @description: 若已有流程在执行中则忽略本次调用。
	*              通过递增 sessionId 自动废弃前一次残留的异步流程。
	*/
	const init = function() {
		var _ref = _asyncToGenerator(function* (res, order, preCheckData) {
			if (payingRef.current) return;
			payingRef.current = true;
			sessionIdRef.current += 1;
			cancelCurrentPayment();
			const session = sessionIdRef.current;
			setOpen(true);
			const isCancelled = () => sessionIdRef.current !== session;
			const callback = createSessionCallback(session);
			if (preCheckData) {
				var _token$get;
				startPayment({ payData: preCheckData }, {
					callback,
					isCancelled,
					stashAuthToken: token === null || token === void 0 || (_token$get = token.get) === null || _token$get === void 0 ? void 0 : _token$get.call(token)
				});
				return;
			}
			if (res.id) _fastPayNew(res, callback, isCancelled);
			else newCardPay(res, callback, isCancelled);
		});
		return function init(_x, _x2, _x3) {
			return _ref.apply(this, arguments);
		};
	}();
	/**
	* @title: 等待页关闭按钮点击
	* @description: 点击 PisellModal 关闭按钮时，弹出确认弹窗而非直接关闭
	*/
	const handleCloseClick = () => {
		setShowCloseConfirm(true);
	};
	/**
	* @title: 确认弹窗 - 继续等待
	* @description: 关闭确认弹窗，继续等待支付结果
	*/
	const handleContinueWaiting = () => {
		setShowCloseConfirm(false);
	};
	/**
	* @title: 确认弹窗 - 查看订单
	* @description: 递增 sessionId 使旧流程的 isCancelled 返回 true，释放锁并关闭弹窗
	*/
	const handleViewOrder = () => {
		sessionIdRef.current += 1;
		cancelCurrentPayment();
		payingRef.current = false;
		setShowCloseConfirm(false);
		setOpen(false);
		closeAll === null || closeAll === void 0 || closeAll();
		onChange === null || onChange === void 0 || onChange({ key: "cancel" });
	};
	/**
	* @title: 快捷支付
	* @description:
	* @param {any} res
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-08-16 11:15
	*/
	const _fastPayNew = function() {
		var _ref2 = _asyncToGenerator(function* (res, callback, isCancelled) {
			try {
				var _state$payGroup, _state$payGroup2, _state$payGroup3, _token$get2;
				const params = getPayGroupParamsFromStorage((_state$payGroup = state.payGroup) === null || _state$payGroup === void 0 ? void 0 : _state$payGroup.order_id, { card_id: res.id });
				if (!params) {
					callback({
						key: "fail",
						data: {
							res,
							fn: "_fastPayNew1",
							message: locales.getText("tocPay.text.getParamsFail")
						}
					});
					return;
				}
				const { data } = yield fastPayNew({
					order_id: (_state$payGroup2 = state.payGroup) === null || _state$payGroup2 === void 0 ? void 0 : _state$payGroup2.order_id,
					params
				});
				if (isCancelled()) return;
				yield setPayNumber((_state$payGroup3 = state.payGroup) === null || _state$payGroup3 === void 0 ? void 0 : _state$payGroup3.order_id, data === null || data === void 0 ? void 0 : data.pay_number, token === null || token === void 0 || (_token$get2 = token.get) === null || _token$get2 === void 0 ? void 0 : _token$get2.call(token));
				if ((data === null || data === void 0 ? void 0 : data.type) === "token") callback({
					key: "success",
					data
				});
				if ((data === null || data === void 0 ? void 0 : data.type) === "3ds") startPayment({ payData: data }, {
					callback,
					isCancelled
				});
			} catch (e) {
				callback({
					key: "fail",
					data: {
						res,
						fn: "_fastPayNew2",
						message: locales.getText("tocPay.text.getParamsFail")
					}
				});
			}
		});
		return function _fastPayNew(_x4, _x5, _x6) {
			return _ref2.apply(this, arguments);
		};
	}();
	/**
	* @title: 新卡支付
	* @description:
	* @param {any} res
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-08-16 11:16
	*/
	const newCardPay = (res, callback, isCancelled) => {
		var _state$payGroup4, _state$payGroup5, _token$get3;
		let _cardInfo = {
			card_name: res.card_name,
			card_number: res.card_number,
			card_expiry_month: res.date.format("MM"),
			card_expiry_year: res.date.format("YY"),
			card_ccv: res.card_ccv,
			is_save: res.is_save ? 1 : 0
		};
		_cardInfo = getPayGroupParamsFromStorage((_state$payGroup4 = state.payGroup) === null || _state$payGroup4 === void 0 ? void 0 : _state$payGroup4.order_id, _cardInfo);
		if (!_cardInfo) {
			callback({
				key: "fail",
				data: {
					_cardInfo,
					message: locales.getText("tocPay.text.getParamsFail"),
					fn: "newCardPay"
				}
			});
			return;
		}
		startPayment({
			orderId: (_state$payGroup5 = state.payGroup) === null || _state$payGroup5 === void 0 ? void 0 : _state$payGroup5.order_id,
			cardInfo: _cardInfo
		}, {
			callback,
			isCancelled,
			stashAuthToken: token === null || token === void 0 || (_token$get3 = token.get) === null || _token$get3 === void 0 ? void 0 : _token$get3.call(token)
		});
	};
	useImperativeHandle(ref, () => ({ init }));
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(PisellModal, {
		platform: "h5",
		open,
		footer: false,
		header: false,
		closable: true,
		onCancel: handleCloseClick,
		bodyStyle: { padding: 0 }
	}, /* @__PURE__ */ React.createElement("div", { className: "" }, /* @__PURE__ */ React.createElement(ThreedsLoading, {
		title: locales.getText("tocPay.text.processingPayment"),
		subtitle: locales.getText("tocPay.text.securityCheckRequired"),
		description: locales.getText("tocPay.text.doNotClosePage")
	}), /* @__PURE__ */ React.createElement("div", { id: "threeds-container" }))), /* @__PURE__ */ React.createElement(PisellModal, {
		open: showCloseConfirm,
		closable: false,
		footer: null,
		header: false,
		mobileModalHeight: "auto",
		headerDivider: false,
		footerDivider: false,
		bodyStyle: { padding: 24 },
		transitionName: "pisell-move-down"
	}, /* @__PURE__ */ React.createElement("div", { className: "tds-close-confirm-modal" }, /* @__PURE__ */ React.createElement("div", { className: "tds-close-confirm-title" }, locales.getText("tocPay.text.stopWaitingTitle")), /* @__PURE__ */ React.createElement("div", { className: "tds-close-confirm-desc" }, locales.getText("tocPay.text.stopWaitingDesc")), /* @__PURE__ */ React.createElement("div", { className: "tds-close-confirm-actions" }, /* @__PURE__ */ React.createElement(Button, {
		type: "primary",
		block: true,
		className: "tds-close-confirm-btn-primary",
		onClick: handleContinueWaiting
	}, locales.getText("tocPay.text.continueWaiting")), /* @__PURE__ */ React.createElement("div", {
		className: "tds-close-confirm-link",
		onClick: handleViewOrder
	}, locales.getText("tocPay.text.viewOrder"))))));
};
var TDSPay_default = forwardRef(TDSPay);
//#endregion
export { TDSPay_default as default };
