import {createRouter, createWebHistory} from 'vue-router'
import LayoutCom from '@/layout/index.vue'
import GisLayoutCom from '@/views/gis/layout/index.vue'
import staticRouter from './modules/static'
import store from '@/store/index'
import TempCom from '@/views/global/temp.vue'
import RouterViewCom from "@/layout/router-view.vue";
import {gisRouter} from './modules/gis'
import {ElMessage} from "element-plus";
import {toLogin} from "@/utils/permissions";

export const RoutersMap: any = new Map([
])

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

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

router.beforeEach((to, from , next) => {
    if (to.path === "/login") {
        if (sessionStorage.getItem("sg_token")) {
            location.replace('/')
        } else {
            next()
        }
    } else {
        if (sessionStorage.getItem("sg_token")) {
            getInit(to, next)
        } else if (to.query.axToken) {
            sessionStorage.setItem("sg_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]
        if (firstRoute) {
            next({
                path: firstRoute.redirect || firstRoute.path
            })
        }
    } else if (to.path === '/gis') {
        next({path: '/gis/' + gisRouter[0].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("sg_token") && location.pathname !== '/login') {
        setRouters()
        // await Promise.all([
        //     store.dispatch('app/LOAD_USER_INFO'),
        // ]).then(async ([u]) => {
        //     if (u.roles.some(v => ['ZBY', 'ZBGL'].includes(v.permissionValue))) {
        //         setRouters()
        //         store.dispatch('app/LOAD_PUBLIC_CONFIG', {key: 'sign.begin.time'})
        //         store.dispatch('app/LOAD_PUBLIC_CONFIG', {key: 'sign.remind.time'})
        //         store.dispatch('app/LOAD_PUBLIC_CONFIG', {key: 'sign.end.time'})
        //         store.dispatch('app/LOAD_PUBLIC_CONFIG', {key: 'log.submit.time'})
        //         store.dispatch('app/LOAD_PUBLIC_CONFIG', {key: 'log.remind.time'})
        //         store.dispatch('app/LOAD_PUBLIC_CONFIG', {key: 'week.submit.date'})
        //         store.dispatch('app/LOAD_PUBLIC_CONFIG', {key: 'week.submit.time'})
        //         store.dispatch('app/LOAD_PUBLIC_CONFIG', {key: 'week.remind.time'})
        //         store.dispatch('app/LOAD_SIGN_INFO')
        //         store.dispatch('app/LOAD_DAILY_INFO')
        //         store.dispatch('app/LOAD_WEEKLY_INFO')
        //     } else {
        //         ElMessage({
        //             duration: 0,
        //             type: 'warning',
        //             message: '该账号无系统角色！点击关闭按钮跳转到登录页。',
        //             showClose: true,
        //             onClose: () => toLogin()
        //         })
        //     }
        // })
    }

}
const setRouters = () => {
    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 = []
    // const arr = [stagingRouter, systemRouter]
    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;
