import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
import { userToken } from '@/composables/config'
const pages = import.meta.glob('../views/*.vue')

let routes: Array<RouteRecordRaw> = []
Object.keys(pages).forEach((path: string) => {
    const math = path.match(/\.\/views(.*)\.vue$/)
    if (math) {
        const name = math[1].toLowerCase()
        routes.push({
            name: name.replace('/', ''),
            path: name === '/home' ? '/' : name.replace(/-/g, '/'),
            component: pages[path], // () => import('./views/*.vue')
        })
    }
    return {}
})

routes = routes.concat([{ path: '/:pathMatch(.*)', redirect: '/' }])

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

// 白名单路由
const whiteList = ['/login', '/language', '/reset/password']

// 路由守卫
router.beforeEach((to, from, next) => {
    // 获取登录状态
    const isLoggedIn = userToken.value // 假设使用token来判断登录状态

    if (isLoggedIn) {
        // 已登录状态
        next()
    } else {
        // 未登录状态
        if (whiteList.includes(to.path)) {
            // 在白名单中，允许访问
            next()
        } else {
            // 不在白名单中，重定向到登录页
            next('/login')
        }
    }
})

export default router
