import {Button} from "antd";
import JSZip from "jszip"
import {saveAs} from "file-saver";
import {useState} from "react";

import {getById} from "@/service/api/news.ts";

import {showToast} from "@/components/message.ts";
import {IconDownload} from "@/components/icons";
import {useTranslation} from "react-i18next";


/**
 * 批量获取新闻内容
 * @param ids
 */
function getAllNewsContent(ids: Id[]) {
	return new Promise<NewsInfo[]>((resolve, reject) => {
		const request = ids.map((id) => getById(id))
		Promise.all(request).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		})
	})
}

/**
 * 获取新闻html
 * @param news
 */
function getNewsHtml(news: NewsInfo) {
	return `<html>
<head>
<title>${news.title}</title>
<meta charset="UTF-8">
</head>
<body>
<div style="max-width: 80%;width:1000px;margin:30px auto;">
	<h1>${news.title}</h1>
	<div style="margin: 5px 0;font-size: 13px;">
		<span style="color: #766DF4">${news.media_name}</span>
		<span style="color: #999;margin-left: 10px;">${news.publish_time}</span>
	</div>
	<div>${news.content}</div>
</div>
</body>
</html>`
}

/**
 * 将新闻数据包装成html并打包下载
 * @param list
 */
async function downloadAsZip(list: NewsInfo[]) {
	const zip = new JSZip();

	list.forEach(news => {
		zip.file(`${news.title}.html`, getNewsHtml(news))
	})
	const content = await zip.generateAsync({type: "blob"});
	saveAs(content, "news.zip");

}

export default function ButtonNewsDownload(props: { ids: Id[] }) {
	const {t} = useTranslation()
	const [loading, setLoading] = useState(false)
	const onDownloadClick = async (ids: Id[]) => {
		if(loading) return;
		if (props.ids.length === 0) {
			showToast(t('news.download_empty'), 'warning')
			return
		}
		setLoading(true)
		try {
			const list = await getAllNewsContent(ids)
			await downloadAsZip(list)
		} catch (e) {
			showToast(t('news.download_failed'), 'error')
		} finally {
			setLoading(false)
		}
	}
	return (
		<button
			disabled={loading}
			className={'btn-action bg-[#eef5ff] text-gray-800 hover:bg-[#d2e3ff]'}
			onClick={() => onDownloadClick(props.ids)}
		>
			<span className="text">{t('download')}</span>
			<IconDownload />
		</button>
	)
}
