<template>
  <el-main></el-main>
</template>
<script>
import { setSignedIn } from '@/utils/auth'
import { mapActions } from 'vuex'
import { ElLoading } from 'element-plus'
export default {
  name: 'Login',
  data () {
    return {}
  },
  created () {
    ElLoading.service({ lock: true })
    const code = this.$route.query.code
    if (typeof code === 'undefined') {
      const redirectURL = encodeURIComponent(window.location.href)
      setTimeout(() => (location.href = buildRedirectURL(redirectURL)), 1000)
    } else {
      this.$http
        .showLoading(false)
        .mock(false)
        .post('login/login', { code: code })
        .then(r => {
          if (r.errno === 0 && r.data.signed_in) {
            setSignedIn() // 设为已登录
            this.setUserInfo(r.data.user_info)
            localStorage.setItem('userId', r.data.user_info.user_id)
            console.log(r.data.user_info)
            setTimeout(() => this.$router.push({ path: '/index/index' }), 1000)
            localStorage.setItem('userToken', r.data.sess_id)
          } else {
            this.$message.error(r.errmsg)
            const redirectURL = encodeURIComponent(window.location.protocol + '//' + window.location.host + window.location.pathname)
            setTimeout(() => (location.href = buildRedirectURL(redirectURL)), 1500)
          }
        })
    }
  },
  methods: {
    ...mapActions({
      setUserInfo: 'user/setUserInfo'
    })
  }
}
// 组装重定向链接
const buildRedirectURL = redirectURL => {
  const loginURL = process.env.VUE_APP_SSO_LOGINURL
  const APPID = process.env.VUE_APP_SSO_APPID
  return loginURL + '?app_id=' + APPID + '&redirect_url=' + redirectURL + '&response_type=code'
}
</script>
