import { constantRoutes, asyncRoutes } from '@/router/index'
import store from '@/store'

let routesTree = []
let routes = []

function getRoutes() {
  const roles = store.getters.roles
  routes = [...constantRoutes, ...asyncRoutes].filter(item => item.meta)
  if (!roles.includes('admin')) {
    routes = routes.filter(route => !route.meta.roles || route.meta.roles.includes('normal'))
  }
  return routes
}

function formatRoutesToModule() {
  routes = getRoutes()
  routesTree = []
  routes.forEach(first => {
    const obj = {
      label: first.meta.title,
      value: first.meta.id
    }
    if (first.children) {
      obj.children = []
      first.children.forEach(second => {
        obj.children.push({
          label: second.meta.title,
          value: second.meta.id
        })
      })
    }
    routesTree.push(obj)
  })

  return routesTree
}

export function getToutesTree() {
  return formatRoutesToModule()
}

// 根据id获取栏目
export function getModuleType(ids) {
  ids = ids.split('-')
  const parent = routes.find(item => item.meta.id === parseInt(ids[0]))
  const children = parent && parent.children.find(item => item.meta.id === parseInt(ids[1]))
  if (!parent || !children) {
    return ''
  }
  return `${parent.meta.title}/${children.meta.title}`
}
