<template>
		<view class="login-container">
			<!-- 提示登录的图标 -->
			<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
			<!-- 登录按钮 -->
			<button type="primary" class="btn-login" @click="getToken">一键登录</button>		
			<!-- 登录提示 -->
			<view class="tips-text">登录后尽享更多权益</view>
		</view>

</template>

<script>
	// 按需导入 mapMutations 辅助函数
	import { mapMutations, mapState } from 'vuex'
	
	export default {
		computed: {
			...mapState('m_user', ['recoUID']),
		},
		name:"my-login",
		data() {
			return {
				queryObj: {
					latitude: 0,
					longitude: 0
				}
			};
		},
		methods: {
			// 调用 mapMutations 辅助方法，把 m_user 模块中的 updateUserInfo 映射到当前组件中使用
			...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateLocation']),
			
			// 引导用户开启位置权限
			openSetting() {
				var that = this
				wx.showModal({
					title: '位置信息',
					content: '开启后将为你推送最近的资源',
					showCancel: true,
					cancelText: '取消',
					cancelColor: '#000000',
					confirmText: '开启',
					confirmColor: '#3CC51F',
					success: res => {
						if (res.confirm) {
							wx.openSetting({
								success(res) {
									if (res.authSetting['scope.userFuzzyLocation']) {
										
										// 获取经纬度
										wx.getFuzzyLocation({
											type: 'wgs84',
											success (res) {
											   that.queryObj.latitude = res.latitude
											   that.queryObj.longitude = res.longitude
											   that.updateLocation(that.queryObj)
											   that.getLogin()
											}
										})
									}
								},
								fail(res) {
									uni.$showMsg(res)
								}
							})
						} else if(res.cancel) {
							uni.$showMsg("需要位置权限")
						}
					}
				})
			},
			
			// 调用登录接口，换取永久的 token
			async getToken() {
				var that = this
			
				// 获取位置信息
				wx.getSetting({
					success(res) {
						if (!res.authSetting['scope.userFuzzyLocation']) {
							wx.authorize({
								scope: 'scope.userFuzzyLocation',
								success() {
									// 获取经纬度
									wx.getFuzzyLocation({
										type: 'wgs84',
										success (res) {
										   that.queryObj.latitude = res.latitude
										   that.queryObj.longitude = res.longitude
										   that.updateLocation(that.queryObj)
										   that.getLogin()
										}
									})
								},
								fail() {
									// 拒绝后引导用户开启
									if (wx.openSetting) {
										that.openSetting()
									}
									return
								}
							})
						} else {
							// 获取经纬度
							wx.getFuzzyLocation({
								type: 'wgs84',
								success (res) {
								   that.queryObj.latitude = res.latitude
								   that.queryObj.longitude = res.longitude
								   that.updateLocation(that.queryObj)
								   that.getLogin()
								}
							})
							that.getLogin()
						}
					}
				})
			},
			
			// 真正的登录逻辑
			async getLogin() {
				
				// 调用微信登录接口
				const [err, res] = await uni.login().catch(err => err)
				// 判断是否 wx.login() 调用失败
				if (err || res.errMsg !== 'login:ok') return uni.$showError('登录失败！')
				// 准备参数对象
				const query = {
					code: res.code,
					recoUID: this.recoUID
				}
				
				// 换取 token
				const { data: loginResult } = await uni.$http.get('/ucenter/mini-program-openid-uid/wxlogin', query)
				if (loginResult.code === 20000) {
					uni.$showMsg('登录成功！')
				}
				
				// 更新vuex中的token
				this.updateToken(loginResult.data.token)
				
				// // 将用户的基本信息存储到 vuex 中
				if (loginResult.data.avatar === '') {
					loginResult.data.avatar = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/'
				}
				const userInfo = {
					alias: loginResult.data.alias,
					avatar: loginResult.data.avatar,
					city: loginResult.data.city,
					uid: loginResult.data.uid,
					count: loginResult.data.count,
					isAdmin: loginResult.data.isAdmin
				}
				this.updateUserInfo(userInfo)
				
				let SocketTask = wx.connectSocket({
					url: `${uni.$wsLocation}/education/chat?uid=`+userInfo.uid,
					success(res) {
						console.log("开始连接",res)
						if (userInfo.count == 0) {
							uni.removeTabBarBadge({
								index: 2
							})
						} else {
							// 调用 uni.setTabBarBadge() 方法，为购物车设置右上角的徽标
							uni.setTabBarBadge({
								index: 2,
								text: userInfo.count + '', // 注意：text 的值必须是字符串，不能是数字
							})
						}
					}
				})
				SocketTask.onMessage( res => {
					console.log('监听',res.data)
					userInfo.count++;
					this.updateUserInfo(userInfo)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
.login-container {
	
	// 登录盒子的样式
	height: 750rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #E2F0D9;
	position: relative;
	overflow: hidden;
	
	// 绘制登录盒子底部的半椭圆造型
	&::after {
		content: ' ';
		display: block;
		position: absolute;
		width: 100%;
		height: 40px;
		left: 0;
		bottom: 0;
		background-color: white;
		border-radius: 100%;
		transform: translateY(50%);
	}
	
	// 登录按钮的样式
	.btn-login {
		width: 90%;
		border-radius: 100px;
		margin: 15px 0;
		background-color: #008000;
	}
	
	// 按钮下方提示消息的样式
	.tips-text {
		font-size: 12px;
		color: gray;
	}
}
</style>