<template>
	<view class="bg">
		<view class="title">广安农机农技智慧服务小程序正在使用广安农机农技平台登陆提供的服务，平台登陆将使用:</view>
		<view class="info">
			<text class="icon">&#xe605;</text>
			<text v-if="first">您的公开信息（昵称，头像，性别等）</text>
			<text v-else>您的手机号</text>
		</view>
		<button class="btn" @click="getUserProfile()" v-if="first">允许使用</button>
		<button class="btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" style="background-color: #2196F3" v-else>允许使用</button>
		<button class="btn" style="background-color: #9E9E9E;" @click="cancel()">取消</button>
	</view>
</template>
<script>
export default {
	data() {
		return {
			item: {},
			first: true
		};
	},
	onLoad() {},
	methods: {
		getUserProfile() {
			//获取用户信息
			uni.getUserProfile({
				desc: '用于完善会员资料',
				lang: 'zh_CN',
				provider: 'weixin',
				success: info => {
					this.item.avatarUrl = info.userInfo.avatarUrl;
					this.item.nickName = info.userInfo.nickName;
					this.item.gender = info.userInfo.gender;
					this.item.city = info.userInfo.country + ' ' + info.userInfo.province + ' ' + info.userInfo.city;
					console.log('登陆：' + JSON.stringify(this.item));
					uni.login({
						provider: 'weixin',
						success: res => {
							this.item.code = res.code;
							this.$http.request({
								url: this.$http.urls.login,
								data: this.item,
								success: res => {
									console.log(JSON.stringify(res));
									if (res.data.code === 200) {
										uni.setStorageSync('user', res.data.data);
										uni.navigateBack({ delta: 1 });
									}
									if (res.data.code === 600) {
										this.first = false;
									}
								}
							});
						}
					});
				}
			});
		},
		// 绑定用户手机号
		getPhoneNumber(e) {
			uni.login({
				provider: 'weixin',
				success: res => {
					this.item.code = res.code;
					this.item.encryptedData = e.target.encryptedData;
					this.item.iv = e.target.iv;
					this.$http.request({
						url: this.$http.urls.bindPhone,
						data: this.item,
						success: res => {
							uni.setStorageSync('user', res.data.data);
							uni.$emit('update');
							uni.navigateBack({ delta: 1 });
						}
					});
				}
			});
		},
		cancel() {
			uni.navigateBack();
		}
	}
};
</script>

<style lang="less">
page {
	background-color: white;
}
.bg {
	padding: 30px;
	.title {
		font-weight: bold;
	}
	.info {
		color: #8b918d;
		margin-top: 10px;
	}
	.btn {
		margin-top: 20px;
	}
}
</style>
