<script setup>
import { onMounted, ref, inject } from 'vue'
import { courseUrl, registerSetCourseUrl } from '@/composables/useCourseIframe'
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,userCurrent,pageGotype } from './stores/counter'

const route = useRoute()
const store = userInfoStore()
const CurrentRole = userCurrentRole()
const Current = userCurrent()
const setgotype = pageGotype()
const lang = inject('lang')

const name = ref('')
const isShow = ref(true)
const setTimeState = ref(null)
const topUserInfo = ref({})

onMounted(() => {
  registerSetCourseUrl()
  // 通过 code 获取登录信息
  let isGrantCode = getUrlParam(window.parent.location.href, 'grant_code')
  let ticket = getUrlParam(window.parent.location.href, 'ticket')
  let userid = getUrlParam(window.parent.location.href, 'userid') 
  // let userid = '0c3735c9-a2ef-11ef-9b30-005056b86db5'
  let gotype = getUrlParam(window.parent.location.href, 'gotype')
  console.log('gotype',gotype);
  setgotype.setpageType(gotype);
  
  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
            let isBjt = localStorage.getItem('isBjt')
            let userid = localStorage.getItem('userid')
            let username = localStorage.getItem('username')
            if(isBjt == 1){
              if(r.data.data.userName != username){
                top.U.alert("与绑定用户的姓名不符，请重新登录!");
                linkLogin()
                return
              }
              checkEduid(r.data.data.eduId).then(res3 => {
                console.log(res3);
                if(res3 && res3.value && res3.value.length && res3.value[0].length){
                  top.U.alert("该用户已绑定其他账号，请重新登录!");
                  linkLogin()
                  return
                }else {
                  localStorage.removeItem('isBjt')
                  localStorage.removeItem('userid')
                  localStorage.removeItem('username')
                  setEduid(userid, r.data.data.eduId)
                  setStateUserinfo(userid)
                }
              })
            }
            else{
              userInfo(r.data.data)
            }
          }
        })
      } else {
        linkLogin()
      }
    })
  }else if(ticket){
    axios.get(`https://pbl.cocorobo.cn/api/bat/getToken?ticket=${ticket}`)
      .then(r => {
        if (r.status === 200 && r.data.data && r.data.data.result) {
          console.log(r.data.data.result)
          name.value = r.data.data.result.name
          userInfo2(r.data.data.result)
        }else {
          top.location.href = `https://bjt.baoan.edu.cn/manage/?baojiaotong=1&service=https://cloud.cocorobo.cn/ai.html`
        }
      })
  }else if(userid){
    selectUser2(userid)
  } else {
    linkLogin()
  }
})

const linkLogin = () => {
  
  if(window.location.href.indexOf("localhost")>-1){
    isShow.value = false
  }else{
    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) => {
  // eduId  - 教育ID
  // userId  - 用户id
  // 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.setUserCurrentRole(data.currentRole)
    Current.setUserCurrent(data)
    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;
    let diqu = `${data.schoolName}&${data.schoolCode}&${data.orgName}&${data.orgCode}`
    if (data.telephoneNumber) {
      top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/batchRegistrationSzdjg3", [data.userName, data.telephoneNumber + '@szdjg.com', '16ace517-b5c7-4168-a9bb-a9e0035df840', data.schoolName || "", data.telephoneNumber, userGrand, userIdentity, data.userId, diqu, data.eduId], function (r) {
        // console.log('rrrrr', r)
        console.log('lang.lang', lang.lang);
        let url = lang.lang == 'hk'
					? "https://cloud.api.cocorobo.hk/api/user"
					: lang.lang == 'en'
					? "https://cloud.api.cocorobo.com/api/user"
					: "https://beta.api.cocorobo.cn/api/user";

        axios.post(url, qs.stringify(params)).then(d => {
          // store.user = top.US.userInfo
          setStateUserinfo(d.data[0][0].userid)
        })
      }, [], { "type": "POST", "withCredentials": true });
    } else {
      isShow.value = false
      ElMessageBox.alert('没有绑定手机号，请先去绑定手机号', "提示", {
        confirmButtonText: '确定',
      })
    }
  } else {
    isShow.value = false
    ElMessageBox.alert('当前账号无使用平台权限，如有需要，请联系可可乐博公司,联系方式：0755-86525412', "温馨提示", {
      confirmButtonText: '确定',
      showClose: false
    }).then(() => {
      const a = document.createElement('a');
      a.href = "https://ai.szedu.cn/";
      a.target = '_blank';
      a.rel = 'noreferrer';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      // top.location.href = "https://zy.szedu.cn/ai/"
    })
  }

}

// 同步登录信息
const userInfo2 = (data) => {

  let userIdentity = 1
  isShow.value = true
  CurrentRole.currentRole == data.user_role.join(",")
  Current.setUserCurrent(data)
  userIdentity = data.init_user_type == '1' ? 1 : 2
  let userGrand = ""

  let params = {
    openid: data.user_id,
    edu: true
  }
  axios.defaults.headers = { 'content-type': 'application/x-www-form-urlencoded' }
  axios.defaults.withCredentials = true;
  let diqu = `${data.last_top_org_name}&${data.init_v_platform_code}`
  top.U.A.Request("https://pbl.cocorobo.cn/api/pbl/batchRegistrationSzdjg3", [data.name, data.user_id + '@szdjg.com', '16ace517-b5c7-4168-a9bb-a9e0035df840', data.last_top_org_name || "", data.phone, userGrand, userIdentity, data.user_id, diqu, data.user_id], function (r) {
    // console.log('rrrrr', r)
    console.log('lang.lang2', lang.lang);
    let url = lang.lang == 'hk'
					? "https://cloud.api.cocorobo.hk/api/user"
					: lang.lang == 'en'
					? "https://cloud.api.cocorobo.com/api/user"
					: "https://beta.api.cocorobo.cn/api/user";
    axios.post(url, qs.stringify(params)).then(async d => {
      // store.user = top.US.userInfo
      // setStateUserinfo(d.data[0][0].userid)
      let userinfo = await selectUser3(d.data[0][0].userid)
      if(userinfo.eduid){
        setStateUserinfo(d.data[0][0].userid)
      }else {
        localStorage.setItem('userid', userinfo.userid)
        localStorage.setItem('username', userinfo.name)
        localStorage.setItem('isBjt', 1)
        linkLogin()
      }
    })
  }, [], { "type": "POST", "withCredentials": true });


}

const setStateUserinfo = (userid) => {
  selectUser(userid)
  // 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.setUserInfo(top.US.userInfo) 
  }, 1000)
}

// 优化selectUser，结合settimeoutUserinfo的逻辑，统一用户信息拉取和存储
const selectUser = (uid) => {
    // 优先使用已存在的用户信息
    var userInfo = topUserInfo.value;
    var panId = userInfo && userInfo.accountNumber;
    if (panId) {
        return;
    }

    // 拉取用户信息并处理
    const requestUser = () => {
        top.U.A.Request(`${top.US.Config.pbl}selectUser?userid=${uid}`, [], function (res) {
            if (res && res.value && res.value.length && res.value[0].length && res.value[0][0].userid) {
                // 拉取成功，存储用户信息
                isShow.value = false;
                top.US.userInfo = res.value[0][0];
                topUserInfo.value = res.value[0][0];
                top.U.UF.Cookie.set("cocoroboLoginType=2");
                store.setUserInfo(res.value[0][0]);
                setTimeout(() => {
                  top.US.userInfo = res.value[0][0];
                }, 5000)
                setTimeout(() => {
                  top.US.userInfo = res.value[0][0];
                }, 60000);
            } else {
                top.U.alert("获取用户信息失败，正在重试!");
                requestUser();
            }
        }, [], { "type": "GET", "withCredentials": true });
    };

    try {
        requestUser();
    } catch (error) {
        top.U.alert("登录失败，正在重试!");
        requestUser();
    }
}

const selectUser2 = (uid) => {
    // 优先使用已存在的用户信息
    var userInfo = topUserInfo.value;
    var panId = userInfo && userInfo.accountNumber;
    if (panId) {
        return;
    }

    // 拉取用户信息并处理
    const requestUser = () => {
      axios.get(`https://pbl.cocorobo.cn/api/pbl/selectUser?userid=${uid}`, { withCredentials: true })
        .then(res => {
          console.log(res);
          if (res && res.data && res.data.length && res.data[0].length && res.data[0][0].userid) {
              // 拉取成功，存储用户信息
              isShow.value = false;
              topUserInfo.value = res.data[0][0];
              store.setUserInfo(res.data[0][0]);
          } else {
              requestUser();
          }
      })
    };

    try {
        requestUser();
    } catch (error) {
        requestUser();
    }
}

const selectUser3 = async (uid) => {
    // 拉取用户信息并处理
    const requestUser = async () => {
        try {
            const res = await axios.get(`https://pbl.cocorobo.cn/api/pbl/selectUser?userid=${uid}`, { withCredentials: true });
            console.log(res);
            if (res && res.data && res.data.length && res.data[0].length && res.data[0][0].userid) {
                // 拉取成功，存储用户信息
                let userinfo = res.data[0][0];
                return userinfo;
            } else {
                return await requestUser();
            }
        } catch (error) {
            return await requestUser();
        }
    };

    return await requestUser();
}

const setEduid = async (userid, eduId) => {
  const res = await axios.get(`https://pbl.cocorobo.cn/api/pbl/setEduid?userid=${userid}&eduid=${eduId}`);
  console.log(res);
}

const checkEduid = async (eduId) => {
  const res = await axios.get(`https://pbl.cocorobo.cn/api/pbl/checkEduid?eduid=${eduId}`);
  console.log(res);
  return res
}



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: 100vh;">
    <router-view></router-view>
  </div>
  <iframe :src="courseUrl" allow="camera *; microphone *;display-capture;midi;encrypted-media;clipboard-write;clipboard-read" :webkitallowfullscreen="true" :mozallowfullscreen="true" :allowfullscreen="true"  class="courseIframe" v-if="courseUrl"></iframe>
  <!-- </keep-alive> -->
</template>

<style scoped></style>

<style>
.courseIframe {
  width: 100vw;
  height: 100vh;
  position: fixed;
  z-index: 99999;
  top: 0;
  left: 0;
  border: none;
}
</style>
