import http from "@/rokeTools/request/index.js";
// success 每次请求成功的返回值, callback 全部请求完成的返回

// const urlObjs = [{url_tag:'',data:{type_code:''}}];
/*
 * test1,请求方法使用示例，用法参考
 * success单条请求成功返回数据,请求失败不返回
 * callback 全部请求完成发挥数据,包括错误请求
 * */
export function test1() {
	console.log('1111')
	let urlObjs = [{
		url_tag: 'report.get_process_category',
		data: {}
	}, {
		url_tag: "report.get_work_center_list",
		data: {}
	}];
	let max = 5;
	batchFetchQueue(urlObjs, max, (results) => {
		//所有请求结束再返回数据
		console.log(JSON.stringify(results));
	}, (requestData) => {
		//每次请求成功的数据都立即返回
		console.log(JSON.stringify(requestData));
	})
}
// 参数格式
// 
/*
 * max 最大并发条数,
 * success单条请求成功返回数据,请求失败不返回
 * callback 全部请求完成返回数据,包括错误请求
 * */
export function batchFetchQueue(urlObjs, max, callback, success) {
	console.log(JSON.stringify(urlObjs));
	const urlCount = urlObjs.length;
	if (max > urlObjs.length) {
		max = urlObjs.length;
	}
	const requestsQueue = [];
	const results = [];
	let i = 0;
	const handleRequest = (urlObj) => {
		const req = fetch(urlObj).then(requestData => {
			requestData['url_tag'] = urlObj.url_tag;
			requestData['obj'] = urlObj.data;
			'function' === typeof success && success(requestData);
			const len = results.push(requestData);
			if (len < urlCount && i + 1 < urlCount) {
				requestsQueue.shift();
				handleRequest(urlObjs[++i]);
			} else if (len === urlCount) {
				'function' === typeof callback && callback(results)
			}
		}).catch(err => {
			err['url'] = urlObj.url;
			err['obj'] = urlObj.obj;
			results.push(err);
			if (results.length < urlCount && i + 1 < urlCount) {
				requestsQueue.shift();
				handleRequest(urlObjs[++i]);
			} else if (results.length === urlCount) {
				'function' === typeof callback && callback(results)
			}
		});
		if (requestsQueue.push(req) < max) {
			if (i + 1 < urlCount) {
				handleRequest(urlObjs[++i]);
			}
		}
	};
	handleRequest(urlObjs[i])
}


const fetch = function(urlObj) {
	return new Promise(resolve => {
		let url_tag = urlObj.url_tag;
		let data = urlObj.data;
		if (!data) {
			data = {};
		}
		http(url_tag, data).then((requestData) => {
			resolve(requestData);
		}).catch((err) => {
			resolve(err);
		})
	})
}