import { _objectSpread2 } from "../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { request } from "../../../../../utils/index.js";
import { getUniqueIdempotencyToken } from "../../utils.js";
import { setPayNumber } from "../../payGroup.js";
import dayjs from "dayjs";
import { sendWarningLog } from "@pisell/utils";
import { PisellToast } from "@pisell/materials";
//#region src/components/pay/toC/PaymentMethods/MWCreditCard/tds2.tsx
const { REACT_APP_API_ENV } = process.env;
const paymentInfo = {
	transactionInfo: {
		transactionProduct: "TEST 3DSv2",
		transactionAmount: "1.00",
		transactionCurrency: "AUD"
	},
	customerName: "Jim Bob",
	billingAddress: {
		billAddrLine1: "123 Test Street",
		billAddrCity: "Brisbane",
		billAddrState: "QLD",
		billAddrPostCode: "4000",
		billAddrCountry: "AU"
	}
};
let paymentData = {};
const postmessageUrl = "merchantwarrior";
/**
* 当前活跃的 message 监听器清理函数。
* 步骤3（createThreeDSMethodIframe）和步骤5（createChallengeIframe）
* 各自注册 window message 监听器时会存入此变量，
* 供组件卸载或新流程启动时清理残留监听器 + reject 挂起的 Promise。
*/
let activeCleanup = null;
/**
* 取消当前支付流程中残留的 message 监听器和定时器，
* 并 reject 挂起的 Promise 使 startPayment 的 await 结束。
* reject 值为 0，startPayment catch 中 `if (err === 0) return` 会静默处理。
*/
const cancelCurrentPayment = () => {
	activeCleanup === null || activeCleanup === void 0 || activeCleanup();
	activeCleanup = null;
};
const log = (data) => {
	let _template = {
		module,
		contents: {
			path: location.href,
			data,
			date: dayjs().format("YYYY-MM-DD HH:mm")
		}
	};
	sendWarningLog({
		title: "3ds支付失败",
		content: [{
			key: "res",
			value: JSON.stringify(_template)
		}]
	});
};
const setHistoryLog = (log) => {
	if (!paymentData.logList) paymentData.logList = [];
	paymentData.logList.push(log);
};
const getCurrentTime = () => {
	return dayjs().format("YYYY-MM-DD HH:mm:ss");
};
/**
* @title: 点击支付
* @description:
* @param {any} param1
* @return {*}
* @Author: Wzw
* @Date: 2022-10-22 10:05
*/
const startPayment = function() {
	var _ref = _asyncToGenerator(function* ({ orderId, cardInfo, payData }, options) {
		const { callback, isCancelled, stashAuthToken } = options || {};
		let paymentInfo = {
			amount: 0,
			order_id: 0
		};
		try {
			paymentData = {
				orderId,
				logList: []
			};
			setHistoryLog({
				msg: "startPayment 开始",
				time: getCurrentTime(),
				hasPayData: !!payData,
				payDataOrderId: payData === null || payData === void 0 ? void 0 : payData.order_id,
				payDataPayNumber: payData === null || payData === void 0 ? void 0 : payData.pay_number
			});
			const step2 = payData ? payData : yield checkEnrollment(orderId, cardInfo, {
				callback,
				isCancelled,
				stashAuthToken
			});
			if (isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) {
				closeIframe();
				return;
			}
			setHistoryLog({
				msg: "步骤2完成: 提交卡信息到后端",
				time: getCurrentTime(),
				hasStep2: !!step2
			});
			if (step2 === 0) return;
			paymentData.step2 = step2;
			paymentInfo.amount = step2.amount;
			paymentInfo.order_id = step2.order_id;
			console.log("第三步");
			setHistoryLog({
				msg: "步骤3开始: 创建iframe监听postMessage",
				time: getCurrentTime()
			});
			let step3 = yield createThreeDSMethodIframe(step2, callback);
			if (isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) {
				closeIframe();
				return;
			}
			paymentData.step3 = step3;
			setHistoryLog({
				msg: "步骤3完成: iframe监听结束",
				time: getCurrentTime(),
				step3Result: step3
			});
			if (step3 === "N") return;
			setHistoryLog({
				msg: "步骤4开始: 调用checkTDSAuth",
				time: getCurrentTime(),
				order_id: step2 === null || step2 === void 0 ? void 0 : step2.order_id,
				pay_number: step2 === null || step2 === void 0 ? void 0 : step2.pay_number
			});
			const step4 = yield checkTDSAuth(step2, step3, {
				callback,
				isCancelled
			});
			if (isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) {
				closeIframe();
				return;
			}
			setHistoryLog({
				msg: "步骤4完成: checkTDSAuth 返回",
				time: getCurrentTime(),
				hasStep4: !!step4
			});
			if (step4 === 0) return;
			paymentData.step4 = step4;
			if (step4) {
				setHistoryLog({
					msg: "步骤5开始: 创建challenge iframe",
					time: getCurrentTime()
				});
				const step5 = yield createChallengeIframe(step4, callback);
				if (isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) {
					closeIframe();
					return;
				}
				paymentData.step5 = step5;
				setHistoryLog({
					msg: "步骤5完成: challenge iframe结束",
					time: getCurrentTime()
				});
				setHistoryLog({
					msg: "步骤6开始: 调用check_pares接口",
					time: getCurrentTime()
				});
				yield checkPARes(step2, step4, step5);
				if (isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) {
					closeIframe();
					return;
				}
				setHistoryLog({
					msg: "步骤6完成: check_pares接口返回",
					time: getCurrentTime()
				});
			}
			if (isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) {
				closeIframe();
				return;
			}
			callback === null || callback === void 0 || callback({ key: "hideModal" });
			setHistoryLog({
				msg: "支付成功",
				time: getCurrentTime()
			});
			paymentEnd(_objectSpread2({ status: "success" }, paymentInfo), callback);
			return true;
		} catch (err) {
			console.log("error", err);
			setHistoryLog({
				msg: "支付异常",
				time: getCurrentTime(),
				error: err,
				errorCode: err === null || err === void 0 ? void 0 : err.code
			});
			closeIframe();
			if (isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) return;
			callback === null || callback === void 0 || callback({ key: "hideModal" });
			if (err === 0) return;
			if ((err === null || err === void 0 ? void 0 : err.code) === 700500) {
				callback === null || callback === void 0 || callback({ key: "bankVerifyFailed" });
				return false;
			}
			paymentData.error = err;
			paymentEnd(_objectSpread2({ status: "fail" }, paymentInfo), callback);
			return false;
		}
	});
	return function startPayment(_x, _x2) {
		return _ref.apply(this, arguments);
	};
}();
/**
* @title: 前置检查 - 提交卡信息到后端（预检查版本）
* @description: 与 checkEnrollment 调用相同 API，但不包含 Toast/callback/closeIframe 等副作用。
*              失败时直接 throw error，由调用方（MWCreditCard）捕获并展示 3DS 错误弹窗。
* @param {string} orderId 订单ID
* @param {any} cardInfo 卡信息
* @return {Promise<any>} 返回后端数据（含 pay_info），失败则 throw
*/
const preCheckEnrollment = function() {
	var _ref2 = _asyncToGenerator(function* (orderId, cardInfo, stashAuthToken) {
		try {
			const { data } = yield request.getRequest().post("/h5/pay/order/mw-3ds-pay/v2/" + orderId, _objectSpread2({}, cardInfo));
			yield setPayNumber(orderId, data === null || data === void 0 ? void 0 : data.pay_number, stashAuthToken);
			if (!(data === null || data === void 0 ? void 0 : data.pay_info)) throw new Error("Card does not support 3DS verification");
			return data;
		} catch (err) {
			log({
				msg: err,
				data: {
					orderId,
					cardInfo
				}
			});
			throw err;
		}
	});
	return function preCheckEnrollment(_x3, _x4, _x5) {
		return _ref2.apply(this, arguments);
	};
}();
/*******
* @title: 步骤2
* @description: 提交卡信息到后端
* @return {*}
* @Author: Wzw
* @Date: 2022-10-18 10:26
*/
const checkEnrollment = function() {
	var _ref3 = _asyncToGenerator(function* (orderId, cardInfo, options) {
		const { callback, isCancelled, stashAuthToken } = options || {};
		try {
			let { data } = yield request.getRequest().post("/h5/pay/order/mw-3ds-pay/v2/" + orderId, _objectSpread2({}, cardInfo));
			if (isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) return 0;
			yield setPayNumber(orderId, data === null || data === void 0 ? void 0 : data.pay_number, stashAuthToken);
			if (!(data === null || data === void 0 ? void 0 : data.pay_info)) return null;
			return data;
		} catch (err) {
			log({
				msg: err,
				data: {
					orderId,
					cardInfo
				}
			});
			if (isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) return 0;
			callback === null || callback === void 0 || callback({ key: "hideModal" });
			closeIframe();
			PisellToast({
				content: (err === null || err === void 0 ? void 0 : err.message) || "",
				duration: 2
			});
			console.log("error", err);
			return 0;
		}
	});
	return function checkEnrollment(_x6, _x7, _x8) {
		return _ref3.apply(this, arguments);
	};
}();
/**
* @title: 步骤3
* @description: 创建iframe, 监听
* @param {any} threeDSMethodData
* @return {*}
* @Author: Wzw
* @Date: 2022-10-18 10:36
*/
const createThreeDSMethodIframe = function() {
	var _ref4 = _asyncToGenerator(function* (threeDSMethodData, callback) {
		var _threeDSMethodData$pa, _threeDSMethodData$pa2, _threeDSMethodData$pa3, _threeDSMethodData$pa4, _threeDSMethodData$pa5, _threeDSMethodData$pa6;
		const defaultReturnParams = {
			threeDSServerTransID: (threeDSMethodData === null || threeDSMethodData === void 0 || (_threeDSMethodData$pa = threeDSMethodData.pay_info) === null || _threeDSMethodData$pa === void 0 ? void 0 : _threeDSMethodData$pa.threeDSServerTransID) || (threeDSMethodData === null || threeDSMethodData === void 0 || (_threeDSMethodData$pa2 = threeDSMethodData.pay_info) === null || _threeDSMethodData$pa2 === void 0 ? void 0 : _threeDSMethodData$pa2.paReq) || "",
			threeDSCompInd: (threeDSMethodData === null || threeDSMethodData === void 0 || (_threeDSMethodData$pa3 = threeDSMethodData.pay_info) === null || _threeDSMethodData$pa3 === void 0 ? void 0 : _threeDSMethodData$pa3.threeDSCompInd) || "N"
		};
		if ((threeDSMethodData === null || threeDSMethodData === void 0 || (_threeDSMethodData$pa4 = threeDSMethodData.pay_info) === null || _threeDSMethodData$pa4 === void 0 ? void 0 : _threeDSMethodData$pa4.threeDSServerTransID) && (threeDSMethodData === null || threeDSMethodData === void 0 || (_threeDSMethodData$pa5 = threeDSMethodData.pay_info) === null || _threeDSMethodData$pa5 === void 0 ? void 0 : _threeDSMethodData$pa5.threeDSCompInd)) return defaultReturnParams;
		if (!(threeDSMethodData === null || threeDSMethodData === void 0 ? void 0 : threeDSMethodData.pay_info.acsURL) || typeof (threeDSMethodData === null || threeDSMethodData === void 0 || (_threeDSMethodData$pa6 = threeDSMethodData.pay_info) === null || _threeDSMethodData$pa6 === void 0 ? void 0 : _threeDSMethodData$pa6.acsURL) !== "string") return defaultReturnParams;
		const displayBox = document.getElementById("threeds-container");
		displayBox.innerHTML = "";
		let iframe = document.createElement("iframe");
		iframe.classList.add("hidden_TDS_From");
		iframe.name = "threeDSMethodIframe";
		displayBox.appendChild(iframe);
		var form = document.createElement("form");
		form.classList.add("hidden_TDS_From");
		form.id = "threeDSMethodForm";
		form.type = "hidden";
		displayBox.appendChild(form);
		var input = document.createElement("input");
		input.id = "threeDSMethodData";
		input.name = "threeDSMethodData";
		input.type = "hidden";
		input.value = threeDSMethodData.pay_info.paReq;
		form.appendChild(input);
		form.action = threeDSMethodData.pay_info.acsURL;
		form.target = iframe.name;
		form.method = "post";
		form.submit();
		let timer = null;
		return new Promise((res, rej) => {
			var _threeDSMethodData$pa7;
			const handleMessage = (event) => {
				if (event.origin.indexOf(postmessageUrl) !== -1 || event.origin.indexOf("securesuite") !== -1) {
					if (typeof event.data.threeDSServerTransID == "string") {
						setHistoryLog({
							msg: "第三步: message 返回 threeDSServerTransID",
							time: getCurrentTime(),
							threeDSServerTransID: event.data.threeDSServerTransID
						});
						if (timer) clearTimeout(timer);
						window.removeEventListener("message", handleMessage);
						res({
							threeDSServerTransID: event.data.threeDSServerTransID,
							threeDSCompInd: "Y"
						});
					}
				}
			};
			timer = setTimeout(() => {
				window.removeEventListener("message", handleMessage);
				res(defaultReturnParams);
				log({
					msg: "第三步: 10秒超时则走N逻辑",
					data: threeDSMethodData
				});
			}, (threeDSMethodData === null || threeDSMethodData === void 0 || (_threeDSMethodData$pa7 = threeDSMethodData.pay_info) === null || _threeDSMethodData$pa7 === void 0 ? void 0 : _threeDSMethodData$pa7.tdsMethodTimeoutMS) || 1e4);
			window.addEventListener("message", handleMessage, false);
			activeCleanup = () => {
				window.removeEventListener("message", handleMessage);
				if (timer) clearTimeout(timer);
				rej(0);
			};
		});
	});
	return function createThreeDSMethodIframe(_x9, _x10) {
		return _ref4.apply(this, arguments);
	};
}();
/**
* @title: 步骤4
* @description:
* @param {any} param1
* @return {*}
* @Author: Wzw
* @Date: 2022-10-18 10:43
*/
const checkTDSAuth = function() {
	var _ref5 = _asyncToGenerator(function* (step2, step3, options) {
		const { callback, isCancelled } = options || {};
		try {
			const { pay_number, order_id, pay_info, amount, notifyURL } = step2;
			const { threeDSServerTransID, threeDSCompInd } = step3;
			var currentData = /* @__PURE__ */ new Date();
			let isPre = false;
			if (REACT_APP_API_ENV === "pre" && pay_info.check_tds_auth.card_name === "aa bb") isPre = true;
			const request_unique_idempotency_token = getUniqueIdempotencyToken();
			setHistoryLog({
				msg: "步骤4开始: 调用tds_auth_pay接口",
				time: getCurrentTime(),
				order_id,
				pay_number,
				request_unique_idempotency_token
			});
			let { data } = yield request.getRequest().post("/h5/pay/order/mw-3ds-pay/v2/tds_auth_pay", {
				order_id,
				pay_number,
				request_unique_idempotency_token,
				mw_data: {
					accessToken: pay_info.check_tds_auth.access_token,
					method: "checkTDSAuth",
					cardID: pay_info.check_tds_auth.card_id,
					paymentCardExpiry: pay_info.check_tds_auth.card_expiry,
					paymentCardName: pay_info.check_tds_auth.card_name,
					customerName: pay_info.check_tds_auth.card_name,
					transactionAmount: amount,
					transactionCurrency: paymentInfo.transactionInfo.transactionCurrency,
					transactionProduct: pay_info.check_tds_auth.product_name,
					browserAcceptHeader: "*/*",
					browserColorDepth: screen.colorDepth,
					browserJavaEnabled: navigator.javaEnabled(),
					browserJavascriptEnabled: true,
					browserLanguage: navigator.language,
					browserScreenHeight: screen.height,
					browserScreenWidth: screen.width,
					browserTZ: currentData.getTimezoneOffset(),
					browserUserAgent: navigator.userAgent,
					purchaseDate: "20220420165834",
					billAddrCity: paymentInfo.billingAddress.billAddrCity,
					billAddrCountry: paymentInfo.billingAddress.billAddrCountry,
					billAddrLine1: paymentInfo.billingAddress.billAddrLine1,
					billAddrPostCode: paymentInfo.billingAddress.billAddrPostCode,
					billAddrState: paymentInfo.billingAddress.billAddrState,
					threeDSCompInd: isPre ? "" : threeDSCompInd || "N",
					threeDSServerTransID: isPre ? "" : threeDSServerTransID,
					threeDSRequestorAuthenticationInd: "01",
					threeDSRequestorURL: window.location.href,
					notifyURL
				}
			});
			setHistoryLog({
				msg: "步骤4完成: tds_auth_pay接口返回",
				time: getCurrentTime(),
				hasStep4: !!data
			});
			if (!data) return null;
			return data;
		} catch (err) {
			setHistoryLog({
				msg: "步骤4异常",
				time: getCurrentTime(),
				errorCode: err === null || err === void 0 ? void 0 : err.code
			});
			log({
				msg: err,
				data: paymentData
			});
			if (isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) return 0;
			if ((err === null || err === void 0 ? void 0 : err.code) === 700500) throw err;
			PisellToast({
				content: (err === null || err === void 0 ? void 0 : err.message) || "",
				duration: 1e3 * 2
			});
			callback === null || callback === void 0 || callback({ key: "hideModal" });
			closeIframe();
			return 0;
		}
	});
	return function checkTDSAuth(_x11, _x12, _x13) {
		return _ref5.apply(this, arguments);
	};
}();
/**
* @title: 步骤5
* @description:  监听
* @param {any} challengeData
* @return {*}
* @Author: Wzw
* @Date: 2022-10-18 10:45
*/
const createChallengeIframe = (challengeData, callback) => {
	const displayBox = document.getElementById("threeds-container");
	displayBox.innerHTML = "";
	let iframe = document.createElement("iframe");
	iframe.classList.add("tdsv2challengeIframe");
	iframe.name = "challengeIframe";
	iframe.id = "3dsv2challengeIframe";
	displayBox.appendChild(iframe);
	var form = document.createElement("form");
	form.classList.add("hidden_TDS_From");
	form.id = "3dsv2challengeForm";
	displayBox.appendChild(form);
	var input = document.createElement("input");
	input.id = "creq";
	input.name = "creq";
	input.value = challengeData.challengeData;
	input.type = "hidden";
	form.appendChild(input);
	form.action = challengeData.acsURL;
	form.target = iframe.name;
	form.method = "post";
	form.submit();
	iframe.onload = function() {};
	return new Promise((res, rej) => {
		let timer = null;
		const handleMessage = (event) => {
			if (event.origin.indexOf(postmessageUrl) !== -1 || event.origin.indexOf("securesuite") !== -1) {
				if (typeof event.data.cres == "string") {
					if (timer) clearTimeout(timer);
					window.removeEventListener("message", handleMessage);
					res(event.data.cres);
					closeIframe();
				}
			}
		};
		timer = setTimeout(() => {
			log({
				msg: "第五步: 60秒超时则走N逻辑",
				data: challengeData
			});
			window.removeEventListener("message", handleMessage);
			rej("time out");
		}, 120 * 1e3);
		window.addEventListener("message", handleMessage, false);
		activeCleanup = () => {
			window.removeEventListener("message", handleMessage);
			if (timer) clearTimeout(timer);
			rej(0);
		};
	});
};
/**
* @title: 步骤6
* @description:
* @param {any} cres
* @return {*}
* @Author: Wzw
* @Date: 2022-10-18 10:48
*/
const checkPARes = function() {
	var _ref6 = _asyncToGenerator(function* (step2, step4, step5) {
		const { pay_number, order_id, pay_info, amount } = step2;
		const { tdsPayKey, tdsPayToken } = step4;
		const cres = step5;
		const request_unique_idempotency_token = getUniqueIdempotencyToken();
		let { data } = yield request.getRequest().post("/h5/pay/order/mw-3ds-pay/v2/check_pares", {
			order_id,
			pay_number,
			request_unique_idempotency_token,
			mw_data: {
				transactionProduct: pay_info.check_tds_auth.product_name,
				cres,
				accessToken: pay_info.check_tds_auth.access_token,
				tdsPayKey,
				tdsPayToken,
				paymentCardName: pay_info.check_tds_auth.card_name,
				transactionAmount: amount,
				card_id: pay_info.check_tds_auth.card_id
			}
		});
		return data;
	});
	return function checkPARes(_x14, _x15, _x16) {
		return _ref6.apply(this, arguments);
	};
}();
/**
* @title: 支付结束
* @description:
* @return {*}
* @Author: Wzw
* @Date: 2022-10-18 14:28
*/
const paymentEnd = (props, callback) => {
	const { status } = props;
	callback({
		key: status,
		data: props
	});
	if (status !== "success") log({
		msg: "支付失败",
		data: paymentData
	});
};
const closeIframe = () => {
	let dom = document.querySelector(".tdsv2challengeIframe");
	if (dom) dom.classList.add("tdsv2challengeIframeClose");
};
//#endregion
export { cancelCurrentPayment, preCheckEnrollment, startPayment };
