<template>
	<view class="page-container">
		<scroll-view style="height: 100%" scroll-y="true">
			<view class="download-list">
				<scroll-view scroll-x scroll-with-animation :scroll-animation-duration="300"
					:disable-programmatic-animation="true">
					<checkbox-group class="item-container" @change="changeCheck">
						<label v-for="(item, index) in taskArr" :key="index" class="history-item align-center">
							<checkbox v-if="isDeleteMode" color="#DA2538" :value="item.id+''"
								:checked="item.is_checked" />
							<downloading-item v-on:CancelTask="cancelTask" @pauseDownload="pauseDownload"
								@resumeDownload="resumeDownload" :ref="'downloadItem'+item.options.filename"
								:progress="getProgress(item)" :item="item"></downloading-item>
						</label>
					</checkbox-group>
				</scroll-view>
				<u-empty v-if="isEmpty" icon="/static/images/empty.svg" width="240" />
			</view>
		</scroll-view>
		<view v-if="isDeleteMode" class="history-bottom align-center">
			<u-button :plain="true" shape="circle" text="全选" @click="selectAll"></u-button>
			<u-button type="error" :plain="true" shape="circle" text="删除" @click="deldownload"></u-button>
		</view>
	</view>
</template>

<script>
	import fileManager from "@/utils/fileManager.js";
	import downloadingItem from '@/components/downloading-item.vue'
	export default {
		components: {
			downloadingItem,
		},
		data() {
			return {
				isEmpty: false,
				loaded: false,
				taskArr: [],
				progress: 0,
				isDeleteMode: false,
				checked: [],
			};
		},
		methods: {
			selectAll() {
				this.taskArr.map(item => {
					if (!this.checked.includes(item.id + '')) {
						this.checked.push(item.id + '')
						console.log(this.checked);
						item.is_checked = true
					}
				})
			},
		async deldownload() {
		    if (this.checked.length > 0 && this.taskArr.length > 0) {
		        const indexesToDelete = [];
		
		        for (const [i, item] of this.taskArr.entries()) {
		            if (item.is_checked === true) {
		                let task = item;
		                task.pause();
		                let fileName = this.getRelFileName(task.filename);
		                await fileManager.deleteFile(fileName).then((res) => {
		                    task.abort();
		                });
		                indexesToDelete.push(i);
		            }
		        }
		
		        // 从后往前删除元素，以避免索引变化影响删除操作
		        for (let i = indexesToDelete.length - 1; i >= 0; i--) {
		            this.taskArr.splice(indexesToDelete[i], 1);
		        }
		
		        this.checked = [];
		    }
		},
			changeCheck(e) {
				this.checked = e.detail.value
				this.taskArr.map(item => {
					if (this.checked.includes(item.id + '')) {
						item.is_checked = true
					} else {
						item.is_checked = false
					}
				})
			},
			showCancel(isDeleteMode) {
				this.isDeleteMode = isDeleteMode
				for (let i = 0; i < this.taskArr.length; i++) {
					let item = this.taskArr[i]
					// this.$refs['downloadItem'+item.options.filename][0].setProgress(progress)
					this.$refs["downloadItem" + item.options.filename][0].showCancel(this.isDeleteMode)
				}
			},

			async init() {
				if (this.loaded === false) {
					//获取正在下载的列表
					await fileManager.task_downloads().then((res) => {

						for (let i = 0; i < res.length; i++) {
							let task = res[i]
							task.is_checked = false;
							if (task.state > 0 && task.state <= 3) {
								this.taskArr.push(task)
								//正在下载 但被打断的任务 重新开始
								task.addEventListener("statechanged", this.onStateChanged, false);
								if (Object.keys(task.eventHandlers).length == 0) {
									task.start()
								}
							}
							// else if (task.state == undefined) {
							// 	this.taskArr.push(task)
							// 	task.start()
							// } 
							else if (task.state == 5) {
								this.taskArr.push(task)
								// task.addEventListener("statechanged", this.onStateChanged, false);
								// task.resume()
							}
						}
						this.isEmpty = this.taskArr.length == 0
						this.loaded = true
					});
				} else {}
			},
			getRelFileName(fileName) {
				let relName = fileName
				var index = fileName.lastIndexOf("/");
				relName = fileName.substring(index + 1, fileName.length);
				return relName
			},
			async cancelTask(id) {
				for (let i = 0; i < this.taskArr.length; i++) {
					let task = this.taskArr[i]
					if (task.id == id) {
						task.pause()
						let fileName = this.getRelFileName(task.filename)
						await fileManager.deleteFile(fileName).then((res) => {
							task.abort()
						})
						this.taskArr.splice(i, 1)
						break
					}
				}
			},
			async pauseDownload(id) {
				for (let i = 0; i < this.taskArr.length; i++) {
					let task = this.taskArr[i]
					if (task.id == id) {
						task.pause()
					}
				}
			},
			async resumeDownload(id) {
				for (let i = 0; i < this.taskArr.length; i++) {
					let task = this.taskArr[i]
					if (task.id == id) {
						task.resume()
					}
				}
			},
			getProgress(task) {
				let progress = task.totalSize == 0 ? 0 : Math.round((task.downloadedSize / task.totalSize) * 10000) / 100
				let progressInt = parseInt(progress)
				if (progressInt > 100) {
					console.log("task.downloadedSize ", task.downloadedSize)
					console.log("task.totalSize ", task.totalSize)
				}
				return progressInt
			},
			onStateChanged(task, status) {
				switch (task.state) {
					case 1: // 开始
						break;
					case 2: // 已连接到服务器
						break;
					case 3: // 已接收到数据
						let progress = this.getProgress(task)
						console.log(progress)
						this.$refs['downloadItem' + item.options.filename][0].setProgress(progress)
						break;
					case 4: // 下载完成
						console.log("download finish")
						for (let i = 0; i < this.taskArr.length; i++) {
							let taskIndex = this.taskArr[i]
							if (taskIndex.id == task.id) {
								this.taskArr.splice(i, 1)
								break
							}
						}
						fileManager.saveSuccessFileName(task.options.filename)
						break;
				}
			},
		},
	};
</script>

<style lang="scss">
	.page-container {
		height: calc(100% - var(--safe-top) - 94px);
		background-color: $uni-bg-color;

		.download-list {
			padding: 15px;
		}

		.u-empty {
			padding-top: 100px;
		}

		.history-bottom {
			height: 60px;
			width: 100%;
			padding: 0 10px;
			border-top: 1px solid rgba(0, 0, 0, 0.1);
			position: fixed;
			bottom: 0px;

			.u-button {
				flex: 1 1 0%;
				margin: 0 5px;

				&::before {
					display: none;
				}
			}
		}
	}
</style>