import { RouteRecordRaw } from 'vue-router'
import { AuthType } from '@/constants/menu'
import { useRouterStore } from '@/stores'
import router from '../router'
import Page from '../components/layouts/page/index.vue'

export default new (class {
    /** 防止动态路由无限加载 */
    isReady = false;

    /** 已注册的路由 */
    private registeredRouteNames: string[] = [];

    /**
     * 添加404页面
     */
    private addNotFound() {
        router.addRoute({
            path: '/:pathMatch(.*)*',
            name: 'NotFound',
            component: Page,
            meta: {
                title: '系统错误'
            },
            children: [
                {
                    path: '',
                    name: 'NotFoundIndex',
                    component: () => import('../views/error/404.vue'),
                    meta: {
                        title: '404'
                    }
                }
            ]
        })
        this.registeredRouteNames.push('NotFound')
    }

    /**
     * 动态添加路由
     * @param routes 
     * @param parentName 
     */
    private addRoutes(routes: Model.MenusRsp[], parentName = '') {
        routes.forEach((item) => {
            if (item.authType === AuthType.Menu && item.component) {
                let component;
                switch (item.component) {
                    case 'Page': {
                        component = Page;
                        break;
                    }
                    default: {
                        const componentString = item.component.replace(/^\/+/, ''); // 过滤字符串前面所有 '/' 字符
                        const componentPath = componentString.replace(/\.\w+$/, ''); // 过滤后缀名，为了让 import 加入 .vue ，不然会有警告提示...
                        component = () => import('../' + componentPath + '.vue');
                    }
                }

                const route: RouteRecordRaw = {
                    path: (item.url.startsWith('/') ? '' : '/') + item.url,
                    name: item.resourceCode,
                    component,
                    meta: {
                        title: item.title,
                        icon: item.icon,
                        remark: item.remark,
                        keepAlive: true, // 默认缓存页面
                    },
                }

                parentName ? router.addRoute(parentName, route) : router.addRoute(route);

                if (item.parentCode === '') {
                    this.registeredRouteNames.push(item.resourceCode); // 添加一级路由到注册列表
                }

                if (item.children && item.children.length) {
                    this.addRoutes(item.children, item.resourceCode);
                }
            }
        })
    }

    /**
     * 移除所有已注册的路由
     */
    unregisterRoutes() {
        this.registeredRouteNames.forEach((name) => {
            router.removeRoute(name);
        })
        this.registeredRouteNames = [];
        this.isReady = false;
    }

    /**
     * 注册路由
     * @returns 
     */
    registerRoutes() {
        const routerStore = useRouterStore();
        this.addNotFound();
        this.addRoutes(routerStore.userRoutes);
        this.isReady = true;
    }
})