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

const route = useRoute()
const store = userInfoStore()
const CurrentRole = userCurrentRole()
const name = ref('')
const isShow = ref(true)
const setTimeState = ref(null)

onMounted(() => {
  // 通过 grant_code 获取登录信息
  let isGrantCode = getUrlParam(window.parent.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)
      if (res.data.code == 0) {
        let accessTokenParams = {
          accessToken: res.data.data.accessToken
        }
        axios.post('//cloud.cocorobo.cn/api/getUserInfo', JSON.stringify(accessTokenParams)).then(r => {
          
          if (r.data.code == 0) {
            console.log(r.data.data)
            // store.user = r.data.data
            name.value = r.data.data.userName
            userInfo(r.data.data)
          }
        })
      } else {
        linkLogin()
      }
    })
  } else {
    linkLogin()
  }
})

const linkLogin = () => {
  top.location.href = `https://sz.edu.cn/thirdauth/oauth2/authorize?service=initService&scope=all&response_type=code&app_id=f03970962b254aa29115fefd42a8eeb7&redirect_uri=https://cloud.cocorobo.cn/api`
}

// 同步登录信息
const userInfo = (data) => {
  // areaAdministrator - 安全管理员
  // userAdministrator - 用户管理员（市区级）
  // securityAuditor - 安全审计员（市区级）
  // schoolAdministrator - 用户管理员（校级）
  // schoolSecurityAuditor - 安全审计员（校级）
  // edupersonnel - 单位用户
  // teacher - 教师
  // visitorstudent - 学生
  // visitorparent - 家长
  // visitor - 访客
  // parentagency - 家长代办

  let userIdentity = 1
  if (data.currentRole == "edupersonnel" || data.currentRole == "areaAdministrator" || data.currentRole == "userAdministrator" || data.currentRole == "securityAuditor" || data.currentRole == "schoolAdministrator" || data.currentRole == "schoolSecurityAuditor" || data.currentRole == "teacher") {
    isShow.value = true
    CurrentRole.currentRole == data.currentRole
    userIdentity = 1
    let userGrand = ""
    if (data.childList && data.childList.length > 0) {
      userGrand = data.childList[0].gradeName + data.childList[0].className
    }
    let params = {
      openid: data.userId,
      edu: true
    }
    axios.defaults.headers = { 'content-type': 'application/x-www-form-urlencoded' }
    axios.defaults.withCredentials = true;
    axios.post(`https://beta.api.cocorobo.cn/api/user`, qs.stringify(params)).then(res => {
      // console.log(res, '222222222222')
      if (res.data && res.data[0][0].active == 1) {
        setStateUserinfo()
      } else {
        if (data.telephoneNumber) {
          top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/batchRegistrationSzdjg", [data.userName, data.telephoneNumber + '@szdjg.com', '16ace517-b5c7-4168-a9bb-a9e0035df840', data.schoolName, data.telephoneNumber, userGrand, userIdentity, data.userId], function (r) {
            // console.log('rrrrr', r)
            axios.post(`https://beta.api.cocorobo.cn/api/user`, qs.stringify(params)).then(d => {
              // store.user = top.US.userInfo
              setStateUserinfo()
            })
          }, [], { "type": "POST", "withCredentials": true });
        } else {
          isShow.value = false
          ElMessageBox.alert('没有绑定手机号，请先去绑定手机号', "提示", {
            confirmButtonText: '确定',
          })
        }
      }
    }).catch(e => {
      if (data.telephoneNumber) {
        top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/batchRegistrationSzdjg", [data.userName, data.telephoneNumber + '@szdjg.com', '16ace517-b5c7-4168-a9bb-a9e0035df840', data.schoolName || "", data.telephoneNumber, userGrand, userIdentity, data.userId], function (r) {
          // console.log('rrrrr', r)
          axios.post(`https://beta.api.cocorobo.cn/api/user`, qs.stringify(params)).then(d => {
            // store.user = top.US.userInfo
            if (d.data && d.data[0][0].active == 1) {
              isShow.value = false
              setStateUserinfo()
            }
          })
        }, [], { "type": "POST", "withCredentials": true });
      } else {
        isShow.value = false
        ElMessageBox.alert('没有绑定手机号，请先去绑定手机号', "提示", {
          confirmButtonText: '确定',
        })
      }

    })
  } else {
    isShow.value = false
    ElMessageBox.alert('当前账号无使用平台权限，如需体验，您需申请体验账号，查看平台内容', "温馨提示", {
      confirmButtonText: '确定',
      showClose: false
    }).then(() => {
      top.location.href = "https://zy.szedu.cn/ai/"
    })
  }

}

const setStateUserinfo = () => {
  // setTimeState
  setTimeState.value = setInterval(() => {
    if (JSON.stringify(top.US.userInfo) != '{}') {
      // store.user = top.US.userInfo
      settimeoutUserinfo()
      clearInterval(setTimeState.value)
    }
  }, 1000)
}

const settimeoutUserinfo = () => {
  setTimeout(() => {
    isShow.value = false
    console.log("top.US.userInfo", top.US.userInfo)
    store.user = top.US.userInfo
  }, 1000)
}

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>
  <!-- <keep-alive> -->
  <div v-loading="isShow" style="height: 100%;">
    <router-view></router-view>
  </div>
  <!-- </keep-alive> -->
</template>

<style scoped></style>
