import type { RouteRecordRaw } from 'vue-router'
import { asyncRouter } from '@/router'
import config from '@/config/defaultSetting'
import { generatorDynamicRouter } from '@/utils/dynamicRouter'

// eslint-disable-next-line
function hasPermission(route: RouteRecordRaw, permission: any[]) {
  if (route.meta && route.meta.permission) {
    let flag = false
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.includes(permission[i])
      if (flag) {
        return true
      }
    }
    return false
  }
  return true
}

function hasRole(route: RouteRecordRaw, role: any[]) {
  if (route.meta && route.meta.role) {
    let flag = false
    for (let i = 0, len = role.length; i < len; i++) {
      flag = route.meta.role.includes(role[i])
      if (flag) {
        return true
      }
    }
    return false
  }
  return true
}

// 根据角色过滤路由
function filterAsyncRouter(routerMap: RouteRecordRaw[], role: any[]) {
  const accessedRouters = routerMap.filter(route => {
    if (hasRole(route, role)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, role)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

// 过滤掉hidden为true的路由
function filterMenuRouter(router: RouteRecordRaw[]) {
  const routerMap: RouteRecordRaw[] = JSON.parse(JSON.stringify(router))
  const accessedRouters = routerMap.filter(route => {
    if (!route.hidden) {
      if (route.children && route.children.length) {
        route.children = filterMenuRouter(route.children)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const keepAliveRouter: any = []
function filterKeepAliveRouter(router: RouteRecordRaw[]) {
  router.forEach(item => {
    if (item.meta?.keepAlive || item.children?.some(child => child.meta?.keepAlive)) {
      keepAliveRouter.push(item.meta?.viewName)
    }
    if (item.children?.length) {
      filterKeepAliveRouter(item.children)
    }
  })
  return keepAliveRouter
}

export const useRouterStore = defineStore({
  id: 'router',
  state: () => ({
    menuRouter: <any>[],
    asyncRouter: <any>[],
    dynamicRouter: <any>[],
    keepAliveRouter: <any>[]
  }),
  actions: {
    generatorRouter(role?: any[]): Promise<RouteRecordRaw[]> {
      return new Promise(resolve => {
        if (config.isDynamicRouter) {
          this.asyncRouter = generatorDynamicRouter(this.dynamicRouter)
        } else {
          this.asyncRouter = role ? filterAsyncRouter(asyncRouter, role) : asyncRouter
        }

        this.menuRouter = filterMenuRouter(this.asyncRouter)
        this.keepAliveRouter = filterKeepAliveRouter(this.menuRouter)
        resolve(this.asyncRouter)
      })
    },
    setDynamicRouter(router: any[]) {
      this.dynamicRouter = router
    }
  }
})
