import {createRouter, createWebHashHistory} from 'vue-router'
import {useStore} from "../store";
import {ElMessage} from "element-plus";
const router = createRouter({ 
    history: createWebHashHistory(),
    routes: [
        {
            path: '/',
            name: 'login',
            component: () => import(`../views/login/index.vue`),
            meta: {
                title: '登陆',
            },
        },
        {
            path: '/reg',
            name: 'register',
            component: () => import(`../views/register/index.vue`),
            meta: {
                title: '注册',
            },
        }
    ]
})
// 全局路由守卫
router.beforeEach((to)=>{
    // 设置网页标题
    document.title =  "电子职高校内交流平台-" + `${to.meta.title}`;
    // 获取状态管理器
    let store = useStore();
    let routers = router.getRoutes();
    // 判断用户是否已登陆，并且刷新页面
    if (store.userinfo !== null && routers.length === 2){
        router.addRoute({path: '/home', name: 'home', component: () => import("../views/home/index.vue"), meta: {title: '首页'}});
        router.addRoute("home",{path: 'chat', name:'chat', component: () => import("../views/chat/index.vue"), meta: {title: '聊天频道'}})
        router.addRoute("home",{path: 'file', name:'file', component: () => import("../views/file/index.vue"), meta: {title: '文件分享'}})
        router.addRoute("home",{path: 'voice', name:'voice', component: () => import("../views/voice/index.vue"), meta: {title: '语音频道'}})
        router.addRoute("home",{path: 'setting', name:'setting', component: () => import("../views/setting/index.vue"), meta: {title: '个人设置'}})
        return to.fullPath;
    }
    // 验证用户是否未登陆进入了其他页面
    if (to.name !== "login" && to.name !== "register" && to.name !== "404"){
        if (store.userinfo === null){
            ElMessage.warning("您还未登录,请进行登陆后重试");
            return {name:'login'}
        }
    }
    // 验证用户是否输入了正确的地址
    // 如果当前路由没有该地址，则跳转至404
    for (let route of routers) {
        if (route.name === to.name){
            return true;
        }
    }
    ElMessage.warning("页面找不到，返回主页");
    return {name: store.userinfo === null ? 'login' : 'home'};
})

export default router