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 { PayStatus } from "../const.js";
import { sleep } from "../helper.js";
import payLog from "../utils/payLog.js";
import { useCallback, useEffect, useRef } from "react";
//#region src/components/eftposPay/payo/hooks.tsx
/**
* @title: 循环查询 接口状态
* @Author: hongbing.wang
* @Date: 2024-08-20 13:29
*/
const useValidate = (timeout) => {
	const controllerRef = useRef();
	const ref = useRef(true);
	const isTimeoutCloseRef = useRef(false);
	const TimeoutRef = useRef();
	const checkApi = useCallback(function() {
		var _ref = _asyncToGenerator(function* (check, number, time) {
			time = time || 5e3;
			controllerRef.current = new AbortController();
			let res = { code: PayStatus.Timeout };
			console.log("循环开始前...");
			while (ref.current && res && `${res.code}` === PayStatus.Timeout) {
				const start = Date.now();
				res = yield check({ number }, { signal: controllerRef.current.signal }).catch((err) => Promise.resolve(err));
				const diff = Date.now() - start;
				console.log(diff, time, time - diff, "diff", res);
				if (diff < time) yield sleep(time - diff);
			}
			if (isTimeoutCloseRef.current) {
				if (!res) return { code: PayStatus.Timeout };
				const { code } = res;
				if (`${code}` === `200`) return _objectSpread2(_objectSpread2({}, res), {}, { code: PayStatus.Timeout });
			}
			return res;
		});
		return function(_x, _x2, _x3) {
			return _ref.apply(this, arguments);
		};
	}(), []);
	/**
	* @title: 关闭循环
	* @Author: hongbing.wang
	* @Date: 2024-08-20 13:48
	*/
	const close = useCallback(() => {
		var _controllerRef$curren;
		ref.current = false;
		(_controllerRef$curren = controllerRef.current) === null || _controllerRef$curren === void 0 || _controllerRef$curren.abort();
	}, []);
	const run = (...params) => {
		isTimeoutCloseRef.current = false;
		TimeoutRef.current && clearTimeout(TimeoutRef.current);
		TimeoutRef.current = setTimeout(() => {
			isTimeoutCloseRef.current = true;
			payLog.log("Payo：支付状态查询超时");
			close();
		}, timeout);
		return checkApi(...params);
	};
	useEffect(() => () => {
		clearTimeout(TimeoutRef.current);
		close();
	}, [close]);
	return [run, close];
};
//#endregion
export { useValidate };
