import { useRateLimitStore } from "@/stores/modules/rateLimit"
import { storeToRefs } from "pinia";

const getRateLimitStore = async () => {
	return useRateLimitStore()
}

export const sleep = async (time: number) => {
	return new Promise((resolve) => {
		setTimeout(() => {
			resolve(true);
		}, time);
	});
}

export const formatDate = (date: Date) => {
	const d = new Date(date);

	const year = d.getFullYear();
	const month = String(d.getMonth() + 1).padStart(2, '0');
	const day = String(d.getDate()).padStart(2, '0');
	const hour = String(d.getHours()).padStart(2, '0');
	const minute = String(d.getMinutes()).padStart(2, '0');
	const second = String(d.getSeconds()).padStart(2, '0');

	return `${year}/${month}/${day} ${hour}:${minute}:${second}`;
}

export const goTo = (url: string) => {
	uni.navigateTo({
		url: url
	})
}

/**
 * 创建一个限流器，限制函数在指定时间窗口内的调用次数。
 * @param func 要限流的原始函数
 * @param time 时间窗口长度（毫秒）
 * @param n 最大允许调用次数
 * @returns 包装后的函数，每次调用返回布尔值表示是否允许执行
 */
export const rateLimit = async <T extends (...args: any[]) => any>(
	time: number,
	n: number,
	func?: T
): Promise<(...args: Parameters<T>) => boolean> => {

	const {
		timestamps
	} = storeToRefs(await getRateLimitStore())

	return function (this: ThisParameterType<T>, ...args: Parameters<T>): boolean {
		const now = Date.now();

		// 清理超出时间窗口的历史记录
		while (timestamps.value.length > 0 && timestamps.value[0] <= now - time) {
			timestamps.value.shift();
		}

		// 如果当前窗口内调用次数已达到上限，则拒绝本次调用
		if (timestamps.value.length >= n) {
			return false;
		}

		// 记录本次调用时间戳
		timestamps.value.push(now);
		console.log(timestamps.value)

		// 执行原函数，忽略其返回值
		func?.apply(this, args);
		return true;
	};
}