<template>
	<view>
		自动登录中...
	</view>
</template>

<script>
	export default {
		data() {
			return {
				code:"",
				state: ''
			}
		},
		mounted() {
			this. getCode()
		},
		methods: {
			getCode() { // 非静默授权，第一次有弹框
				let appid = 'wxac0afae9104e5e4d'
				// let local = 'http://192.168.1.16:8080'
				let local = 'https://xiaoyi.xunsoftware.com'
				let that = this
				this.code = ''
				this.state = 'index'
				this.code = this.getUrlCode().code // 截取code
				this.state = this.getUrlCode().state
				console.error('code is :>>>', this.code)
				if (this.code == null || this.code === '') { // 如果没有code，则去请求
					let redirectType = this.getUrlCode().type || 'index'
					window.location.href =
						// `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local1)}&response_type=code&scope=snsapi_userinfo&state=${redirectType}#wechat_redirect`
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=${redirectType}#wechat_redirect`
				} else {
					that.$request({
						url: that.$api.auth.getToken,
						data: {
						    code: that.code,
						    grant_type: 'social_school_doctor_user'
						},
						method: 'POST'
					}).then(res=>{
						if(res.access_token) {
							localStorage.setItem('tenant_id', res.tenant_id) // 获取登录之后的租户id
							this.$storage.setToken(res.access_token)
							this.$storage.setAuthUser(JSON.stringify(res))
							// 登录成功后跳转至/pages/index/index
							window.location.href = local + '/pages/index/index'
							// TODO
							
						} else {
							// console.error(res)
						}
					}).catch(err=>{
						if(err.error_description == '未绑定微信，请先绑定' ||  err.error_description == 'social grant failure, user is null'){
							uni.showToast({
								title: '当前微信未绑定,请先通过账号登录',
								icon:'none'
							})
							setTimeout(()=>{
								window.location.href = local + '/pages/signIn/logOn?type=1'
							},2000)
						}
						
					})
				}
			},
			getUrlCode() { // 截取url中的code方法
				var url = location.search
				this.winUrl = url
				var theRequest = new Object()
				if (url.indexOf("?") != -1) {
					var str = url.substr(1)
					var strs = str.split("&")
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
					}
				}
				return theRequest
			},
		}
	}
</script>

<style>

</style>
