<template>
	<view class="login">
		<h3 style="margin-top: 100px;">学生评价位置调换系统</h3>
		<div id="self_defined_element" class="self-defined-classname ui-mt40"></div>
		<view class="intro">
			请打开钉钉APP扫码登录
		</view>
	</view>
</template>

<script>
	import Config from './config.js'
	import ddLogin from "@/static/js/ddLogin.js"
	export default {
		name:'',
		data(){
			return {
				redirectUrl : '',
				// redirectUrl : 'https://oy-desk.wucits.com',
				school_id : ''
			}
		},
		mounted(){
			// this.school_id=this.getUrlParam("school_id")
			this.school_id=1
			
			if(!this.school_id){
				this.school_id=uni.getStorageSync("school_id")
			}else{
				uni.setStorageSync("school_id",this.school_id)
			}
			
			this.redirectUrl=Config.schoolBaseData.redirectUrl+"?school_id="+this.school_id
			let token=uni.getStorageSync("token")
			
			if(!token){
				this.buildCode()
			}else{
				uni.navigateTo({
					url: "/pages/studentRanked/studentRanked"
				})
			}
		},
		methods:{
			doLogin(code){
				console.log("zhixinglema",this.school_id);
				this.$api.sendRequest({
					url: `/mobile/getUserInfoByScanCode`,
					method : 'post',
					data : {
						code,
						school_id : this.school_id
					},
					success: res => {
						console.log(res,code,"denglu");
						this.$store.commit("setTeacherInfo",res.data.teacher)
						uni.setStorageSync('token', res.data.teacher.token)
						uni.navigateTo({
							url:'/pages/studentRanked/studentRanked'
						})
						// window.location.href = this.redirectUrl;
					},
					error: res => {
				
					}
				})
			},
			getUrlParam(name) {
				var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				var r = window.location.search.substr(1).match(reg);
				if (r != null) return unescape(r[2]);
				return null;
			},
			buildCode(){
				console.log(this.redirectUrl,"this.redirectUrl")
				window.DTFrameLogin(
					{
						id: 'self_defined_element',
						width: '300',
						height: '300',
					},
					{
						redirect_uri: encodeURIComponent(this.redirectUrl),
						client_id: Config.schoolBaseData.client_id,
						scope: 'openid',
						response_type: 'code',
						prompt: 'consent',
					},
					(loginResult) => {
						const {redirectUrl, authCode, state} = loginResult;
						console.log(authCode,"ininini?",redirectUrl);
						this.doLogin(authCode)
						// 这里可以直接进行重定向
						
						// 也可以在不跳转页面的情况下，使用code进行授权
						
					},
					(errorMsg) => {
						// 这里一般需要展示登录失败的具体原因
						console.log(`Login Error: ${errorMsg}`);
					},
				);
			}
		}
	}
</script>

<style scoped>
	.login{
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		
	}
	.self-defined-classname {
		width: 300px;
		height: 300px;

		background-color: rebeccapurple;
	}
	.intro{
		color: #333;
		margin-top: 20px;
	}
</style>