const { session, shell, app } = require('electron')
const fs = require('fs');
const path = require('path')
exports.initDownload = function (win, savePath_ = "", ifOpen = false) {
	session.defaultSession.on('will-download', (event, item) => {
		let DateTime = new Date();
		let FileID = DateTime.getTime();
		const fileName = item.getFilename();
		const url = item.getURL();
		const startTime = item.getStartTime();
		const initialState = item.getState();
		const downloadPath = app.getPath('downloads');
		let fileNum = 0;
		if (savePath_ != "") {
			savePath_ = savePath_.replaceAll("\\", "/")
			savePath_ = savePath_.replaceAll("//", "/")
		}
		let savePath = path.join(savePath_, fileName);
		// savePath基础信息
		const ext = path.extname(savePath);
		const name = path.basename(savePath, ext);
		const dir = path.dirname(savePath);
		// 文件名自增逻辑
		while (fs.existsSync(savePath)) {
			fileNum += 1;
			savePath = path.format({
				dir,
				ext,
				name: `${name}(${fileNum})`,
			});
		}
		win.DownloadObj[FileID] = {
			"状态": "正在下载"
		};
		let TimeID = setInterval(() => {
			if (win.DownloadObj[FileID]["resume"] == true) {
				item.resume(); // 恢复下载  
				win.DownloadObj[FileID]["resume"] = false;
				win.DownloadObj[FileID] = {
					"状态": "正在下载"
				};
				win.webContents.executeJavaScript("文件下载进度('" + url + "'," + item.getReceivedBytes() + "," + item.getTotalBytes() + ",'" + fileName + "','恢复下载','" + FileID + "')")
			}
			if (win.DownloadObj[FileID]["cancel"] == true) {
				item.cancel(); // 取消下载  
				win.DownloadObj[FileID]["cancel"] = false;
				clearInterval(TimeID)
				win.DownloadObj[FileID] = {
					"状态": "停止下载"
				};
			}
		}, 100);
		// 设置下载目录，阻止系统dialog的出现
		item.setSavePath(savePath);
		// 通知渲染进程，有一个新的下载任务
		win.webContents.send('new-download-item', {
			savePath,
			url,
			startTime,
			state: initialState,
			paused: item.isPaused(),
			totalBytes: item.getTotalBytes(),
			receivedBytes: item.getReceivedBytes(),
		});
		win.webContents.executeJavaScript("开始下载文件('" + fileName + "','" + url + "','" + FileID + "')")
		// 下载任务更新
		item.on('updated', (event, state) => {
			win.webContents.send('download-item-updated', {
				startTime,
				state,
				totalBytes: item.getTotalBytes(),
				receivedBytes: item.getReceivedBytes(),
				paused: item.isPaused(),
			});
			if (win.DownloadObj[FileID]) {
				if (win.DownloadObj[FileID]["pause"] == true) {
					item.pause();
					win.DownloadObj[FileID]["pause"] = false;
					win.DownloadObj[FileID] = {
						"状态": "暂停下载"
					};
					win.webContents.executeJavaScript("文件下载进度('" + url + "'," + item.getReceivedBytes() + "," + item.getTotalBytes() + ",'" + fileName + "','暂停下载','" + FileID + "')")
					return;
				}
			}
			if (state === 'interrupted') {
				win.DownloadObj[FileID] = {
					"状态": "停止下载"
				};
				win.webContents.executeJavaScript("文件下载进度('" + url + "'," + item.getReceivedBytes() + "," + item.getTotalBytes() + ",'" + fileName + "','停止下载','" + FileID + "')")
			} else if (state === 'progressing') {
				if (item.isPaused()) {
					win.DownloadObj[FileID] = {
						"状态": "暂停下载"
					};
					win.webContents.executeJavaScript("文件下载进度('" + url + "'," + item.getReceivedBytes() + "," + item.getTotalBytes() + ",'" + fileName + "','暂停下载','" + FileID + "')")
				} else {
					if (item.getReceivedBytes() && item.getTotalBytes()) {
						win.DownloadObj[FileID] = {
							"状态": "正在下载"
						};
						win.webContents.executeJavaScript("文件下载进度('" + url + "'," + item.getReceivedBytes() + "," + item.getTotalBytes() + ",'" + fileName + "','正在下载','" + FileID + "')")
					}
				}
			}
		})
		// 下载任务完成
		item.on('done', (e, state) => { // eslint-disable-line
			clearInterval(TimeID)
			win.webContents.send('download-item-done', {
				startTime,
				state,
			});
			if (state === 'completed') {
				win.DownloadObj[FileID] = {
					"状态": "下载完毕"
				};
				win.webContents.executeJavaScript("文件下载完毕('" + url + "','" + fileName + "','" + FileID + "')");
				if (ifOpen == true) {
					shell.showItemInFolder(savePath) // 下载成功后打开文件所在文件夹
				}
			} else {
				win.DownloadObj[FileID] = {
					"状态": "下载失败"
				};
				win.webContents.executeJavaScript("文件下载失败('" + url + "','" + fileName + "','" + FileID + "')");
			}
		});
	})
}
