// http请求方法封装
class HttpClient {
	
	// [{ key, value }]
	taskList = []
	
	// http基础请求方法
	request = (option) => {
		const taskName = option.name || option.url || ''
		return new Promise((resolve, reject) => {
			const requestTask = uni.request(option).then(response => {
				if (Array.isArray(response) && response.length) {
					resolve(response[response.length - 1])
				} else {
					resolve(response)
				}
			}).catch(error => {
				reject(error)
			}).finally(() => {
				this.removeTaskFromTaskList(taskName)
			})
			this.addTaskToTaskList(requestTask, taskName)
		})
	}
	
	addTaskToTaskList (task, name) {
		if (!(task && name)) { return }
		this.taskList.push({ key: name, value: task })
		// console.log('addTaskToTaskList', name, this.taskList)
	}
	
	removeTaskFromTaskList (name) {
		if (!name) { return }
		for (let i = this.taskList.length - 1; i >= 0; i--) {
			if (this.taskList[i].key === name) {
				this.taskList.splice(i, 1)
				break;
				// console.log('removeTaskFromTaskList', name, this.taskList)
			}
		}
	}
	
	// 取消http请求
	cancelRequest = (name) => {
		this.taskList.forEach(el => {
			if (el.key === name && el.value) {
				el.value.abort()
				this.removeTaskFromTaskList(name)
			}
		})
	}
}

export default HttpClient
