import * as qiniu from 'qiniu-js'
import request from '@/utils/request'

export function toUpLnImg(files, fun) {
	uni.showLoading({
		title: '上传中...'
	})
	for (let i = 0; i < files.length; i++) {
		let file = files[i];
		let imageType = /^image\//;
		//判断是否为图片不是则跳过不执行下面语句
		if (!imageType.test(file.type)) {
			uni.hideLoading()
			this.$api.msg('格式错误')
			continue;
		}
		request({
			url: "/Upload/wxUploudtoken",
			method: 'post',
			data: {}
		}).then(({
			data
		}) => {
			console.log(data, 99);
			let observable = qiniu.upload(file, file.name, data.token, {
				fname: "",
				params: {},
				mimeType: null
			}, {
				useCdnDomain: true,
				region: qiniu.region.z0
			});
			let observer = {
				next(res) {
					console.log(res);
					// ...
				},
				error(err) {
					console.log(err);
					// ...
				},
				complete(res) {
					uni.hideLoading()
					this.$api.msg('上传成功')
					fun('https://limg.liuniu946.com/' + res.key)
					// ...
				}
			}
			let subscription = observable.subscribe(observer) // 上传开始
		})
	}
}

/**
 * @param {Object} files 要上传的文件
 * @param {Function} fun 上传成功后的回调
 */
export function toUpVideo(files, fun) {
	Indicator.open({
		text: '上传中...',
		spinnerType: 'fading-circle'
	});
	for (let i = 0; i < files.length; i++) {
		let file = files[i];
		let Type = /^video\//;
		//判断是否为图片不是则跳过不执行下面语句
		if (!Type.test(file.type)) {
			uni.hideLoading()
			this.$api.msg('格式错误')
			continue;
		}

		request({
			url: "/Upload/wxUploudtoken",
			method: 'post',
			data: {}
		}).then(({
			data
		}) => {
			// console.log(data);
			let observable = qiniu.upload(file, file.name, data.token, {
				fname: "",
				params: {},
				mimeType: null
			}, {
				useCdnDomain: true,
				region: qiniu.region.z0
			});
			let observer = {
				next(res) {
					console.log(res);
					// ...
				},
				error(err) {
					console.log(err);
					// ...
				},
				complete(res) {
					uni.hideLoading()
					this.$api.msg('上传成功')
					fun('https://limg.liuniu946.com/' + res.key)
					// ...
				}
			}
			let subscription = observable.subscribe(observer) // 上传开始
		})
	}
}

export default {
	toUpLnImg,
	toUpVideo
};