// utils/upload.js
const http = require('../../common/request');
const config = require('../../common/config.js');

class Upload {
	static imgUp = [];
	static index = 0;
	static token = '';
	// 获取七牛云 token
	static async qiniuUpImg() {
		const {
			data
		} = await http.getApi(config.API_QINIU_UP_IMG_TOKEN, {});
		if (data.code === 200) {
			this.token = data.data.token;
		}
	}
	// 上传文件核心方法
	static async uploadFile(tempFilePaths) {
		if (!this.token) {
			await this.qiniuUpImg();
		}

		while (this.index < tempFilePaths.length) {
			uni.showLoading({
				mask: true,
				title: `${this.index + 1}/${tempFilePaths.length}`
			})
			// const res = await uni.uploadFile({
			// 	url: config.QINIU_UPLOAD_SITE,
			// 	filePath: tempFilePaths[this.index],
			// 	name: 'file',
			// 	formData: {
			// 		token: this.token
			// 	},
			// });
			const res = await this.uploadFileAsync(tempFilePaths)
			if (res) {
				const rtDataObj = JSON.parse(res.data);
				const img = {
					url: config.QINIU_SITE + rtDataObj.key,
					title: ""
				};
				this.imgUp.push(img);
				this.index += 1;
			} else {
				uni.hideLoading()
			}
		}
		uni.hideLoading()
		const result = [...this.imgUp];
		this.imgUp = [];
		this.index = 0;
		return result;
	}
	static uploadFileAsync(tempFilePaths) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: config.QINIU_UPLOAD_SITE,
				filePath: tempFilePaths[this.index],
				name: 'file',
				formData: {
					token: this.token
				},
				success(res) {
					resolve(res)
				},
				fail(err) {
					reject(err)
				}
			});
		})
	}

}

export default Upload; // 确保导出类