// utils/upload.js

export const uploadFiles = ({
	files = [],
	url = '',
	name = 'file',
	formData = {},
	fileType = 'image',
	vm, // 关键：传入 vm 以便访问 vuex_token、vuex_remember 等
}) => {
	return new Promise(async (resolve, reject) => {
		if (!url) return reject(new Error('上传地址不能为空'));
		if (!Array.isArray(files) || files.length === 0) return reject(new Error('文件列表不能为空'));

		const results = [];
		for (let i = 0; i < files.length; i++) {
			const filePath = files[i];
			try {
				const res = await uploadSingleFile({
					filePath,
					url,
					name,
					formData,
					fileType,
					vm
				});
				results.push(res);
			} catch (err) {
				reject(err);
				return;
			}
		}
		resolve(results);
	});
};

function uploadSingleFile({
	filePath,
	url,
	name,
	formData = {},
	fileType = 'image',
	vm
}) {
	return new Promise((resolve, reject) => {
		const headers = {
			'x-requested-with': 'XMLHttpRequest',
			source: 'uniapp',
			clientId: 'dab457a1ea14411787c240db05bb0832',
		};

		// 手动加上 Token
		if (vm?.vuex_token) {
			headers.Authorization = `Bearer ${vm.vuex_token}`;
		}

		// 加上 rememberMe
		if (vm?.vuex_remember) {
			headers['x-remember'] = vm.vuex_remember;
		}
		console.log('request', headers);
		console.log('request:', {
			url: url,
			filePath: filePath,
			name: name,
			formData: formData
		});
		uni.uploadFile({
			url,
			filePath,
			name,
			formData,
			header: headers,
			fileType,
			success: (res) => {
				try {
					const data = JSON.parse(res.data);
					console.log('request', data);
					if (res.statusCode === 200) {
						resolve(data);
					} else {
						reject(data);
					}
				} catch (e) {
					reject(e);
				}
			},
			fail: (err) => {
				reject(err);
				console.log('request', err);
			}
		});
	});
}