import { createRouter, createWebHashHistory } from 'vue-router';
import { useAuthStore } from '@/store';
import { doLogin } from '@/api'


import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style

const env = import.meta.env;

let children = [];
let files = import.meta.glob('@/pages/page/**/*.vue');
for (let name in files) {
    if (name.includes("/components/") || name.includes('/modules/')) {
        continue;
    }
    let path = name.substring(name.indexOf("/page/") + 5);
    path = path.substring(0, path.length - 4);
    children.push({
        path,
        component: files[name],
        meta: { auth: true }
    });
}

let tests = [];
files = import.meta.glob('@/pages/test/**/*.vue');
for (let name in files) {
    if (name.includes("/components/") || name.includes('/modules/')) {
        continue;
    }
    let path = name.substring(name.indexOf("/test/") + 6);
    path = path.substring(0, path.length - 4);
    tests.push({
        path,
        component: files[name],
        meta: { auth: false }
    });
}

console.debug('test',tests);


const routes = [
    {
        path: "/",
        redirect: "/index"
    },
    {
        path: "/layout",
        component: () => import("../pages/layout.vue"),
        children: [
            {
                path: "/login",
                component: () => import("../pages/login.vue"),
                meta: { title: "用户登录", auth: false }
            },
            {
                path: "/index",
                component: () => import("../pages/index.vue"),
                meta: { title: "首页", auth: true }
            },
            ...children
        ]
    },
    {
        path: '/test',
        component: () => import('@/pages/test'),
        hidden: true,
        redirect: '/test/index',
        children: tests
    },
    {
        path: "/:id(.*)*",
        component: () => import("../pages/404.vue"),
        meta: { title: "404页面" },
    }
]

console.debug(routes);


//创建路由对象
const router = createRouter({
    history: createWebHashHistory(import.meta.env.VITE_APP_CONTEXT_PATH),
    routes
})



router.afterEach(() => {
    NProgress.done();
});

/**
 * 自动登录
 * @returns 
 */
const autoLogin = async () => {
    let store = useAuthStore();
    if (store.isLogin) {
        return;
    }
    if (!store.user.username) {
        store.user.username = import.meta.env.VITE_APP_USERNAME;
        store.user.password = 'YDEDgImeKAtXWOsSdMqNP/v97cDB2/lZgU0mh4T6OIPMT+D2GWVy5bw9eX8ipTUBiGaNXF/5MAxSfJSZH4KMpZO+W6E4NaOY3SlngWyR5HeIaN9rnGQHXFyez9OY1XD16ostoB2/tH/sAQq8GRVEwYSkbzGYfVIX5caBkoctN6k=';
    }
    let r = await doLogin(store.user.username, store.user.password);
    console.debug('r',r);
    if (r.code == 200) {
        store.setToken(r.data);
        return;
    }else {
        throw new Error(r.msg);
    }
}


router.beforeEach(async (to, from, next) => {
    NProgress.start();

    let title = [];

    for (let item of to.matched) {
        if (!item.meta.title) {
            break;
        }
        title.unshift(item.meta.title);
    }

    if (title.length > 0) {
        document.title = title.join(" - ") + " - " + env.VITE_APP_NAME;
    } else {
        document.title = env.VITE_APP_NAME;
    }

    let checkLogin = to.matched.some(record => record.meta.auth);//是否需要验证登录
    //这里使用matched循环查找不直接使用to.meta的原因：多层嵌套路由情况下,逐级检查
    // console.debug(to.matched);
    // console.debug(checkLogin);
    //如果需要检查登录或者角色
    if (checkLogin || to.meta.roles) {
        const store = useAuthStore();
        if (!store.isLogin) {//如果没有登录,则跳转到登录
            try {
                await autoLogin();
                next();
            } catch (e) {
                next({ path: "/login", query: { to: to.fullPath } });
            }
            return;
        }
        //如果要验证角色,但当前登录用户不具备该角色则跳转到404
        if (to.meta.roles && !to.meta.roles.includes(store.user.roleId)) {
            next({ path: "/404" });
            return;
        }
        next();
    } else {
        next();
    }
})
//导出路由对象，以供其它组件使用
export default router





