<template>
  <div><h2>登录中，请稍后...</h2></div>
</template>
<script>
import db from '@/utils/localstorage'
import { randomNum } from '@/utils'
import axios from 'axios'

export default {
  name: 'ssoLogin',
  data() {
    return {
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      randomId: randomNum(24, 16),
      imageCode: '',
      page: {
        width: window.screen.width * 0.5,
        height: window.screen.height * 0.5
      }
    }
  },
  mounted() {
    db.clear()
    this.handleLogin()
  },
  destroyed() {
    window.removeEventListener('message', this.resolveSocialLogin)
  },
  methods: {
    getCodeImage() {
      axios({
        method: 'GET',
        url: `${this.codeUrl}?key=${this.randomId}`,
        responseType: 'arraybuffer'
      })
        .then((res) => {
          return (
            'data:image/png;base64,' +
            btoa(
              new Uint8Array(res.data).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                ''
              )
            )
          )
        })
        .then((res) => {
          this.imageCode = res
        })
        .catch((e) => {
          if (e.toString().indexOf('429') !== -1) {
            this.$message({
              message: this.$t('tips.tooManyRequest'),
              type: 'error'
            })
          } else {
            this.$message({
              message: this.$t('tips.getCodeImageFailed'),
              type: 'error'
            })
          }
        })
    },
    handleTabClick(tab, event) {
      this.tabActiveName = tab.name
    },
    resolveLogo(logo) {
      return require(`@/assets/logo/${logo}`)
    },
    handleLogin() {
      const token = this.getUrlKey('token')
      if (token == null) {
        alert('非法请求!')
      } else {
        this.$post('/system/user/getThirdPartyUserInfo', {
          token: token
        }).then((r) => {
          const data = r.data
          if (data.userId == null) {
            alert('请检查相关参数!')
          } else {
            this.$login('auth/oauth/token', {
              username: data.userId,
              password: '1234qwer',
              key: this.randomId
            })
              .then((r) => {
                const data = r.data
                this.$store.commit('account/setThirdPartyToken', token)
                this.saveLoginData(data)
                this.getUserDetailInfo()
                this.loginSuccessCallback()
              })
              .catch((error) => {
                console.error(error)
                // eslint-disable-next-line no-undef
                that.loading = false
                // eslint-disable-next-line no-undef
                that.getCodeImage()
              })
          }
        })
      }
    },
    getUrlKey(name) {
      return (
        decodeURIComponent(
          (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
            location.href
          ) || [, ''])[1].replace(/\+/g, '%20')
        ) || null
      )
    },
    saveLoginData(data) {
      this.$store.commit('account/setAccessToken', data.access_token)
      this.$store.commit('account/setRefreshToken', data.refresh_token)
      const current = new Date()
      const expireTime = current.setTime(
        current.getTime() + 1000 * data.expires_in
      )
      this.$store.commit('account/setExpireTime', expireTime)
    },
    getUserDetailInfo() {
      this.$get('auth/user')
        .then((r) => {
          this.$store.commit('account/setUser', r.data.principal)
          this.$message({
            message: this.$t('tips.loginSuccess'),
            type: 'success'
          })
          this.loading = false
          this.$router.push('/demp/alertcenter/index')
        })
        .catch((error) => {
          this.$message({
            message: this.$t('tips.loginFail'),
            type: 'error'
          })
          console.error(error)
          this.loading = false
        })
    },
    loginSuccessCallback() {
      this.$get('system/user/success').catch((e) => {
        console.log(e)
      })
    }
  }
}
</script>
