import React from 'react';
import { Modal, message, Progress } from 'antd';
import { uaaRequest } from '@/webPublic/one_stop_public/utils/request';
import { getFileInfo } from '@/webPublic/zyd_public/utils/handlePhoto';

export async function showDownloadProgressFromFileName(res, { ext, fileName }) {
	const reader = res.body.getReader();
	let contentLength = res.headers.get('Content-Disposition').split('filename=')[1]; // 文件大小从filename里面取
	let nowTime = new Date().getTime();
	if (contentLength && contentLength.includes('.')) {
		contentLength = Number(contentLength.split('.')[0]); // 文件大小
		if (contentLength > 0) {
			message.info('正在获取文件,请耐心等待');
			let receivedLength = 0;
			let chunks = [];
			while (true) {
				const { done, value } = await reader.read();
				if (done) {
					break;
				}
				chunks.push(value);
				receivedLength += value.length;
				// 下载进度
				const progress = (receivedLength / contentLength) * 100;
				if (new Date().getTime() - 1200 > nowTime) {
					message.info('正在获取文件,请耐心等待,下载进度为' + progress.toFixed(2) + '%', 1);
					nowTime = new Date().getTime();
				}
				// 将获取的百分比callback返回出去
				// console.log(progress);
				// console.log(`Reveived ${receivedLength} of ${contentLength}`, progress, 'progress');
			}
			let a = document.createElement('a');
			a.style.display = 'none';
			document.body.append(a);
			const urlFile = window.URL.createObjectURL(new Blob(chunks, { type: ext }));
			a.href = urlFile;
			let filename = fileName;
			if (ext && filename.indexOf('.') === -1) {
				filename = filename + '.' + ext;
			}
			a.download = filename;
			a.click();
			document.body.removeChild(a);
			window.URL.revokeObjectURL(urlFile);
			a = null;
		}
	}
}

export async function showDownloadProgressFromCacheKey(cacheKey, { ext, fileName }) {
	if (cacheKey) {
		const timerInterVal = window.setInterval(() => {
			uaaRequest('/DataColumnApi/queryZip', {
				cacheKey,
			}).then((res) => {
				if (res.finished) {
					clearInterval(timerInterVal);
					if (res.path) {
						message.success('生成成功,开始下载', 2);
						const a = document.createElement('a');
						a.style.display = 'none';
						document.body.append(a);
						a.href = getFileInfo(res.path).url;
						let filename = fileName;
						if (ext && filename.indexOf('.') === -1) {
							filename = filename + '.' + ext;
						}
						a.download = filename;
						a.click();
						document.body.removeChild(a);
					} else {
						message.error('生成文件失败');
					}
				} else {
					if (typeof res.success === 'number' && res.success >= 0 && res.total > 0) {
						const progress = res.success / res.total;
						message.info('正在生成文件,请耐心等待,获取进度' + progress.toFixed(2) + '%', 1);
					} else {
						message.error('生成文件失败');
						clearInterval(timerInterVal);
					}
				}
			});
		}, 2000);
	}
}
