import {createRouter, createWebHashHistory} from 'vue-router'
import {setupLayouts} from 'virtual:generated-layouts'
import generatedRoutes from 'virtual:generated-pages'
import {ConfigGetAction, $response, AdminStatusAction} from "~/api"
import {reGetAdmin} from "~/tool/info"
import {$favicon} from "~/tool/favicon"
import {
    useStore, useSaveTokenType, useSessionToken, useToken, useRouterActive
} from '~/store'

const no_login_list = ['login', '404'];
const $router_active = useRouterActive()
const router = createRouter({
    history: createWebHashHistory(import.meta.env.BASE_URL), routes: setupLayouts(generatedRoutes)
})

const updateRouterActive = (matched) => {
    matched.shift()
    const last = matched[matched.length - 1]
    if (no_login_list.indexOf(last.name) !== -1) return
    setTimeout(() => {
        $router_active.value = matched.map((item) => {
            return {
                title: 'title' in item.meta ? item.meta.title : item.name,
                key: item.name
            }
        })
    })
}

router.beforeEach(async (to, from, next) => {
    window.$loading.start()
    const $store = useStore()
    if (!$store.config) {
        const response = await ConfigGetAction(['Logo', 'Favicon', 'Login欢迎图片', '网站名称'])
        $response(response, () => {
            $store.config = response.data
        })
        $favicon($store.config['Favicon'])
    }
    document.title = ('title' in to.meta && to.meta.title !== '首页') ? `${to.meta.title} ${$store.config['网站名称']}` : $store.config['网站名称']
    if (no_login_list.indexOf(to.name) === -1) {
        const $save_token_type = useSaveTokenType()
        let $token;
        if ($save_token_type.value === 'local') {
            $token = useToken()
        } else {
            $token = useSessionToken()
        }
        if ($token.value === '') {
            next('/login?f=' + encodeURIComponent(to.fullPath))
            setTimeout(() => {
                window.$loading.finish()
            })
        } else {
            const response = await AdminStatusAction()
            $response(response, () => {
                if (!$store.admin_info) reGetAdmin()
                updateRouterActive(to.matched.map(item => item))
                next()
            }, next)
            setTimeout(() => {
                window.$loading.finish()
            })
        }
    } else {
        next()
        setTimeout(() => {
            window.$loading.finish()
        })
    }
})
export default router
