function getBeijingTime(date = new Date()) {
	const f = n => String(n).padStart(2, '0');
	const t = new Date(date.toLocaleString('en-US', { timeZone: 'Asia/Shanghai' }));
	return `${t.getFullYear()}-${f(t.getMonth()+1)}-${f(t.getDate())} ${f(t.getHours())}:${f(t.getMinutes())}:${f(t.getSeconds())}`;
}

/**
 * 获取最新发布版本信息
 * @param {Array} releases - 发布版本数组
 * @param {Object} options - 配置项
 * @param {boolean} options.includePrerelease - 是否包含预发布版（默认 true）
 * @returns {Object|null} 最新版本信息
 */
export function getLatestRelease(releases, options = {}) {
	const { includePrerelease = true } = options;

	try {
		if (!Array.isArray(releases)) {
			throw new Error("参数错误：releases 必须是数组");
		}
		if (releases.length === 0) {
			throw new Error("没有可用的版本数据");
		}

		// 过滤掉预发布（如果不包含）
		let filtered = releases;
		if (!includePrerelease) {
			filtered = releases.filter(r => !r.prerelease);
			if (filtered.length === 0) {
				throw new Error("没有找到正式版版本数据");
			}
		}

		// 按发布时间排序，取最新的
		const latest = filtered.sort((a, b) =>
			new Date(b.published_at) - new Date(a.published_at)
		)[0];

		if (!latest) {
			throw new Error("无法找到最新版本");
		}

		return {
			latestVersion: latest.tag_name.replace('v', '') || null,
			download_url: latest.assets?.[0]?.browser_download_url.replace('192.168.1.132:3000', '223.94.45.156:10830') ||
				null,
			prerelease: latest.prerelease,
			published_at: latest.published_at || null,
			title: latest.name || "",
			description: latest.body || ""
		};

	} catch (error) {
		console.error("获取最新版本出错:", error.message);
		return null;
	}
}

export function getReleases(releases, options = {}) {
	const { includePrerelease = true } = options;

	try {
		if (!Array.isArray(releases)) {
			throw new Error("参数错误：releases 必须是数组");
		}
		if (releases.length === 0) {
			throw new Error("没有可用的版本数据");
		}

		// 过滤掉预发布（如果不包含）
		let filtered = releases;
		if (!includePrerelease) {
			filtered = releases.filter(r => !r.prerelease);
			if (filtered.length === 0) {
				throw new Error("没有找到正式版版本数据");
			}
		}

		// 按发布时间排序
		filtered.sort((a, b) =>
			new Date(b.published_at) - new Date(a.published_at)
		);

		let renderedReleases = [];
		filtered.forEach(item => {
			renderedReleases.push({
				version: item.tag_name.replace('v', '') || null,
				download_url: item.assets?.[0]?.browser_download_url.replace('192.168.1.132:3000',
						'223.94.45.156:10830') ||
					null,
				prerelease: item.prerelease,
				published_at: getBeijingTime(new Date(item.published_at || null)) || null,
				title: item.name || "",
				description: item.body || ""
			})
		});
		console.log(filtered);
		console.log(renderedReleases);
		return renderedReleases;

	} catch (error) {
		uni.showToast({
			title: "获取版本列表出错",
			icon: 'none'
		});
		console.error("获取版本列表出错:", error);
		return null;
	}
}