import * as api from '@/service/api'

// uni.login()封装
const wxLogin = function(openid) {
	return new Promise((resolve, reject) => {
		uni.login({
			success(res) {
				if (res.code) {
					resolve(res.code)
				} else {
					reject(res.errMsg);
				}
			}
		})
	})
}
/*微信小程序登录*/
const wechatAppLogin = function() {
	/*登录提示*/
	// loading("正在授权")
	uni.showLoading({
		title:"授权中"
	})
	uni.getUserProfile({
		desc: '获取用户授权',
		success: res => {
			let userInfo = res.userInfo;
			console.log(userInfo);
			// 修改头像
			api.updateThumb({
				thumb:userInfo.avatarUrl,
				token:uni.getStorageSync("token")
			}).then(res=>{
				if(res.code == 200){
					uni.setStorage({
						key:"userInfo",
						data:res.result
					})
					uni.showToast({
						title:"授权成功",
						icon:'success'
					})
					setTimeout(function(){
						uni.navigateTo({
							url: "/pages/index/index",
						})
					},1000)
				}else{
					uni.showToast({
						title:res.msg,
						icon:'error'
					})
				}
			});
			uni.setStorage({
				key:'wxUserOriginInfo',
				data:userInfo
			})
			uni.hideLoading();
		},
		fail() {
			uni.hideLoading();
		}
	})
}

// 获取手机号授权
const getPhoneNumber = function(event) {
	uni.showLoading({
		title:"授权中"
	})
	let that = this;
	let code = event.detail.code; //获取手机code
	let detail = event.detail;
	let codeResultInfo = uni.getStorageSync('wxUserInfo');
	var promise = new Promise(function(resolve, reject) {
		uni.checkSession({
			success: (res) => {
				api.wxphoneNum({
					iv:detail.iv,
					encryptedData:detail.encryptedData,
					session_key:codeResultInfo.session_key,
					openid:codeResultInfo.openid,
					code:detail.code
					}).then(res => {
						console.log('diyige');
						if(res.code == 200){
							uni.setStorage({
								key:"token",
								data:res.result.token
							})
							uni.setStorage({
								key:"userInfo",
								data:res.result.user
							})
							uni.showToast({
								title:"登录成功",
								icon:'success'
							})
							setTimeout(function(){
								uni.navigateTo({
									url: "/pages/index/index",
								})
							},1000)
						}else{
							console.log(res.msg);
							uni.showToast({
								title:res.msg,
								icon:'error'
							})
						}
						uni.hideLoading();
				},resTwo=>{
					console.log("异常");
				})
			},
		})
	})
	uni.hideLoading();
}

module.exports = {
	wechatAppLogin,
	getPhoneNumber
}

