<template>
	<view>
		<view v-if="showLogin">
			<login :ocode="ocode" :appkey="appkey" scope="snsapi_userinfo" :visible="visible" @success="loginSuccess"
				@fail="loginFail" @cancel="loginCancel" />
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 获取用户信息
				ocode: '1015730314',
				// 商户appkey
				// appkey: '3183DC96A6DABA8D',
				appkey: '9D6ACFE8CF9AFD07',
				// 是否授权可见
				visible: false,
				// 是否启动授权
				showLogin: false,
				// 获取用户信息
				appid: 'wxd6f090391d410534',
			}
		},
		onLoad() {
			this.hasUserInfo()
		},
		methods: {
			// 检查是否存在用户信息
			hasUserInfo() {
				let userInfo = uni.getStorageSync('userInfo');
				console.log(userInfo);
				if (userInfo) {
					uni.navigateTo({
						url: "/pages/home/home"
					})
				} else {
					console.log("重新授权");
					this.showLogin = true
					this.visible = true
				}
			},

			// 授权成功回调
			loginSuccess(res) {
				console.log(res);
				console.log("成功");
				let wxcode = res.detail.wxcode
				// 获取wxcode后请求登录
				this.login(wxcode)
			},
			// 授权失败回调
			loginFail() {
				console.log("授权失败");
				uni.showModal({
					title: '提示',
					content: '授权：请先领取校园卡、并激活！',
					confirmText: '领取',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: "/pages/qr_code/qr_code"
							});
						} else if (res.cancel) {
							uni.reLaunch({
								url: "/pages/404/404"
							})
						}
					}
				});
			},
			// 授权取消回调
			loginCancel() {
				console.log("取消");
				uni.showModal({
					title: '提示',
					content: '请先授权，否则无法使用该功能',
					confirmText: '授权',
					success: (res) => {
						if (res.confirm) {
							uni.reLaunch({
								url: "/pages/index/index"
							})
						} else if (res.cancel) {
							uni.reLaunch({
								url: "/pages/404/404"
							})
						}
					}
				});
			},

			async login(wxcode) {
				console.log(123);
				let res = await this.$myRequest({
					url: "/attendance/api/system/user/login/app",
					method: "post",
					data: {
						redirect_uri: `mnp://${this.appid}`,
						wxcode
					}
				})
				console.log(res);
			}
		}
	}
</script>

<style lang="scss" scoped>

</style>
