<template lang="pug">
.auth(v-html="notice")
</template>

<script>
export default {
  layout: 'auth',
  data () {
    return {
      notice: 'Loading...'
    }
  },
  async mounted () {
    const code = this.$route.query.code
    const type = this.$route.query.type
    const state = this.$route.query.state.split('-')

    if (!code) { this.notice = '<p style="color: #999">非法访问，缺少授权参数"code"。<p><br><br> <a href="https://www.wyr.me" target="_blank">返回首页<a>'; this.$finishLoad(); return }

    if (type === 'weixin') {
      const { data } = await this.$axios.post(`${process.env.baseURL}/visitor/user/weixin`, {
        code,
        app: 'wx9d5e677f533d1e84'
      })

      if (data.status !== 1) {
        this.$toasted.show('微信登录失败，请重试或换用其它登录方式。', {
          position: 'top-center'
        })
        this.$finishLoad()
        return
      } else {
        try {
          window.localStorage.visitorToken = data.result.token
          window.localStorage.visitorInfo = JSON.stringify(data.result.visitorInfo)
          window.location.href = 'https://www.wyr.me/post/' + state[1] + '?hash=comment'
        } catch (_) { }
      }

      return
    }

    if (state[0] === 'weibo' || state[0] === 'qq') {
      const { data } = await this.$axios.post(`${process.env.baseURL}/visitor/user/` + state[0], {
        code
      })

      if (data.status !== 1) {
        this.$toasted.show((state[0] === 'weibo' ? '微博' : 'QQ') + '登录失败，请重试或换用其它登录方式。', {
          position: 'top-center'
        })
        this.$finishLoad()
        return
      } else {
        try {
          window.localStorage.visitorToken = data.result.token
          window.localStorage.visitorInfo = JSON.stringify(data.result.visitorInfo)
          window.location.href = 'https://www.wyr.me/post/' + state[1] + '?hash=comment'
        } catch (_) { }
      }

      return
    }

    const { data } = await this.$axios.post('/visitor/user/auth', {
      type: 'github',
      code
    })

    if (data.status !== 1) {
      this.notice = '<p style="color: #999">授权失败，请关闭页面从登陆入口再试一次。<p><br><br> <a href="https://www.wyr.me" target="_blank">返回首页<a>'
      this.$finishLoad()
      return
    }

    window.opener.authSuccess(data)
    window.close()

    this.$finishLoad()
  },
  methods: {

  }
}
</script>

<style lang="stylus" scoped>
.auth
  width 100%
  height 100%
  padding 50px
</style>
