// 下载任务全局状态管理
class DownloadStoreFile {
	constructor() {
		let tasks = uni.getStorageSync('downloadFileTasks');
		this.tasks = tasks || [] ; // 下载任务列表
		this.listeners = []; // 监听器列表
	}
	
	// 添加任务
	addTask(data) {
		const taskIndex = this.tasks.length;
		const taskItem = {
			id: Date.now() + Math.random(), // 唯一ID
			url: '',
			status: 'downloading', // downloading, paused, completed, failed
			progress: 0,
			title:'',
			type:'',
			releaseTime:'',
			task: null,
			filePath: '',
			createTime: Date.now(),
			localPath:''
		};
		Object.assign(taskItem, data);
		this.tasks.push(taskItem);
		this.notifyListeners();
		this.saveToStorage();
		
		return taskIndex;
	}
	
	// 更新任务
	updateTask(index, updates) {
		if (this.tasks[index]) {
			Object.assign(this.tasks[index], updates);
			this.notifyListeners();
			this.saveToStorage();
		}
	}
	
	// 删除任务
	removeTask(index) {
		const taskItem = this.tasks[index];
		if (taskItem && taskItem.task && taskItem.status === 'downloading') {
			taskItem.task.abort();
		}
		this.tasks.splice(index, 1);
		this.notifyListeners();
		this.saveToStorage();
	}
	
	// 获取所有任务
	getTasks() {
		return this.tasks;
	}
	
	// 获取任务
	getTask(index) {
		return this.tasks[index];
	}
	
	// 添加监听器
	addListener(callback) {
		this.listeners.push(callback);
		// 返回取消监听的函数
		return () => {
			const index = this.listeners.indexOf(callback);
			if (index > -1) {
				this.listeners.splice(index, 1);
			}
		};
	}
	
	// 通知所有监听器
	notifyListeners() {
		// 创建新数组引用，确保Vue能检测到变化
		const tasksCopy = [...this.tasks];
		this.listeners.forEach(callback => {
			try {
				callback(tasksCopy);
			} catch (e) {
				console.error('DownloadStoreFile listener error:', e);
			}
		});
	}
	
	// 保存到本地存储
	saveToStorage() {
		// 只保存基本信息，不保存task对象
		const tasksToSave = this.tasks.map(item => ({
			id: item.id,
			url: item.url,
			status: item.status,
			progress: item.progress,
			filePath: item.filePath,
			createTime: item.createTime,
			localPath:item.localPath,
			title:item.title,
			type:item.type,
			releaseTime:item.releaseTime,
		}));
		uni.setStorageSync('downloadFileTasks', tasksToSave);
	}
	
	// 从本地存储加载
	loadFromStorage() {
		const savedTasks = uni.getStorageSync('downloadFileTasks');
		if (savedTasks && Array.isArray(savedTasks)) {
			this.tasks = savedTasks.map(item => ({
				...item,
				task: null // task对象无法序列化，需要重新创建
			}));
			this.notifyListeners();
		}
	}
	
	// 恢复下载中的任务
	resumeDownloadingTasks(startDownloadCallback) {
		this.tasks.forEach((taskItem, index) => {
			// 如果任务状态是下载中，但task对象为null，说明需要重新创建下载任务
			if (taskItem.status === 'downloading' && !taskItem.task) {
				if (typeof startDownloadCallback === 'function') {
					startDownloadCallback(index);
				}
			}
		});
	}
}

// 创建单例
const downloadStoreFile = new DownloadStoreFile();

// 在应用启动时加载存储的任务
// #ifndef VUE3
if (typeof Vue !== 'undefined') {
	Vue.prototype.$downloadStoreFile = downloadStoreFile;
}
// #endif

export default downloadStoreFile;
