<template>
	<view>
		<view v-if='!hasLogin'>
			<view style="text-align: center;margin: 100upx;font-size: 36upx;">欢迎回来</view>
			<view style="width: 50%;margin: 0 auto;">
				<button @click="wxlogion"  type="primary" open-type='getUserInfo'>
					授权登录
				</button>
			</view>
		</view>
		<view  v-if='hasLogin&& !successlogion'>
			<view style="text-align: center;margin: 100upx;font-size: 36upx;">获取您手机号码权限</view>
			<view style="width: 50%;margin: 0 auto;">
				 <button type="primary" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">手机号登录</button>
			</view>
		</view>
	</view>
	
</template>

<script>
	import {
		mapMutations,mapState
	} from 'vuex'
	export default {
		props:{
		  showdialog:{
		    default: false,
		    type: Boolean
		  },
		  ishow:{
		    default: true,
		    type: Boolean
		  },
		},
		 data() {
			return{
				show: false
			}
		},
		computed:{
			...mapState([
			  'hasLogin',  // 用户是否同意授权
			  'userInfo',   // 同意授权用户头像
			  'successlogion', // 同意手机号授权 登录成功
			  'sessionId',   // 登录成功的token
			  'getcode',  // logion时候获取的code session_key oppen_id
			]),
		},
		onLoad(){
			console.log(this.successlogion);
		},
		methods:{
			...mapMutations(['login','showDialog', 'setOpenid', 'setcode','islogionsuccess']),
			// 授权用户信息头像
			wxlogion() {
				let  that = this;
				    uni.getUserInfo({
					     success: (res) => {
							 that.login(res.userInfo);
							 that.showDialog(true); // 改变haslogion的值
							 that.$msg("授权成功");
							 if(this.successlogion) {
								uni.navigateBack();
							 }
					     },
					     fail(res) {
							 that.showDialog(false);
							 that.$msg("授权失败")
					     }
				    })
			},
			// 获取手机号码
			decryptPhoneNumber(e) {
			              console.log(e);    
			              if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {    
			                  console.log(e);
			              } else {    
			                  console.log('用户同意提供手机号');
							  console.log(this.getcode);
											let encryptedData = e.detail.encryptedData;
											let iv = e.detail.iv;
											console.log(this.userInfo);
											// 调取注册账号
											this.request({
												url: '/v1/entry/mp_account',
												method:'POST',
												data: {
													code: this.getcode.code,
													encryptedData:　encryptedData,
													iv:　iv,
													name: this.userInfo.nickName,
													avatar: this.userInfo.avatarUrl
												},
												success: (res) => {
													let token = res.data.data.token;
													this.setOpenid(token);
													this.islogionsuccess(true);
													uni.navigateBack();
												},
												fail: (res) => {
														 this.islogionsuccess(false);
														 this.setOpenid('');
														 this.$msg("获取失败")
												     }
											})
											
									    }
			  },
		}
	}
</script>

<style>
</style>
