<template>
    <div v-if="isType === ''" class="hc-body-loading">
        <div v-if="isErrorShow" class="error-page">
            <div class="img" :style="`background-image: url(${svg403});`" />
            <div class="content">
                <h1>401</h1>
                <div class="desc">抱歉，身份验证异常，请重新进入</div>
            </div>
        </div>
    </div>
    <HcDataForm v-if="isType === 'data-fill'" :option="formNode" />
    <HcLogForm v-if="isType === 'log-fill'" :option="formNode" />
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useAppStore } from '~src/store'
import { useRoute } from 'vue-router'
import svg403 from '~src/assets/view/403.svg'
import { isNullES } from 'js-fast-way'
import HcDataForm from './components/data-form.vue'
import HcLogForm from './components/log-form.vue'
import { userLogin } from '~api/user'

//初始变量
const useRoutes = useRoute()
const store = useAppStore()

//变量
const isErrorShow = ref(false)
const isType = ref('')
const formNode = ref({})

//渲染完成
onMounted(() => {
    const { user, source } = useRoutes.query
    if (!isNullES(user)) {
        const userInfo = JSON.parse(decodeURIComponent(user))
        store.setIsSource(source)
        useAppLoginApi(userInfo)
    } else {
        formRender()
        isErrorShow.value = true
        postMsg('参数异常', 'error')
    }
})

//请求授权登录
const useAppLoginApi = async (form) => {
    const { error, status, res } = await userLogin(form)
    if (!error && status === 200) {
        //设置token和用户信息
        store.setTokenVal(res['access_token'])
        store.setRefreshTokenVal(res['refresh_token'])
        store.setTenantId(res['tenant_id'])
        store.setUserInfo(res)
        //设置主题
        store.setTheme('light')
        store.setThemeVal('light')
        //处理其他数据
        setTimeout(() => {
            setFormType()
            isErrorShow.value = false
        }, 1000)
    } else {
        formRender()
        isErrorShow.value = true
        postMsg('身份验证异常', 'error')
    }
}

const formRender = () => {
    window?.postMessage({
        type: 'formRender',
        source: 'web',
        data: {},
    })
}

//弹出提示
const postMsg = (title, icon) => {
    window?.postMessage({
        type: 'msg',
        source: 'web',
        data: {
            title: title,
            icon: icon,
        },
    })
}

//处理数据
const setFormType = () => {
    const { type, node } = useRoutes.query
    if (isNullES(type)) {
        formRender()
        isErrorShow.value = true
        postMsg('身份验证异常', 'error')
        return
    }
    //处理其他数据
    formNode.value = node ? JSON.parse(decodeURIComponent(node)) : {}
    isType.value = type
}
</script>

<style lang="scss" scoped>
@import "../../styles/error/app-auth.scss";
</style>

<style lang="scss">
html, body, #app {
    background-color: white;
}
</style>
