<template>
	<view>
		<u-top-tips ref="uTips"></u-top-tips>
	</view>
</template>

<script>
	const NET = require('../../utils/request')
	const API = require('../../config/api')
	export default {
		data() {
			return {}
		},
		onReady() {
			this.appLoginWx()
		},
		methods: {
			//  获取个人数据
			getUserInfo(info) {
				NET.request(API.WxLogin, uni.getStorageSync("wxLoginData"), 'POST').then(res => {
					uni.setStorage({
						key: 'token',
						data: res.data.token
					});
					uni.setStorage({
						key: 'userData',
						data: {
							headImage: info.userInfo.avatarUrl,
							userName: res.data.name,
							userId: res.data.userId,
						}
					});
					uni.switchTab({
						url: '/pages/index/index'
					});
				}).catch(error => {
					this.$refs.uTips.show({
						title: '微信登录授权失败',
						type: 'warning',
					})
				})
			},
			//  获取登录权限
			appLoginWx() {
				uni.getProvider({
					service: 'oauth',
					success: (res) => {
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								success: (res2) => {
									uni.getUserInfo({
										provider: 'weixin',
										success: (info) => {
											uni.setStorage({
												key: 'wxLoginData',
												data: {
													code: res2.code,
													encryptedData: info.encryptedData,
													iv: info.iv,
													rawData: info.rawData,
													signature: info.signature,
												}
											});
											this.getUserInfo(info)
										},
										fail: () => {
											this.$refs.uTips.show({
												title: '微信登录授权失败',
												type: 'warning',
											})
										}
									})
								},
								fail: () => {
									this.$refs.uTips.show({
										title: '微信登录授权失败',
										type: 'warning',
									})
								}
							})
						} else {
							this.$refs.uTips.show({
								title: '请先安装微信或升级版本',
								type: 'warning',
							})
						}
					}
				});
			},
		},
	}
</script>

<style>
</style>
