import wx from 'weixin-js-sdk'
import * as API_WeiXin from '$project/apis/weixin'
import * as API_Common from '$project/apis/common'

//获取微信配置
export function getWxConfig(jsApiList) {
	var jsApiList = jsApiList || ['chooseImage', 'getLocalImgData', 'scanQRCode'];
	let promise = (jsApiList => {
		return new Promise((resolve, reject) => {
			console.log(jsApiList);
			API_WeiXin.getConfig().then(response => {
				var wxconfig = response.wxConfig;
				console.log(wxconfig.nonceStr)
				wx.config({
					debug: false, // 开启调试模式,
					appId: wxconfig.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
					timestamp: wxconfig.timestamp, // 必填，生成签名的时间戳
					nonceStr: wxconfig.nonceStr, // 必填，生成签名的随机串
					signature: wxconfig.signature, // 必填，签名，见附录1
					jsApiList: jsApiList // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
				});
				wx.ready(function() {
					resolve(response);
				})
				wx.error(function(res) {
					reject('微信api配置出错');
				});
			}).catch(error => {
				mui.toast(error);
				reject(error);
			})
		})
	})(jsApiList)

	return promise;
}

//选择图片
export function chooseImage() {
	let promise = new Promise((resolve, reject) => {
		wx.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: function(res) {
				var localIds = res.localIds;
				console.log(localIds);
				wx.getLocalImgData({
					localId: localIds[0],
					success: function(res) {
						resolve(res);
					}
				});
			}
		});
	});
	return promise;
}

//上传图片
export function uploadPic(imgBase64) {
	let promise = new Promise((resolve, reject) => {
		var formData = new FormData();
		formData.append('photoName', '1.jpg');
		formData.append('photoBase64Data', imgBase64);

		console.log(formData);
		console.log(typeof formData);

		API_Common.uploadBase64(formData).then(response => {
			resolve(response);
		}).catch(error => {
			mui.toast(error);
			reject(error);
		})
	});
	return promise;
}

//获取坐标
export function getLocation() {
	let promise = new Promise((resolve, reject) => {
		wx.ready(function() {
			wx.getLocation({
				type: 'gcj02', // 默认为wgs84的gps坐标，可传入'gcj02'
				success: function(res) {
					resolve(res);
				},
				faile: function(res) {
					reject(res);
				},
				complete() {}
			})
		})
	})
	return promise;
}

//扫描二维码
export function scanQRCode(needResult) {
	var needResult = needResult || 1;
	let promise = new Promise((resolve, reject) => {
		wx.scanQRCode({
			needResult: needResult,
			scanType: ["qrCode"],
			success: function(res) {
				var url = res.resultStr;
				resolve(url);
			},
			faile: function(res) {
				reject(res);
			},
			complete() {}
		})
	});
	return promise;
}
