import {type RouteRecordRaw} from 'vue-router'
import {ElMessage} from 'element-plus'
import {filterRouters, getMenuChildren, getBtnAuth, getQueryString} from './index'
import {saveCommonRoute} from '@common/src/api';
import {COMMON_APP} from '@common/src/constants';
import {useDebounceFn} from '@vueuse/core'


export interface ILoadType {
    routePath: any
    storeMAppPath: any
    hookProgressPath: any
    hookTitlePath: any
    storeMPermissionPath: any
    hookLoadingPath: any
    constantsPath: any
    storeMUserPath: any
    apiLoginPath: any
}

export const loginLoad = async (sys_code, pathModule: ILoadType) => {
    const router = await pathModule.routePath
    const useAppStoreWithOut = await pathModule.storeMAppPath
    const useTitle = await pathModule.hookProgressPath
    const useNProgress = await pathModule.hookProgressPath
    const usePermissionStoreWithOut = await pathModule.storeMPermissionPath
    const usePageLoading = await pathModule.hookLoadingPath
    const NO_REDIRECT_WHITE_LIST = await pathModule.constantsPath
    const useUserStoreWithOut = await pathModule.storeMUserPath
    const {codeLogin, getAuthBtn, getMenuList} = await pathModule.apiLoginPath

    const {start, done} = useNProgress()

    const {loadStart, loadDone} = usePageLoading()

    const SYS_CODE = sys_code

    // 防抖处理函数
    const debounceFn = useDebounceFn(async (to, flag) => {
        // 埋点计数
        if (COMMON_APP.includes(to.fullPath)) {
            await saveCommonRoute({
                "appCode": flag,
                "routePath": to.fullPath
            })
        }
    }, 100)

    router.beforeEach(async (to, _from, next) => {
        start()
        loadStart()
        const permissionStore = usePermissionStoreWithOut()
        const appStore = useAppStoreWithOut()
        const userStore = useUserStoreWithOut()
        // const queryParams = new URLSearchParams(window.location.search)
        const code = getQueryString('code')

        const flag = getQueryString('flag') || sessionStorage.getItem('flag')

        appStore.setMenuTheme('#373f4e')

        debounceFn(to, flag)

        if (code && flag) {
            if (!userStore.getToken) {
                const state = getQueryString('state')
                const deptId = JSON.parse(state as string)?.deptId
                const {data} = await codeLogin({system: flag, code, deptId})
                userStore.setUserInfo(data)
                userStore.setToken(data.accessToken)
                sessionStorage.setItem('flag', flag || '')

                // 门户页进来页面跳转进入该方法
                await getRouter()

                // queryParams.delete('code')
                // queryParams.delete('flag')
                // queryParams.delete('state')
                const newUrl = `${window.location.pathname}`
                window.history.replaceState({}, '', newUrl)
                next()
            } else {
                if (NO_REDIRECT_WHITE_LIST.indexOf(to.path) !== -1) {
                    next()
                } else {
                    next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
                }
            }
        } else {
            if (userStore.getUserInfo) {
                if (to.path === '/login') {
                    // next({path: '/'})
                    ElMessage.warning('暂不支持直接键入登录页')
                    next(false)
                } else {
                    if (permissionStore.getIsAddRouters) {
                        next()
                        return
                    }

                    // 开发者可根据实际情况进行修改
                    const roleRouters = userStore.getRoleRouters || []

                    // 是否使用动态路由
                    if (appStore.getDynamicRouter) {
                        appStore.serverDynamicRouter
                            ? await permissionStore.generateRoutes(
                                'server',
                                roleRouters as AppCustomRouteRecordRaw[]
                            )
                            : await permissionStore.generateRoutes('frontEnd', roleRouters as string[])
                    } else {
                        await permissionStore.generateRoutes('static')
                    }

                    permissionStore.getAddRouters.forEach((route) => {
                        console.log(route)
                        router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
                    })
                    permissionStore.setIsAddRouters(true)
                    next(to.path === '/' ? permissionStore.addRouters[0].path : to.fullPath)
                }
            } else {
                if (NO_REDIRECT_WHITE_LIST.indexOf(to.path) !== -1) {
                    next()
                } else {
                    // userStore.setRoleRouters(routers)
                    const roleRouters = userStore.getRoleRouters || []
                    await permissionStore.generateRoutes('frontEnd', roleRouters as string[])
                    permissionStore.getAddRouters.forEach((route) => {
                        router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
                    })
                    permissionStore.setIsAddRouters(true)
                    console.log(permissionStore.addRouters)

                    // next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
                    // next(to.path === '/' ? permissionStore.addRouters[0].path : to.fullPath)
next()
                }
            }
        }
    })

// 获取角色信息
    const getRouter = async () => {
        const permissionStore = usePermissionStoreWithOut()
        const appStore = useAppStoreWithOut()
        const userStore = useUserStoreWithOut()
        const res = await getMenuList({})
        const btn = await getAuthBtn({})
        if (res) {
            const routers = filterRouters(getMenuChildren(res.data, SYS_CODE)) || []
            const btnAuth = getBtnAuth(btn.data) || []
            if (!routers.length) {
                ElMessage.error('暂无菜单权限')
                return
            }
            userStore.setRoleRouters(routers)
            userStore.setBtnAuth(btnAuth)
            appStore.getDynamicRouter && appStore.getServerDynamicRouter
                ? await permissionStore.generateRoutes('server', routers).catch(() => {
                })
                : await permissionStore.generateRoutes('frontEnd', routers).catch(() => {
                })

            permissionStore.getAddRouters.forEach((route) => {
                router.addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
            })
            permissionStore.setIsAddRouters(true)

            // 获取从门户页跳转过来携带的state参数中的path 有该path 说明是门户页跳转常用功能
            const state = getQueryString('state')
            const path = JSON.parse(state as string)?.path

            // 重定向到项目的第一个路由
            const redirectPath = await getPath(permissionStore.addRouters, firstPath)

            router.push({
                // path: toRaw(permissionStore.addRouters[0]).path
                // path: path ? path : toRaw(permissionStore.addRouters[0]).path
                path: path ? path : redirectPath
            })
        }
    }

    // 获取第一个显示的菜单

    let firstPath = ''

    const getPath = async (routers: AppRouteRecordRaw[], path: string) => {
        // 过滤掉 非展示的页面
        const arr = routers.filter(i => i.meta.hidden !== true)

        if (!arr.length) {
            ElMessage.error('暂无菜单权限')
            return '/404'
        }
        firstPath = `${path}${arr[0].path.charAt(0) === '/' ? '' : '/'}${arr[0].path}`
        if (arr[0].children) {
            return await getPath(arr[0].children, firstPath)
        }
        return firstPath
    }


    router.afterEach((to) => {
        useTitle(to?.meta?.title as string)
        done() // 结束Progress
        loadDone()
    })
}
