<template>
    <div v-loading="loading" class="hc-body-loading" element-loading-text="授权登录中...">
        <div v-if="isErrorShow" class="error-page">
            <div :style="`background-image: url(${svg403});`" class="img" />
            <div class="content">
                <h1>403</h1>
                <div class="desc">抱歉，token授权登录异常，请重新进入</div>
                <div class="actions">
                    <el-button block size="large" type="primary" @click="toLoginTap">手动登录</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useAppStore } from '~src/store'
import { loginByToken } from '~api/user'
import { setAppName } from '~uti/tools'
import { useRoute, useRouter } from 'vue-router'
import svg403 from '~src/assets/view/403.svg'
import { initUserConfigInfo, setRouterData } from '~sto/user'
import { getObjVal, isNullES } from 'js-fast-way'

//初始变量
const router = useRouter()
const useRoutes = useRoute()
const useAppState = useAppStore()

//先清理下缓存
useAppState.clearStoreData()

//变量
const loading = ref(true)
const isErrorShow = ref(false)

//渲染完成
onMounted(() => {
    // http://档案的域名/#/auth?token=xxxxxxx
    const token = useRoutes?.query?.token
    if (!isNullES(token)) {
        isErrorShow.value = false
        loginByTokenApi({
            token: token,
        })
    } else {
        loading.value = false
        isErrorShow.value = true
    }
})

//请求授权登录
const loginByTokenApi = async (form) => {
    const { error, code, data } = await loginByToken(form)
    const res = getObjVal(data)
    if (!error && code === 200 && res) {
        useAppState.setTokenVal(res['access_token'])
        useAppState.setRefreshTokenVal(res['refresh_token'])
        useAppState.setTenantId(res['tenant_id'])
        useAppState.setUserInfo(res)
        await setRouterData()
        await initUserConfigInfo()
        loading.value = false
        isErrorShow.value = false
        //设置标题
        useAppState.setTitle('')
        useAppState.setLogoIcon('')
        useAppState.setLogoName('')
        setAppName('')
        window?.$message?.success('授权登录成功')
        router.push({ path: '/home/index' })
    } else {
        window.$message?.error('授权登录失败')
        isErrorShow.value = true
        loading.value = false
    }
}

//跳转登陆
const toLoginTap = () => {
    router.push({ path: '/login' })
}
</script>

<style lang="scss" scoped>
@import "../../styles/error/style.scss";
.hc-body-loading {
    position: relative;
    height: 100%;
    width: 100%;
}
</style>
