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;

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

    /**
     * 动态添加路由
     * @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.children && item.children.length) {
                    this.addRoutes(item.children, item.resourceCode);
                }
            }
        })
    }

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