<template>
  <!-- 绍兴研学授权 -->
  <div>
    <p class="authorize">授权中...</p>
  </div>
</template>
<script>
import yxAxios from '@/https/yxAxios'
export default {
  data() {
    return {
      appId: 'wx1305e88d2bc74073',
    }
  },
  mounted() {
    let code = this.getQueryVariable('code')
    let openId = localStorage.getItem('openId')
    if (!openId) {
      if (!code) {
        // location.href = `https://ocp.sxsedu.net/szsh/usercenter/api/wx/wx1305e88d2bc74073/getCode/yx_zlyx`
        location.href = `https://ocp.sxsedu.net/szsh/usercenter/api/wx/wx1305e88d2bc74073/getCode/yx_test_auth`
      } else {
        // 通过code获取openId和token
        this.$toast.loading({
          message: '加载中...',
          duration: 0,
          forbidClick: true,
        })
        yxAxios
          .get(`https://ocp.sxsedu.net/szsh/usercenter/api/wx/wx1305e88d2bc74073/getMsgByCode?appId=wx1305e88d2bc74073&code=${code}`)
          .then((res) => {
            this.$toast.clear()
            console.log(res)
            if (res.data.code == 200) {
              localStorage.setItem('openId', res.data.data.openid)
              localStorage.setItem('unionId', res.data.data.unionId)
              localStorage.setItem('nicknameUser', res.data.data.nickname)
              localStorage.setItem('headImgUrl', res.data.data.headImgUrl)
              this.backPage()
            } else {
              setTimeout(() => {
                localStorage.removeItem('openId')
                // location.href = `https://ocp.sxsedu.net/szsh/usercenter/api/wx/wx1305e88d2bc74073/getCode/yx_zlyx`
                location.href = `https://ocp.sxsedu.net/szsh/usercenter/api/wx/wx1305e88d2bc74073/getCode/yx_test_auth`
              }, 2000)
            }
          })
      }
    } else {
      this.backPage()
    }
  },
  methods: {
    backPage() {
      let prePage = localStorage.getItem('prePage')
      let prePageQuery = localStorage.getItem('prePageQuery')
      if (prePage) {
        this.$router.push({ name: prePage, query: JSON.parse(prePageQuery) })
      } else {
        this.$router.push({ name: 'Home' })
      }
    },
    // 获取链接参数
    getQueryVariable(variable) {
      // 取地址栏参数
      var query = window.location.search.substr(1)
      if (!query && window.location.hash.indexOf('?') > -1) {
        query = window.location.hash.split('?')[1]
      }
      var vars = query.split('&')
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=')
        if (pair[0] === variable) {
          return pair[1]
        }
      }
      return false
    },
  },
}
</script>
<style>
.authorize {
  font-size: 32px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
