import { isNull } from './index'
import { privateRoutes } from '@/router/private-routes'

/**
 * 所有子集路由
 * @param {*}
 * @returns
 */

export const getChildrenRoutes = (routes) => {
  const result = []
  routes.forEach((item) => {
    if (item.children && item.children.length > 0) {
      result.push(...item.children)
    }
  })
  return result
}

/**
 * 处理脱离层级的路由
 * @param {*}
 * @returns
 */
export const filterRoutes = (routes) => {
  // 所有子集路由
  const childrenRoutes = getChildrenRoutes(routes)

  // 根据子集路由查重
  return routes.filter((route) => {
    //   根据route 在  childrenRoutes 中进行查重 把所有路由表剔除
    return !childrenRoutes.find((childrenRoute) => {
      return childrenRoute.path === route.path
    })
  })
}

/**
 * 根据routes 数据 返回对应的 menu 规则的数据
 * @param {*}
 * @returns 返回对应的 menu 规则的数据
 */
export const generteMenus = (routes, basePath = '') => {
  const result = []
  // 不满足 meta && meta.title 的数据去除
  routes.forEach((item) => {
    // item 不存在children && 不存在meta  直接 return
    if (isNull(item.children) && isNull(item.meta)) return

    // 判断是否是子路由  子路由直接 return 下面处理
    if (item.path.split('/').length > 2) return

    // 添加第一级路由
    let route = {
      ...item,
      children: []
    }
    result.push(route)
  })

  // 给子路由匹配上 一级路由
  result.forEach((key) => {
    routes.forEach((item) => {
      if (key.path === item.path) {
        return
      } else if (key.path === `/${item.path.split('/')[1]}`) {
        key.children.push(item)
      }
    })
  })
  return result
}

export const changeSortMenus = (tree) => {
  if (!tree || !Array.isArray(tree)) return []
  function customSort(n1, n2) {
    const { sort: sort1 = Number.MAX_SAFE_INTEGER } = n1.sort || {}
    const { sort: sort2 = Number.MAX_SAFE_INTEGER } = n2.sort || {}
    return sort1 - sort2
  }

  tree.sort(customSort)

  tree.forEach((n) => {
    if (n.children && Array.isArray(n.children) && n.children.length > 0) {
      n.children = changeSortMenus(n.children)
    }
  })

  return tree
}

export const getMenusData = () => {
  const result = []
  let uniqueArr = {}
  privateRoutes.forEach((item) => {
    if (!uniqueArr[item.meta.title]) {
      uniqueArr[item.meta.title] = true
      let obj = {
        label: item.meta.title,
        id: item.name,
        path: item.path,
        sort: item.sort,
        children: []
      }
      result.push(obj)
    }
  })
  privateRoutes.forEach((n) => {
    result.forEach((i) => {
      if (i.path == n.path) {
        let obj = { parentSymbol: i.id, label: n.children[0].meta.title, id: n.name, sort: n.children[0].sort }
        i.children.push(obj)
      }
    })
  })
  return result
}

export const flatMenus = (router) => {
  const arr = []
  router.sort((a, b) => a.sort - b.sort)
  const f = (router) => {
    router.sort((a, b) => a.sort - b.sort)
    router.forEach((r) => {
      if (r.children && r.children.length > 0) {
        f(r.children)
      } else {
        arr.push(r.id)
      }
    })
  }
  f(router)
  return arr
}
