<script setup>
import { onMounted, ref } from 'vue'
import { RouterLink, RouterView } from 'vue-router'
import Header from './views/header.vue';
import axios from 'axios';
import { userInfoStore } from './stores/counter'

const store = userInfoStore()
const userName = ref('')
const admin = ref(false)
const isLogin = ref(false)
onMounted(() => {
  console.log(11, store)
  // 通过 grant_code 获取登录信息
  let isGrantCode = getUrlParam(window.location.href, 'grant_code')
  axios.defaults.headers = { 'content-type': 'application/json;charset=utf-8' }
  if (isGrantCode) {
    let params = {
      grantCode: isGrantCode,
      redirectUri: "https://cloud.cocorobo.cn/testapi"
    }
    axios.post('//cloud.cocorobo.cn/api/getAccessToken', JSON.stringify(params)).then(res => {
      console.log(res)
      let accessTokenParams = {
        accessToken: res.data.data.accessToken
      }
      axios.post('//cloud.cocorobo.cn/api/getUserInfo', JSON.stringify(accessTokenParams)).then(r => {
        console.log(r,r.data.code,r.data.data)
        if (r.data.code == 0) {
          isLogin.value = true
          userName.value = r.data.data.userName
          let userInfo = r.data.data
          if (userInfo.currentRole == "areaAdministrator" || userInfo.currentRole == "userAdministrator" || userInfo.currentRole == "securityAuditor" || userInfo.currentRole == "schoolAdministrator" || userInfo.currentRole == "schoolSecurityAuditor" || userInfo.currentRole == "teacher") {
            admin.value = true
          }
          store.user = r.data.data
        } else {

        }
      })
    })
  }

})


const getUrlParam = (urlStr, urlKey) => {
  const url = new URL(urlStr) // 字符串转换成url格式
  const paramsStr = url.search.slice(1) // 获取'?'后面的参数字符串
  const paramsArr = paramsStr.split('&') // 分割'&'字符 获得参数数组
  for (let i = 0; i < paramsArr.length; i++) {
    const tempArr = paramsArr[i].split('=')
    if (tempArr[0] === urlKey) {
      return tempArr[1]
    }
  }
}


</script>

<template>
  <Header :admin="admin" :isLogin="isLogin" :userName="userName"></Header>
  <keep-alive>
    <router-view></router-view>
  </keep-alive>
</template>

<style scoped></style>
