<template>
	<view>
		cas登录
		<el-dialog v-model="DeptShow" title="请选择要登录的科室" width="40%" >
			<div style="word-break: break-all" v-loading="Loading">
				 <el-radio-group v-model="SelectDeptId">
				    <el-radio v-for="(item,index) in dept_json" :key="index" :label="item.deptId">{{item.deptName}}</el-radio>
				  </el-radio-group> 
			</div>
			 <template #footer>
			      <div class="dialog-footer">
			        <el-button type="primary" @click="SelectDeptFunc()">
			          确定
			        </el-button>
			      </div>
			    </template>
		</el-dialog>
	</view>
</template>

<script setup>
	import {
		ChangeDefaultDept
	} from "@/api/api.js";
	import {
		ElMessage
	} from 'element-plus'
	import {
		ref,nextTick,onMounted
	} from 'vue'
	let dept_json=ref([])
	let DeptShow=ref(false)
	let Loading=ref(false)
	let SelectDeptId=ref('')
	let access_token=ref('')
	const SelectDeptFunc=()=>{
		if(SelectDeptId.value==''){
			ElMessage.error("请选择科室")
			return false
		}
		Loading.value=true
		ChangeDefaultDept({
			deptid:SelectDeptId.value
		}).then(res => {
			if (res.status) {
				access_token.value=res.data.token
				sessionStorage.setItem('token', access_token.value);
				sessionStorage.setItem('refreshToken', res.data.refresh_token);
				setTimeout(()=>{
					 login()
				},300)
				
			}else{
				ElMessage.error(res.msg)
			}
		})
	}
	const login=()=>{
		var token = sessionStorage.getItem('token');
		console.log(token)
		if (token!=null && token == access_token.value) {
			//window.location.href = "./#/yewu/mainList"
				window.location.href = "./#/dashboard"
		}else{
			ElMessage.error("登录失败")
		}
	}
	onMounted(()=>{
		access_token.value=getParameterByName('access_token')
		let refresh_token=getParameterByName('refresh_token')
		let dept_arr=getParameterByName('dept_arr')
		sessionStorage.setItem('token', access_token.value);
		sessionStorage.setItem('refreshToken', refresh_token);
		
		if(!!dept_arr){
			 try {
			        dept_json.value = JSON.parse(decodeURIComponent(dept_arr));
			        console.log(dept_json.value);
			      } catch (e) {
			        console.error('JSON 解析失败');
			      }
			 
		}
		if(dept_json.value.length>1){
			DeptShow.value=true
		}else{
			login()
		}
 
		
	})
	//获取url参数
	    function getParameterByName(name, url) {
	        if (!url) url = decodeURIComponent(window.location.href)
	        name = name.replace(/[\[\]]/g, '\\$&')
	        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
	            results = regex.exec(url)
	        if (!results) return null
	        if (!results[2]) return ''
	        return decodeURIComponent(results[2].replace(/\+/g, ' '))
	    }
</script>

<style>
</style>