import router from '@/router';
import { OperationTabMenu } from '@/services/go/commonService/interface';
import { localStorageUtil } from '@/utils/storage';
import { RouteRecordRaw } from 'vue-router';

/**
 * 添加404页面
 */
const addNotFound = () => {
    router.addRoute({
        path: '/:pathMatch(.*)*',
        name: '404',
        component: () => import('@/views/error-page/404.vue'),
    })
}

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

            const route: RouteRecordRaw = {
                path: item.path,
                name: item.code,
                component,
                meta: {
                    title: item.title,
                    url: item.url,
                    auth: item.auth ?? [],
                    remark: item.remark,
                },
            }

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

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

/**
 * 注册路由
 */
export const registerRoutes = (): Promise<boolean> => {
    const routerMap: OperationTabMenu[] = localStorageUtil.getItem('menus');
    return new Promise((resolve, reject) => {
        addNotFound();
        if (routerMap.length) {
            addRoutes(routerMap);
            resolve(true);
        } else {
            reject(false);
        }
    })
}