require("../../../../_virtual/_rolldown/runtime.js");
const require_defineProperty = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/defineProperty.js");
const require_objectSpread2 = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_const = require("../../const.js");
const require_helper = require("../../helper.js");
const require_payLog = require("../../utils/payLog.js");
const require_types = require("../types.js");
const require_service = require("../service.js");
let _pisell_utils = require("@pisell/utils");
//#region src/components/eftposPay/aggregatePayment/utils/payment.ts
/**
* 聚合支付方法类
* 核心点：
* 1.发起支付/退款，在十秒钟后发起轮询操作，两个接口谁先返回成功用谁的结果，如果返回的失败是存在明确code信息的则全部失败
* 2.轮询操作总查询时间2分钟，超时直接失败，单次轮询超时时间5秒，超时直接abort本次请求，间隔两秒后发起新的请求
* 3.最终成功或者失败都需要把定时器给清理掉，并将未完成的接口abort掉
*/
const sanitizePaymentLogContent = (content) => {
	var _content$params;
	if (!content || typeof content !== "object") return content;
	if (!((_content$params = content.params) === null || _content$params === void 0 || (_content$params = _content$params.eftpos) === null || _content$params === void 0 ? void 0 : _content$params.pay_param_base64)) return content;
	const clonedContent = require_helper.cloneDeep(content);
	delete clonedContent.params.eftpos.pay_param_base64;
	return clonedContent;
};
const addPaymentLog = ({ title, content }) => {
	require_payLog.default.log(title, sanitizePaymentLogContent(content));
};
const paymentLog = { addLog: addPaymentLog };
var PaymentMethod = class {
	constructor(options) {
		require_defineProperty._defineProperty(this, "initOptions", void 0);
		require_defineProperty._defineProperty(this, "paymentNum", void 0);
		require_defineProperty._defineProperty(this, "orderId", void 0);
		require_defineProperty._defineProperty(this, "callback", void 0);
		require_defineProperty._defineProperty(this, "shouldContinue", void 0);
		require_defineProperty._defineProperty(this, "config", {});
		require_defineProperty._defineProperty(this, "controller", null);
		require_defineProperty._defineProperty(this, "queryController", null);
		require_defineProperty._defineProperty(this, "queryStartTimer", null);
		require_defineProperty._defineProperty(this, "globalTimeoutTimer", null);
		require_defineProperty._defineProperty(this, "requestTimeoutTimer", null);
		require_defineProperty._defineProperty(this, "queryIntervalTimer", null);
		require_defineProperty._defineProperty(this, "isFinished", false);
		require_defineProperty._defineProperty(this, "isQuerying", false);
		require_defineProperty._defineProperty(this, "currentActionType", null);
		require_defineProperty._defineProperty(this, "currentQueryId", "");
		require_defineProperty._defineProperty(this, "currentRunId", "");
		require_defineProperty._defineProperty(this, "currentQueryApi", null);
		this.initOptions = options;
		this.paymentNum = options.paymentNum;
		this.orderId = options.orderId;
		this.callback = options.callback;
		this.shouldContinue = options.shouldContinue || (() => true);
		this.config = options.config || {};
		require_payLog.default.setContext({
			transactionNumber: this.paymentNum,
			extra: { paymentCode: (options === null || options === void 0 ? void 0 : options.paymentCode) || "" }
		});
		addPaymentLog({
			title: "聚合支付初始化",
			content: {
				paymentNum: this.paymentNum,
				paymentCode: (options === null || options === void 0 ? void 0 : options.paymentCode) || ""
			}
		});
	}
	/**
	* 判断请求是否需要等待轮询结果
	* 1. 有明确错误code且不是超时和支付超时，则直接失败
	* @param code 错误码
	*/
	isBusinessFailed(res) {
		var _res$data;
		const { external_unified_status, response_code } = (res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.external_unified_response) || {};
		return `${res === null || res === void 0 ? void 0 : res.code}` === "200" && external_unified_status === require_types.EPaymentStatus.Failed && response_code !== require_const.PayStatus.Timeout && response_code !== require_const.PayStatus.PayTimeout;
	}
	/**
	* 判断业务是否成功
	*/
	isBusinessSuccess(res) {
		var _res$data2;
		const { external_unified_status } = (res === null || res === void 0 || (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.external_unified_response) || {};
		return `${res === null || res === void 0 ? void 0 : res.code}` === "200" && external_unified_status === require_types.EPaymentStatus.Success;
	}
	/**
	* 清理定时器和请求控制器
	*/
	cleanupTimersAndControllers() {
		if (this.controller) {
			this.controller.abort();
			this.controller = null;
		}
		if (this.queryController) {
			this.queryController.abort();
			this.queryController = null;
		}
		if (this.queryStartTimer) {
			clearTimeout(this.queryStartTimer);
			this.queryStartTimer = null;
		}
		if (this.globalTimeoutTimer) {
			clearTimeout(this.globalTimeoutTimer);
			this.globalTimeoutTimer = null;
		}
		if (this.requestTimeoutTimer) {
			clearTimeout(this.requestTimeoutTimer);
			this.requestTimeoutTimer = null;
		}
		if (this.queryIntervalTimer) {
			clearTimeout(this.queryIntervalTimer);
			this.queryIntervalTimer = null;
		}
	}
	/**
	* 清理资源并重置状态
	* @param markAsFinished 是否标记为已完成（true: 操作完成; false: 准备新操作）
	*/
	clean(markAsFinished = false) {
		console.log("🧹 清理资源", { markAsFinished });
		this.cleanupTimersAndControllers();
		this.isQuerying = false;
		this.isFinished = markAsFinished;
		this.currentQueryApi = null;
		this.currentActionType = null;
	}
	/**
	* 开始新的操作流程（统一的流程初始化）
	* @param actionType 操作类型
	* @returns 本次流程的唯一ID
	*/
	startNewOperation(actionType) {
		const runId = require_helper.getUuid();
		this.currentRunId = runId;
		paymentLog.addLog({
			title: `触发新的操作：${actionType}`,
			content: {
				actionType,
				runId
			}
		});
		this.clean(false);
		this.currentActionType = actionType;
		return runId;
	}
	/**
	* 处理操作过程
	*/
	handleOperationProcess(res) {
		if (!this.currentActionType) return;
		const actionType = this.currentActionType;
		try {
			this.callback(this, {
				status: require_types.EPaymentStatus.Processing,
				actionType,
				data: res
			});
		} catch (error) {
			console.error("⚠️ 回调执行出错:", error);
			paymentLog.addLog({
				title: "回调执行出错",
				content: error
			});
		}
	}
	/**
	* 处理成功结果
	*/
	handleOperationSuccess(res) {
		if (this.isFinished || !this.shouldContinue() || !this.currentActionType) {
			paymentLog.addLog({
				title: "操作结果：已完成或不应继续处理，忽略操作成功结果",
				content: {
					actionType: this.currentActionType,
					res
				}
			});
			return;
		}
		const actionType = this.currentActionType;
		paymentLog.addLog({
			title: "操作结果：成功",
			content: {
				actionType,
				res
			}
		});
		this.clean(true);
		try {
			this.callback(this, {
				status: require_types.EPaymentStatus.Success,
				actionType,
				data: res
			});
		} catch (error) {
			console.error("⚠️ 回调执行出错:", error);
			paymentLog.addLog({
				title: "回调执行出错",
				content: error
			});
		}
	}
	/**
	* 处理错误（最终失败）
	* @param error 错误信息
	*/
	handleOperationError(error) {
		if (this.isFinished || !this.shouldContinue() || !this.currentActionType) {
			console.log(`⚠️ 已完成或不应继续处理，忽略操作错误`);
			return;
		}
		const actionType = this.currentActionType;
		paymentLog.addLog({
			title: "操作结果：失败",
			content: {
				actionType,
				error
			}
		});
		this.clean(true);
		try {
			this.callback(this, {
				status: require_types.EPaymentStatus.Failed,
				actionType,
				data: error
			});
		} catch (err) {
			console.error("⚠️ 回调执行出错:", err);
			paymentLog.addLog({
				title: "回调执行出错",
				content: err
			});
		}
	}
	/**
	* 处理接口响应
	*/
	handleResponse(res) {
		var _res$data3;
		if (!this.currentActionType) return;
		let needContinue = true;
		const { external_unified_status } = (res === null || res === void 0 || (_res$data3 = res.data) === null || _res$data3 === void 0 ? void 0 : _res$data3.external_unified_response) || {};
		switch (external_unified_status) {
			case require_types.EPaymentStatus.Success:
				this.handleOperationSuccess(res);
				needContinue = false;
				break;
			case require_types.EPaymentStatus.Failed:
				this.handleOperationError(res);
				needContinue = false;
				break;
			case require_types.EPaymentStatus.Processing:
			default:
				this.handleOperationProcess(res);
				needContinue = true;
				break;
		}
		return needContinue;
	}
	/**
	* 创建超时 Promise
	*/
	createTimeoutPromise(timeoutMs) {
		return new Promise((_, reject) => {
			this.requestTimeoutTimer = setTimeout(() => {
				console.log(`⏱️ 单次查询超时（${timeoutMs / 1e3}秒），强制终止`);
				if (this.queryController) this.queryController.abort();
				reject(/* @__PURE__ */ new Error("REQUEST_TIMEOUT"));
			}, timeoutMs);
		});
	}
	/**
	* 单次查询请求
	*/
	performQuery(actionType) {
		var _this = this;
		return require_asyncToGenerator._asyncToGenerator(function* () {
			if (_this.isFinished || !_this.shouldContinue()) {
				paymentLog.addLog({ title: "查询前置校验：已完成或不应继续处理，取消查询" });
				return;
			}
			if (!_this.currentQueryApi) {
				paymentLog.addLog({ title: "查询API未设置，取消查询" });
				return;
			}
			if (_this.queryController) {
				_this.queryController.abort();
				_this.queryController = null;
			}
			if (_this.requestTimeoutTimer) {
				clearTimeout(_this.requestTimeoutTimer);
				_this.requestTimeoutTimer = null;
			}
			const queryId = require_helper.getUuid();
			_this.currentQueryId = queryId;
			_this.queryController = new AbortController();
			const { signal } = _this.queryController;
			paymentLog.addLog({ title: "查询轮询：开始单次查询" });
			try {
				var _this$initOptions, _res$data4;
				const res = yield Promise.race([_this.currentQueryApi({
					order_id: _this.orderId,
					unique_payment_number: _this.paymentNum,
					payment_code: (_this$initOptions = _this.initOptions) === null || _this$initOptions === void 0 ? void 0 : _this$initOptions.paymentCode,
					request_version: queryId,
					is_force_request_api: 1
				}, { signal }), _this.createTimeoutPromise(require_types.REQUEST_TIMEOUT)]);
				paymentLog.addLog({
					title: "查询轮询：单次查询返回",
					content: {
						actionType,
						res
					}
				});
				if (_this.requestTimeoutTimer) {
					clearTimeout(_this.requestTimeoutTimer);
					_this.requestTimeoutTimer = null;
				}
				if ((res === null || res === void 0 || (_res$data4 = res.data) === null || _res$data4 === void 0 ? void 0 : _res$data4.request_version) !== _this.currentQueryId) {
					paymentLog.addLog({ title: "查询轮询结果：过期的查询响应，忽略" });
					return;
				}
				if (_this.isFinished || !_this.shouldContinue()) {
					paymentLog.addLog({ title: "查询轮询结果：已完成或不应继续处理" });
					return;
				}
				if (`${res === null || res === void 0 ? void 0 : res.code}` !== "200") {
					paymentLog.addLog({ title: "查询轮询结果：查询返回失败，code非200" });
					_this.handleOperationError(res);
					return;
				}
				if (_this.isBusinessSuccess(res)) {
					paymentLog.addLog({ title: "查询轮询结果：查询成功" });
					if (_this.handleResponse(res)) _this.scheduleNextQuery(actionType);
					return;
				}
				if (_this.isBusinessFailed(res)) {
					paymentLog.addLog({
						title: "查询轮询结果：有明确错误code，停止轮询",
						content: res
					});
					_this.handleOperationError(res);
				} else {
					paymentLog.addLog({
						title: "查询轮询结果：交易进行中，继续轮询",
						content: res
					});
					_this.handleOperationProcess(res);
					_this.scheduleNextQuery(actionType);
				}
			} catch (error) {
				if (_this.requestTimeoutTimer) {
					clearTimeout(_this.requestTimeoutTimer);
					_this.requestTimeoutTimer = null;
				}
				if (queryId !== _this.currentQueryId) {
					paymentLog.addLog({ title: "查询轮询结果：error-过期的查询异常，忽略" });
					return;
				}
				if (_this.isFinished || !_this.shouldContinue()) return;
				if ((error === null || error === void 0 ? void 0 : error.name) === "AbortError" || (error === null || error === void 0 ? void 0 : error.message) === "REQUEST_TIMEOUT") {
					paymentLog.addLog({ title: "查询轮询结果：error-请求被取消或超时，继续轮询" });
					_this.scheduleNextQuery(actionType);
					return;
				}
				paymentLog.addLog({
					title: "查询轮询结果：error-有明确错误code，停止轮询",
					content: error
				});
				_this.handleOperationError(error);
			}
		})();
	}
	/**
	* 安排下一次查询
	*/
	scheduleNextQuery(actionType) {
		var _this$config;
		if (this.isFinished || !this.shouldContinue()) return;
		if (this.queryIntervalTimer) clearTimeout(this.queryIntervalTimer);
		if (((_this$config = this.config) === null || _this$config === void 0 ? void 0 : _this$config.hasQueryInterval) === false) {
			paymentLog.addLog({
				title: "查询轮询：立即安排下一次查询",
				content: { actionType }
			});
			this.performQuery(actionType);
		} else this.queryIntervalTimer = setTimeout(() => {
			paymentLog.addLog({
				title: "查询轮询：安排下一次查询",
				content: { actionType }
			});
			this.performQuery(actionType);
		}, require_types.QUERY_INTERVAL);
	}
	/**
	* 开始轮询
	*/
	startQuery(actionType) {
		var _this$config2;
		if (this.isFinished || !this.shouldContinue() || this.isQuerying) return;
		this.isQuerying = true;
		paymentLog.addLog({
			title: "开始轮询",
			content: { actionType }
		});
		const _globalQueryTimeout = ((_this$config2 = this.config) === null || _this$config2 === void 0 ? void 0 : _this$config2.globalQueryTimeout) || 12e4;
		this.globalTimeoutTimer = setTimeout(() => {
			if (this.isFinished) return;
			paymentLog.addLog({
				title: `轮询全局超时（${_globalQueryTimeout / 1e3}秒），终止所有请求`,
				content: { actionType }
			});
			this.handleOperationError({
				code: "200",
				data: { external_unified_response: {
					external_unified_status: require_types.EPaymentStatus.Failed,
					response_code: require_const.PayStatus.Timeout,
					message: (_pisell_utils.locales === null || _pisell_utils.locales === void 0 ? void 0 : _pisell_utils.locales.getText("page.eftpos-pay.text.transaction.fail.timeout")) || "Transaction timeout."
				} }
			});
		}, _globalQueryTimeout);
		this.performQuery(actionType);
	}
	/**
	* 获取操作API和查询API
	*/
	getActionApi(actionType) {
		let actionApi = null;
		let queryApi = null;
		switch (actionType) {
			case require_types.ActionType.Pay:
				actionApi = require_service.AGPTPayApi;
				queryApi = require_service.AGPTQueryApi;
				break;
			case require_types.ActionType.PayAction:
				actionApi = require_service.AGPTActionApi;
				queryApi = require_service.AGPTQueryApi;
				break;
			case require_types.ActionType.PayQuery:
				queryApi = require_service.AGPTQueryApi;
				break;
			case require_types.ActionType.Refund:
				actionApi = require_service.AGPTRefundApi;
				queryApi = require_service.AGPTRefundQueryApi;
				break;
			case require_types.ActionType.RefundAction:
				actionApi = require_service.AGPTRefundActionApi;
				queryApi = require_service.AGPTRefundQueryApi;
				break;
			case require_types.ActionType.RefundQuery:
				queryApi = require_service.AGPTRefundQueryApi;
				break;
		}
		return {
			actionApi,
			queryApi
		};
	}
	/**
	* 执行纯查询操作（不需要先调用支付/退款接口）
	*/
	runQuery(options) {
		var _this2 = this;
		return require_asyncToGenerator._asyncToGenerator(function* () {
			const { actionType } = options;
			_this2.startNewOperation(actionType);
			const { queryApi } = _this2.getActionApi(actionType);
			if (!queryApi) {
				const error = /* @__PURE__ */ new Error(`${actionType}查询接口不存在`);
				_this2.handleOperationError(error);
				return;
			}
			_this2.currentQueryApi = queryApi;
			paymentLog.addLog({ title: `开始${actionType}查询轮询` });
			_this2.startQuery(actionType);
		})();
	}
	/**
	* 执行操作的核心方法
	*/
	run(runOptions) {
		var _this3 = this;
		return require_asyncToGenerator._asyncToGenerator(function* () {
			const { actionType, params, config } = runOptions;
			const runId = _this3.startNewOperation(actionType);
			paymentLog.addLog({
				title: "请求参数",
				content: { params }
			});
			const { actionApi, queryApi } = _this3.getActionApi(actionType);
			if (!actionApi) {
				const error = /* @__PURE__ */ new Error(`${actionType}接口不存在`);
				_this3.handleOperationError(error);
				return;
			}
			_this3.currentQueryApi = queryApi;
			if (queryApi !== null) _this3.queryStartTimer = setTimeout(() => {
				paymentLog.addLog({
					title: "操作后10秒开始轮询",
					content: { actionType }
				});
				_this3.startQuery(actionType);
			}, require_types.QUERY_START_DELAY);
			_this3.controller = new AbortController();
			const { signal } = _this3.controller;
			const _query = (_status, _title, _content) => {
				paymentLog.addLog({
					title: _title,
					content: _content
				});
				if (_this3.queryStartTimer) {
					clearTimeout(_this3.queryStartTimer);
					_this3.queryStartTimer = null;
				}
				_this3.startQuery(actionType);
			};
			try {
				var _res$data5;
				paymentLog.addLog({
					title: `发起${actionType}请求`,
					content: {
						actionType,
						params
					}
				});
				const res = yield actionApi(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, params), {}, { request_version: runId }), { signal });
				paymentLog.addLog({
					title: "请求返回",
					content: {
						params,
						actionType,
						res
					}
				});
				if (runId != (res === null || res === void 0 || (_res$data5 = res.data) === null || _res$data5 === void 0 ? void 0 : _res$data5.request_version)) {
					paymentLog.addLog({
						title: "响应过期，忽略",
						content: { actionType }
					});
					return;
				}
				if (_this3.isFinished || !_this3.shouldContinue()) {
					paymentLog.addLog({
						title: "返回时已完成或不应继续处理",
						content: { actionType }
					});
					return;
				}
				if (`${res === null || res === void 0 ? void 0 : res.code}` !== "200") {
					paymentLog.addLog({ title: `${actionType}接口返回失败，code非200` });
					_this3.handleOperationError(res);
					return;
				}
				if (_this3.isBusinessSuccess(res)) {
					paymentLog.addLog({
						title: `${actionType}接口成功`,
						content: {
							actionType,
							res
						}
					});
					if (_this3.handleResponse(res)) _query("success", `${actionType}接口返回processing，开始轮询`);
					return;
				}
				if (_this3.isBusinessFailed(res)) {
					paymentLog.addLog({
						title: `${actionType}接口返回失败`,
						content: {
							actionType,
							res
						}
					});
					_this3.handleOperationError(res);
				} else {
					_this3.handleOperationProcess(res);
					_query("failed", `${actionType}超时或无明确错误，开始轮询`, {
						actionType,
						res
					});
				}
			} catch (error) {
				if (runId !== _this3.currentRunId) {
					paymentLog.addLog({
						title: "响应过期，忽略",
						content: { actionType }
					});
					return;
				}
				if (_this3.isFinished || !_this3.shouldContinue()) {
					paymentLog.addLog({
						title: "异常时已完成或不应继续处理",
						content: { actionType }
					});
					return;
				}
				_query("failed", `${actionType}接口异常，开始轮询`, {
					actionType,
					error
				});
			}
		})();
	}
	/**
	* 执行操作
	*/
	runAction(actionOptions) {
		var _this4 = this;
		return require_asyncToGenerator._asyncToGenerator(function* () {
			const { actionType, params, config } = actionOptions;
			console.log("runAction_actionOptions", actionOptions);
			const runActionId = _this4.startNewOperation(actionType);
			paymentLog.addLog({
				title: `${actionType}操作请求参数`,
				content: {
					actionType,
					params
				}
			});
			const { actionApi, queryApi } = _this4.getActionApi(actionType);
			if (!actionApi) {
				const error = /* @__PURE__ */ new Error(`${actionType}操作接口不存在`);
				_this4.handleOperationError(error);
				return;
			}
			_this4.currentQueryApi = queryApi;
			_this4.controller = new AbortController();
			const { signal } = _this4.controller;
			try {
				var _res$data6;
				const res = yield actionApi(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, params || {}), {}, { request_version: runActionId }), { signal });
				if (_this4.isFinished || !_this4.shouldContinue()) {
					paymentLog.addLog({
						title: "Action返回时已完成或不应继续处理，忽略",
						content: { actionType }
					});
					return;
				}
				if (runActionId !== (res === null || res === void 0 || (_res$data6 = res.data) === null || _res$data6 === void 0 ? void 0 : _res$data6.request_version)) {
					paymentLog.addLog({
						title: "Action响应过期，忽略",
						content: { actionType }
					});
					return;
				}
				if (config === null || config === void 0 ? void 0 : config.needResponse) {
					_this4.handleResponse(res);
					return;
				}
				paymentLog.addLog({
					title: "Action请求返回，开始轮询",
					content: { actionType }
				});
				_this4.startQuery(actionType);
			} catch (error) {
				if (_this4.isFinished || !_this4.shouldContinue()) {
					paymentLog.addLog({
						title: "Action异常时已完成或不应继续处理，忽略",
						content: { actionType }
					});
					return;
				}
				if (runActionId !== _this4.currentRunId) {
					paymentLog.addLog({
						title: "Action响应过期，忽略",
						content: { actionType }
					});
					return;
				}
				paymentLog.addLog({
					title: "Action请求异常，开始轮询",
					content: {
						actionType,
						error
					}
				});
				_this4.startQuery(actionType);
			}
		})();
	}
	/**
	* 支付
	* @param params 支付参数
	*/
	pay(params, config) {
		this.run({
			actionType: require_types.ActionType.Pay,
			params,
			config
		});
	}
	/**
	* 支付取消
	* @param params 取消参数
	*/
	payAction(params, config) {
		this.runAction({
			actionType: require_types.ActionType.PayAction,
			params,
			config
		});
	}
	/**
	* 退款
	* @param params 退款参数
	*/
	refund(params, config) {
		this.run({
			actionType: require_types.ActionType.Refund,
			params,
			config
		});
	}
	/**
	* 退款取消
	* @param params 取消参数
	*/
	refundAction(params, config) {
		this.runAction({
			actionType: require_types.ActionType.RefundAction,
			params,
			config
		});
	}
	/**
	* 支付查询（直接查询，带2分钟超时和轮询机制）
	*/
	payQuery() {
		this.runQuery({ actionType: require_types.ActionType.PayQuery });
	}
	/**
	* 退款查询（直接查询，带2分钟超时和轮询机制）
	*/
	refundQuery() {
		this.runQuery({ actionType: require_types.ActionType.RefundQuery });
	}
	/**
	* 停止操作，后续依然可以重新发起操作
	*/
	stop() {
		paymentLog.addLog({
			title: "停止操作",
			content: { actionType: this.currentActionType }
		});
		this.clean(true);
	}
	/**
	* 销毁实例（完全清理并上传日志）
	* 注意：销毁后实例不可再使用
	*/
	destroy() {
		paymentLog.addLog({ title: "支付步骤结束，销毁实例" });
		this.clean(true);
	}
};
//#endregion
exports.default = PaymentMethod;
