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

<script setup>
import {ref, onMounted} from "vue";
import {useAppStore} from "~src/store";
import {loginByToken} from "~api/user"
import {useRouter, useRoute} from 'vue-router'
import svg403 from '~src/assets/view/403.svg';
import {initUserConfigInfo, setRouterData} from "~sto/user";
import {getObjNullValue} from "vue-utils-plus"

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

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

//渲染完成
onMounted(() => {
    // 域名后加  /#/auth?token=xxxxxxx&account=aaaa&timestamp=1670233144838&timeInterval=300&moduleCode=UTF-8
    const { token, account, timestamp, timeInterval, moduleCode } = useRoutes?.query;
    if (token && account && timestamp && timeInterval && moduleCode) {
        isErrorShow.value = false
        loginByTokenApi({
            token: token,
            account: account,
            timestamp: timestamp,
            timeInterval: timeInterval,
            moduleCode: moduleCode,
        });
    } else {
        loading.value = false
        isErrorShow.value = true
    }
})

//请求授权登录
const loginByTokenApi = async (form) => {
    const {error, code, data} = await loginByToken(form)
    const res = getObjNullValue(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
        window?.$message?.success('授权登录成功');
        await 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>
