import {
	Toast,
	Indicator
} from 'mint-ui'z
import * as qiniu from 'qiniu-js'
import request from '@/request.js'
export function getQueryString(name) {
	let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	let href = window.location.href;
	let str = href.slice(href.indexOf("?"));
	let r = str.substr(1).match(reg);
	if (r != null) {
		return unescape(r[2]);
	} else {
		return null;
	}
}

export function toUpLnImg(files, fun) {
	Indicator.open({
		text: '上传中...',
		spinnerType: 'fading-circle'
	});
	for (let i = 0; i < files.length; i++) {
		let file = files[i];
		let imageType = /^image\//;
		//判断是否为图片不是则跳过不执行下面语句
		if (!imageType.test(file.type)) {
			Indicator.close()
			Toast({
				message: '格式错误',
				duration: 1000
			});
			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) {
					Indicator.close()
					Toast({
						message: '上传成功',
						duration: 1000
					});
					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)) {
			Indicator.close()
			Toast({
				message: '格式错误',
				duration: 1000
			});
			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) {
					Indicator.close()
					Toast({
						message: '上传成功',
						duration: 1000
					});
					fun('https://limg.liuniu946.com/' + res.key)
					// ...
				}
			}
			let subscription = observable.subscribe(observer) // 上传开始
		})
	}
}
