<template>
    <div v-loading="loading" class="hc-body-loading" element-loading-text="授权登录中...">
        <div v-if="isErrorShow" class="error-page">
            <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 size="large" @click="toLoginTap">
                        手动登录
                    </el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useAppStore } from '~src/store'
import { useAppLogin } from '~sto/user'
import userApi from '~api/userInfo'
import { useRoute, useRouter } from 'vue-router'
import svg403 from '~src/assets/view/403.svg'

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

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

//渲染完成
onMounted(() => {
    // 域名后加  /#/auth?token=xxxxxxx
    const { token } = useRoutes.query
    console.log(token)
    if (token) {
        isErrorShow.value = false
        useAppState.setTokenVal(token)
        queryCurrentUserData()
    } else {
        loading.value = false
        isErrorShow.value = true
    }
})

//获取用户信息
const queryCurrentUserData = async () => {
    const { error, code, data } = await userApi.queryCurrentUserData()
    if (!error && code === 200) {
        await useAppLoginApi({
            tenantId: '000000',
            username: data.account,
            password: data.plaintextPassword,
            type: 'account',
        })
    } else {
        window.$message?.error('授权信息异常')
        isErrorShow.value = true
        loading.value = false
    }
}

//请求授权登录
const useAppLoginApi = async (form) => {
    loading.value = true
    useAppLogin(form).then(() => {
        loading.value = false
        isErrorShow.value = false
        window?.$message?.success('授权登录成功')
        // router.push({path: '/home/index'});
        router.push({ path: '/using/stats' })//跳转到档案统计页面
    }).catch(() => {
        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>
