import permissionApi from '../api/permission';

// 动态路由
export default {
    async init(router, pages, layout) {
        if (pages == null) {
            pages = {};
        }

        let res = await permissionApi.queryRouter();
        let allPer = res;
        let topPer = allPer.filter(p => p.parentID == null);
        let routes = [
            {
                path: '*',
                name: '404',
                meta: {
                    title: '404'
                },
                children: [],
                component: () => pages['@/pages/system/error/404']
            },
            {
                path: '/',
                redirect: {
                    name: 'login'
                },
                component: layout,
                children: []
            }
        ];
        for (let i = 0; i < topPer.length; i++) {
            topPer[i] = permossionDeep(topPer[i], allPer);
        }
        buildPermossion(pages, topPer, routes, layout, null);
        routes.forEach(route => {
            router.addRoute(route);
        });
        return routes;
    }
};

function buildPermossion(pages, perArry, routes, layout, parent) {
    perArry.forEach(item => {
        let node;
        if (item.parentID == null) {
            node = {
                id: item.id,
                pId: item.parentID,
                path: '/' + item.url.split('/').pop(),
                name: item.url.replace('app.', '').replace(/\./g, '-'),
                meta: {
                    auth: false
                },
                component: layout,
                children: []
            };
            routes.push(node);
        } else {
            // 获取参数
            let url = item.url.split('?')[0];
            let data = {};
            if (item.url.split('?').length > 1) {
                item.url
                    .split('?')[1]
                    .split('&')
                    .forEach(item => {
                        if (item.split('=').length > 1 && item.split('=')[0].length > 0) {
                            data[item.split('=')[0]] = item.split('=')[1];
                        }
                    });
            }
            node = {
                id: item.id,
                pId: item.parentID,
                path: url.split('/').pop(),
                name: url.replace(/\//g, '-'),
                meta: {
                    auth: false,
                    title: item.name,
                    description: item.subName,
                    data,
                    cache: item.isMenu
                },
                children: [],
                component: resolve => {
                    require([], require => {
                        resolve(pages[item.templateUrl]);
                    });
                }
            };
            if (parent == null) {
                parent = routes.find(p => p.id == item.parentID);
            }
            if (parent != undefined) {
                if (parent.pId != null) {
                    let backup = parent;
                    parent = routes.find(p => p.id == parent.pId);
                    node.path = url
                        .split('/')
                        .splice(1)
                        .join('/');
                    parent.children.push(node);
                    parent = backup;
                } else {
                    parent.children.push(node);
                }
            }
        }

        if (item.sonPer != null) {
            buildPermossion(pages, item.sonPer, routes, layout, node);
        }
    });
    return routes;
}

function permossionDeep(per, perArry) {
    let sonPerArry = perArry.filter(p => p.parentID == per.id);
    if (sonPerArry.length > 0) {
        per['sonPer'] = sonPerArry;
        for (let i = 0; i < sonPerArry.length; i++) {
            sonPerArry[i] = permossionDeep(sonPerArry[i], perArry);
        }
    }
    return per;
}
