require("../../../../_virtual/_rolldown/runtime.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_const = require("../../const.js");
const require_const$1 = require("../const.js");
const require_index = require("../../store/index.js");
const require_hooks = require("../../hooks.js");
const require_payLog = require("../../utils/payLog.js");
let react = require("react");
let _pisell_utils = require("@pisell/utils");
//#region src/components/eftposPay/linkly/hooks/useTimeQuery.ts
const GlobalTimeout = 1e3 * 60 * 2;
const RequestTimeout = 1e3 * 5;
const QUERY_INTERVAL = 1e3 * 2;
var EErrorType = /* @__PURE__ */ function(EErrorType) {
	EErrorType["AbortError"] = "AbortError";
	/** 请求被新的请求取代 */
	EErrorType["InvalidRequestError"] = "InvalidRequestError";
	/** 需要刷新 */
	EErrorType["NeedRefreshError"] = "NeedRefreshError";
	/** 请求已达到全局超时时间 */
	EErrorType["GlobalTimeoutError"] = "GlobalTimeoutError";
	return EErrorType;
}(EErrorType || {});
const useTimeResultQuery = (api, resultCheck, handleLinklySuccess) => {
	const dispatch = require_index.useDispatch();
	const { numRef, modeRef, deviceRef } = require_hooks.useStoreRef();
	const failRef = (0, react.useRef)(require_hooks.useFail(0));
	const isPay = modeRef.current === require_const.ModeEnum.Pay || modeRef.current === require_const.ModeEnum.FullPay;
	const controllerRef = (0, react.useRef)(null);
	const requestTimeoutIdRef = (0, react.useRef)(null);
	const globalTimeoutIdRef = (0, react.useRef)(null);
	const isRequestCanceledRef = (0, react.useRef)(false);
	const startTimeRef = (0, react.useRef)(null);
	const isQueryFinishedRef = (0, react.useRef)(true);
	const queryIntervalTimerRef = (0, react.useRef)(null);
	const _resultQuery = function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* () {
			var _ref;
			if (controllerRef.current) {
				controllerRef.current.abort();
				controllerRef.current = null;
			}
			if (requestTimeoutIdRef.current) {
				clearTimeout(requestTimeoutIdRef.current);
				requestTimeoutIdRef.current = null;
			}
			controllerRef.current = new AbortController();
			const { signal } = controllerRef.current;
			isRequestCanceledRef.current = false;
			requestTimeoutIdRef.current = setTimeout(() => {
				var _controllerRef$curren;
				require_payLog.default.log("Linkly轮询：单次请求超时");
				(_controllerRef$curren = controllerRef.current) === null || _controllerRef$curren === void 0 || _controllerRef$curren.abort();
				isRequestCanceledRef.current = true;
			}, RequestTimeout);
			(isPay ? api.linklyPayQuery : api.linklyRefundQuery)({
				pinpad_id: deviceRef === null || deviceRef === void 0 || (_ref = deviceRef.current) === null || _ref === void 0 || (_ref = _ref.metadata) === null || _ref === void 0 ? void 0 : _ref.linkly_pinpad_id,
				session_id: numRef.current
			}, { signal }).then((result) => {
				console.log("Success: 请求成功", result);
				if (checkNeedToHandleResult()) {
					console.log("Success: 全局超时或不需要处理结果，终止查询");
					return;
				}
				isQueryFinishedRef.current = true;
				const data = (result === null || result === void 0 ? void 0 : result.data) || {};
				if (data.status == 1) {
					require_payLog.default.log("Linkly轮询：交易成功");
					reset();
					handleLinklySuccess(result);
					return;
				}
				if ((data === null || data === void 0 ? void 0 : data.status) == 0 && (data === null || data === void 0 ? void 0 : data.signature_flag) != 1) {
					require_payLog.default.log("Linkly轮询：继续查询", { data });
					isQueryFinishedRef.current = false;
					queryIntervalTimerRef.current = setTimeout(() => {
						_resultQuery();
					}, QUERY_INTERVAL);
					return;
				}
				if (data.status < 0) {
					var _failRef$current;
					require_payLog.default.log("Linkly轮询：交易失败", { data });
					reset();
					result.code = require_const.PayStatus.Unknown;
					(_failRef$current = failRef.current) === null || _failRef$current === void 0 || _failRef$current.call(failRef, result, false);
					return;
				}
				if (data.signature_flag == 1) {
					require_payLog.default.log("Linkly轮询：需要签名", { data });
					reset();
					gotoSignature();
					return;
				}
			}).catch((error) => {
				var _failRef$current2;
				console.log("Error: 请求失败", error);
				if (checkNeedToHandleResult()) {
					console.log("Error: 全局超时或不需要处理结果，终止查询");
					return;
				}
				isQueryFinishedRef.current = true;
				if ((error === null || error === void 0 ? void 0 : error.name) === EErrorType.AbortError || isRequestCanceledRef.current) {
					require_payLog.default.log("Linkly轮询：请求被取消，继续查询");
					isQueryFinishedRef.current = false;
					queryIntervalTimerRef.current = setTimeout(() => {
						_resultQuery();
					}, QUERY_INTERVAL);
					return;
				}
				if (!(error === null || error === void 0 ? void 0 : error.code) || `${error.code}` === require_const.PayStatus.Timeout) {
					require_payLog.default.log("Linkly轮询：网关报错，继续查询");
					isQueryFinishedRef.current = false;
					queryIntervalTimerRef.current = setTimeout(() => {
						_resultQuery();
					}, QUERY_INTERVAL);
					return;
				}
				require_payLog.default.log("Linkly轮询：查询失败", { error });
				reset();
				(_failRef$current2 = failRef.current) === null || _failRef$current2 === void 0 || _failRef$current2.call(failRef, error, true);
			}).finally(() => {
				if (requestTimeoutIdRef.current) {
					clearTimeout(requestTimeoutIdRef.current);
					requestTimeoutIdRef.current = null;
				}
			});
		});
		return function _resultQuery() {
			return _ref2.apply(this, arguments);
		};
	}();
	/**
	* 前往签名步骤
	*/
	const gotoSignature = () => {
		dispatch(require_index.updateStatus(require_const.StatusEnum.Question));
		dispatch(require_index.updateState({ title: _pisell_utils.locales.getText("page.eftpos-pay.text.receipt.again.title") }));
		dispatch(require_index.updateCustom({ actionStatus: require_const$1.LinklyActionStatus.Signature }));
	};
	/**
	* 检查是否需要处理结果
	*/
	const checkNeedToHandleResult = () => {
		return checkIsGlobalTimeout() || !resultCheck() || isQueryFinishedRef.current;
	};
	/**
	* 检查是否全局超时
	*/
	const checkIsGlobalTimeout = () => {
		if (startTimeRef.current) if (Date.now() - startTimeRef.current > GlobalTimeout) return true;
		else return false;
		return false;
	};
	/**
	* 重置查询状态
	*/
	const reset = () => {
		require_payLog.default.log("Linkly轮询：重置查询状态");
		if (globalTimeoutIdRef.current) {
			clearTimeout(globalTimeoutIdRef.current);
			globalTimeoutIdRef.current = null;
		}
		if (requestTimeoutIdRef.current) {
			clearTimeout(requestTimeoutIdRef.current);
			requestTimeoutIdRef.current = null;
		}
		if (queryIntervalTimerRef.current) {
			clearTimeout(queryIntervalTimerRef.current);
			queryIntervalTimerRef.current = null;
		}
		if (controllerRef.current) {
			controllerRef.current.abort();
			controllerRef.current = null;
		}
		startTimeRef.current = null;
		isRequestCanceledRef.current = false;
		isQueryFinishedRef.current = true;
	};
	const run = () => {
		reset();
		globalTimeoutIdRef.current = setTimeout(() => {
			var _failRef$current3;
			require_payLog.default.log("Linkly轮询：全局超时");
			setTimeout(reset, 0);
			(_failRef$current3 = failRef.current) === null || _failRef$current3 === void 0 || _failRef$current3.call(failRef, { code: require_const.PayStatus.Timeout }, false);
		}, GlobalTimeout);
		startTimeRef.current = Date.now();
		isQueryFinishedRef.current = false;
		require_payLog.default.log("Linkly轮询：开始查询");
		return _resultQuery();
	};
	return {
		run,
		stop: reset
	};
};
//#endregion
exports.useTimeResultQuery = useTimeResultQuery;
