<template>
  <div></div>
</template>

<script>
export default {
    name: 'LoginSucc',
    data () {
        return {}
    },
    created () {
        this.getParams()
        // 先判断 query 有没有 token, 如果有就进入目标页开始定时刷新 token, 否则进入登录页
        // 在地址栏直接进入的情况: 登录页初始化时判断 token 没过期则跳转首页, 首页初始化时 token 过期则跳转登录页
        // 在登录成功后定期刷新 token
    },
    methods: {
        // 保存参数
        getParams () {
            const { url, jwtToken: token, refreshTokenTime: time, openId, schoolCode, companyId } = this.$route.query
            this.$store.commit('saveAccessToken', token || '')
            this.$store.commit('saveExpireTime', time || '')
            this.$store.commit('saveOpenId', openId || '')
            this.$store.commit('saveSchoolCode', schoolCode || '')
            this.$store.commit('saveCompanyId', companyId || '')
            if (token) {
                if (time && time > Date.now()) {
                    this.getCurrentUserInfo()
                    setTimeout(this.refreshToken, time - Date.now())
                    this.$router.replace(url === '/login' ? '/' : url)
                } else {
                    this.refreshToken(url)
                }
            } else {
                this.$router.replace('/login')
            }
        },
        // 刷新 token
        refreshToken (url) {
            this.$api.loginApi.refreshToken().then(res => {
                const { Status, Data } = res.data
                if (Status) {
                    const refreshTime = Data.refreshTime - 8 * 60 * 60 * 1000
                    this.$store.commit('saveAccessToken', Data.token)
                    this.$store.commit('saveExpireTime', refreshTime)
                    setTimeout(this.refreshToken, refreshTime - Date.now())
                    if (url) {
                        this.getCurrentUserInfo()
                        this.$router.replace(url === '/login' ? '/' : url)
                    }
                }
            })
        },
        getCurrentUserInfo () {
            setTimeout(() => {
                this.$api.platBaseApi.getCurrentUserInfo().then(res => {
                    let data = res.data
                    if (data.Status) {
                        this.$store.commit('saveUserInfo', data.Data)
                    }
                }).catch(() => {})
            }, 300)
        }
    }
}
</script>

<style>
</style>
