import { _asyncToGenerator } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { ModeEnum, PayStatus, StatusEnum } from "../../const.js";
import { LinklyActionStatus } from "../const.js";
import { updateCustom, updateState, updateStatus, useDispatch } from "../../store/index.js";
import { useFail, useStoreRef } from "../../hooks.js";
import payLog from "../../utils/payLog.js";
import { useRef } from "react";
import { locales } from "@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 = useDispatch();
	const { numRef, modeRef, deviceRef } = useStoreRef();
	const failRef = useRef(useFail(0));
	const isPay = modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay;
	const controllerRef = useRef(null);
	const requestTimeoutIdRef = useRef(null);
	const globalTimeoutIdRef = useRef(null);
	const isRequestCanceledRef = useRef(false);
	const startTimeRef = useRef(null);
	const isQueryFinishedRef = useRef(true);
	const queryIntervalTimerRef = useRef(null);
	const _resultQuery = function() {
		var _ref2 = _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;
				payLog.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) {
					payLog.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) {
					payLog.log("Linkly轮询：继续查询", { data });
					isQueryFinishedRef.current = false;
					queryIntervalTimerRef.current = setTimeout(() => {
						_resultQuery();
					}, QUERY_INTERVAL);
					return;
				}
				if (data.status < 0) {
					var _failRef$current;
					payLog.log("Linkly轮询：交易失败", { data });
					reset();
					result.code = PayStatus.Unknown;
					(_failRef$current = failRef.current) === null || _failRef$current === void 0 || _failRef$current.call(failRef, result, false);
					return;
				}
				if (data.signature_flag == 1) {
					payLog.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) {
					payLog.log("Linkly轮询：请求被取消，继续查询");
					isQueryFinishedRef.current = false;
					queryIntervalTimerRef.current = setTimeout(() => {
						_resultQuery();
					}, QUERY_INTERVAL);
					return;
				}
				if (!(error === null || error === void 0 ? void 0 : error.code) || `${error.code}` === PayStatus.Timeout) {
					payLog.log("Linkly轮询：网关报错，继续查询");
					isQueryFinishedRef.current = false;
					queryIntervalTimerRef.current = setTimeout(() => {
						_resultQuery();
					}, QUERY_INTERVAL);
					return;
				}
				payLog.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(updateStatus(StatusEnum.Question));
		dispatch(updateState({ title: locales.getText("page.eftpos-pay.text.receipt.again.title") }));
		dispatch(updateCustom({ actionStatus: 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 = () => {
		payLog.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;
			payLog.log("Linkly轮询：全局超时");
			setTimeout(reset, 0);
			(_failRef$current3 = failRef.current) === null || _failRef$current3 === void 0 || _failRef$current3.call(failRef, { code: PayStatus.Timeout }, false);
		}, GlobalTimeout);
		startTimeRef.current = Date.now();
		isQueryFinishedRef.current = false;
		payLog.log("Linkly轮询：开始查询");
		return _resultQuery();
	};
	return {
		run,
		stop: reset
	};
};
//#endregion
export { useTimeResultQuery };
