import {createRouter, createWebHistory} from 'vue-router'
import LayoutCom from '@/layout/index.vue'
import Demo, {mockRouter} from './modules/demo'
import staticRouter from './modules/static'
import store from '@/store/index'
import TempCom from '@/views/global/temp.vue'
import * as api from '@/api/index'
import {getRoutes} from '@/api/modules/global/global'
import RouterViewCom from "@/layout/router-view.vue";
import {toLogin} from "@/utils/permissions";


const demo = (import.meta as any).env.DEV ? Demo : new Map()
export const RoutersMap = new Map([
    ...demo,
])

const routes = [
    ...staticRouter,
    {
        path: '/',
        name: store.state.menu.menuRootName, // 菜单根路由name标识
        component: LayoutCom,
        children: [
        ]
    },
    { path: '/:pathMatch(.*)*', name: 'NotFound', component: TempCom }
]

const router = createRouter({
    history: createWebHistory(),
    routes,
});

router.beforeEach((to, from , next) => {
    if (to.path === "/login") {
        if ((import.meta as any).env.DEV) {
            next()
        } else {
            toLogin()
        }
    } else {
        if (sessionStorage.getItem("ax_token")) {
            getInit(to, next)
        } else if (to.query.axToken) {
            sessionStorage.setItem("ax_token", <string>to.query.axToken);
            setTimeout(() => {//虽然不知道为什么要加宏任务，但是我不敢改
                delete to.query.axToken
                let url = `${window.location.origin + window.location.pathname}?`
                for (let queryKey in to.query) {
                    url += `${queryKey}=${to.query[queryKey]}&`
                }
                window.location.replace(url.slice(0, url.length - 1));
                getInit(to, next)
            }, 0);
        } else {
            toLogin()
        }
    }
})

const getInit = (to: any, next: any) => {
    document.title = to?.meta?.title || (import.meta as any).env.VITE_PROJECT_TITLE
    if (to.path === '/') {
        const firstRoute = store.state.menu.allRouters[0]
        next({
            path: firstRoute.redirect || firstRoute.path
        })
    } else {
        const m = to.matched[1]?.children?.map((v: any) => {
            v.expend = v.children?.some((s: any) => s.path === to.path)
            return v
        })
        store.dispatch('menu/LOAD_SUB_MENU_ROUTER', m || [])
        if (store.state.menu.subMenuRouter.length > 0) {
            store.dispatch('menu/LOAD_NAVIGATION', {
                path: to.path,
                name: to.name,
                title: to.meta.title
            })
        }
        next()
    }
}

export const initMainRouter = async () => {
    if (sessionStorage.getItem("ax_token") && location.pathname !== '/login') {
        await Promise.all([
            getRoutes(),
            store.dispatch('app/LOAD_USER_INFO')
        ]).then(async ([r, u]) => {
            await store.dispatch('app/LOAD_POWER_DEPT', u.deptId).then(() => {
                setRouters(r)
            })
        })
    }

}
const setRouters = (res: any) => {
    const deep = (arr: Array<any>, parentArr: Array<any>) => {
        return arr.map((v, i) => {
            const _pA = [...parentArr, v]
            const obj: any = {
                meta: {
                    res: v,
                    title: v.meta.title,
                    icon: v.meta.icon,
                }
            }
            obj.name = v.menuCode
            obj.path = '/' + _pA.map(v => v.path.replaceAll('/', '')).join('/')
            if (v.children?.length > 0) {
                obj.children = deep(v.children, _pA)
                obj.component = RouterViewCom
                // obj.redirect = v.redirect
            } else {
                obj.component = RoutersMap.get(obj.name)?.component || TempCom
            }
            return obj
        })
    }
    // @ts-ignore
    const deepRedirect = (item: any) => {
        if (item.children?.length > 0) {
            return deepRedirect(item.children[0])
        } else {
            return item.path
        }
    }
    const arr = res.data.filter(v => {
        return !['6990b747-f628-4698-bb69-d6147c27e7d6'].includes(v.menuCode)
    })
    if ((import.meta as any).env.DEV) {
        arr.unshift(mockRouter)
    }
    const menuRouters = deep(arr, [])
    //  初始化一级菜单默认重定向地址
    menuRouters.forEach(v => {
        if (v.children?.length > 0 && !v.redirect) {
            v.redirect = deepRedirect(v.children[0])
        }
    })
    //  动态添加路由
    menuRouters.forEach(v => {
        router.addRoute(store.state.menu.menuRootName, v)
    })
    store.dispatch('menu/LOAD_ROUTERS', menuRouters)
}
export default router;
