<template>
	<view class="page">
		<view class="wrap">
			<view class="logo">
				<image class="icon" src="https://izhixinyun.com/images/hjyz-logo.png" mode="widthFix"></image>
				<view class="texts">
					<view class="cn">慧教云舟</view>
					<view class="en">EduVessel</view>
				</view>
			</view>
			<template v-if="isLogin">
				<button class="btn phone" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
					<image src="@/static/image/phone.png" mode="widthFix"></image>
					{{ isReg ? '获取手机号' : '绑定手机'}}
				</button>
			</template>
			<template v-else>
				<view class="btn wechat" @click="login">
					快捷登录
				</view>
			</template>
			
			<view class="agree">
				<uni-data-checkbox class="check" multiple v-model="agree" :localdata="agreeData"></uni-data-checkbox>
				<text @click="toAgreement(0)">《用户服务协议》</text>
				<text @click="toAgreement(1)">《用户隐私协议》</text>
			</view>
		</view>
	</view>
</template>

<script>
	import { studentWeChatAppletCallback, studentBinding, weChatToken } from '@/apis/modules/user.js'
	import WXBizDataCrypt from '@/libs/WXBizDataCrypt'
	export default {
		data() {
			return {
				agree: [],
				agreeData: [{
					text: '同意',
					value: 1
				}],
				isLogin: false, // 是否已登录
				isReg: false, // 是否是注册
				sessionKey: '',
				openid: '',
				unionid: '',
				submiting: false
			}
		},
		onShow() {
						// uni.setStorageSync('token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjM5NTc2LCJyblN0ciI6IjZXZUtCNTdOMU9ubGhBSG53RmJwMWN0c3VuVWlyR2l5IiwiYWNjb3VudElkIjozOTU3NiwidXNlcklkIjozOTU3NSwic2Nob29sSWQiOjI4NDYsInVzZXJOYW1lIjoiYWMiLCJwbGF0Zm9ybUlkIjoiMSJ9.hYkjwTUdMMYQLXJVRmqnw3tqRvGndNAzUiVh1ClyCec')
			// 先授权用户信息，再授权手机号
			this.checkLogin()
		},
		methods: {
			// 检查登录状态
			checkLogin() {
				if (uni.getStorageSync('token')) {
					this.toIndex()
				} else {
					uni.clearStorageSync()
					this.isLogin = false
				}
			},
			// 授权用户信息
			login() {
				this.isReg = false
				if (this.agree.length) {
					if (this.submiting) return false
					const that = this
					uni.getUserProfile({
						lang: 'zh_CN',
						desc: '登录',
						success: ({ userInfo }) => {
							uni.login({
								success: async ({ code }) => {
									if (code) {
										this.submiting = true
										
										// 微信小程序登录
										try {
											const res = await studentWeChatAppletCallback({
												code,
												avatarUrl: userInfo.avatarUrl
											})
											const { data, status } = res
											this.submiting = false
											const e = data.sessionKey
											this.sessionKey = e.session_key
											this.openid = e.openid
											uni.setStorageSync('sessionKey', e.session_key)
											uni.setStorageSync('openid', e.openid)
											// 如果没有绑定手机号，则显示绑定按钮，引导用户绑定，否则，直接跳到首页
											if (data.state === 'login') {
												uni.setStorageSync('token', data.token)
												this.toIndex()
											} else {
												// 新用户，前往绑定账号页面
												this.isLogin = true
												this.isReg = true
											}
										} catch (e) {
											this.submiting = false
										}
									} else {
										this.submiting = false
										that.$util.errMsg('登录失败！')
									}
								}
							})			
						},
						fail(res) {
							that.$util.errMsg('登录授权失败！')
						}
					})
				} else {
					this.$util.errMsg('请先阅读勾选协议！')
				}
			},
			// 绑定手机号
			async onGetPhoneNumber(e){
				if (this.submiting) return false
				const { encryptedData, iv } = e.detail
				const appId = this.isDy ? 'tt2192572fbea04fe601' : uni.getAccountInfoSync().miniProgram.appId
				const pc = new WXBizDataCrypt(appId , this.sessionKey)
				const decData = pc.decryptData(encryptedData , iv)
				this.submiting = true
				const phone = decData.phoneNumber
				uni.setStorageSync('phone', phone)
				const { data } = await studentBinding({
					openid: this.openid,
					phone,
					platformId: 1
				})
				if (data) {
					const accounts = data.userAccounts
					// 老用户则前往选择账号
					uni.setStorageSync('accounts', JSON.stringify(accounts))
					this.$util.to(`/user/selectAccount/selectAccount?openid=${this.openid}&phone=${phone}`)
				} else {
					// 新用户则前往绑定账号
					this.$util.to(`/user/reg/reg?openid=${this.openid}&phone=${phone}`)
				}
			},
			toAgreement(id) {
				this.$util.to(id ? `/order/privacyAgreement/privacyAgreement` : `/order/serviceAgreement/serviceAgreement`)
			},
			// 跳转到首页
			toIndex() {
				uni.switchTab({
					url: '../index/index'
				})
			}
		}
	}
</script>

<style scoped lang="scss">
.page {
	min-height: calc(100vh - 170rpx);
	padding-top: 170rpx;
	background: url(@/static/image/login1.png) 0 0/175rpx auto no-repeat,
		url(@/static/image/login2.png) bottom right/123rpx auto no-repeat;
	overflow: hidden;
}
.wrap {
	position: relative;
	height: 60vh;
	padding: 214rpx 74rpx 28rpx;
	margin: 0 61rpx;
	background-color: #fff;
	border-radius: 20rpx;
	.logo {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 40rpx;
		color: #333;
		.icon {
			width: 150rpx;
			margin-right: 20rpx;
		}
		.cn {
			margin-bottom: 10rpx;
			font-size: 40rpx;
			font-weight: 600;
		}
		.en {
			font-size: 28rpx;
		}
	}
	.hello {
		margin: 36rpx 0;
		font-size: 28rpx;
		color: #333;
	}
	.tips {
		margin-top: 30rpx;
		font-size: 26rpx;
		color: #adadad;
		text-align: left;
	}
	.btn {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 88rpx;
		font-size: 32rpx;
		border-radius: 10rpx;
		image {
			width: 50rpx;
			margin-right: 15rpx;
		}
	}
	.wechat {
		margin-bottom: 38rpx;
		color: #fff;
		background-color: #007EFF;
	}
	.phone {
		color: #007EFF;
		border: 1px solid #007EFF;
		background-color: #fff;
		image {
			width: 40rpx;
		}
	}
	.reg {
		font-size: 28rpx;
		color: #e61717;
		text-align: right;
	}
	.agree {
		position: absolute;
		bottom: 28rpx;
		left: 0%;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		text-align: center;
		font-size: 24rpx;
		color: #ccc;
		text {
			color: #007EFF;
		}
	}
	/deep/.check {
		.checklist-box {
			margin: 0;
		}
		.checkbox__inner {
			width: 40rpx !important;
			height: 40rpx !important;
			border-radius: 50% !important;
		}
		.checkbox__inner-icon {
			top: 8rpx !important;
			left: 14rpx !important;
		}
	}
}
</style>
