import Layout from '@/layout/index.vue'

//故障诊断
import faultDiagnosis from './modules/faultDiagnosis'
//寿命预测
import lifePrediction from './modules/lifePrediction'
//维修决策
import maintenanceDecision from './modules/maintenanceDecision'
//故障统计

import faultStatistics from './modules/faultStatistics'
//携行规划
import carrierStandard from './modules/carrierStandard'
// 系统
import system from './modules/system'

export const privateRoutes = [
  {
    path: '/home',
    name: 'Home',
    meta: {
      title: '综合看板',
      icon: 'el-icon-s-home'
    }
  },
  ...faultDiagnosis,
  ...lifePrediction,
  ...maintenanceDecision,
  ...faultStatistics,
  ...carrierStandard,
  ...system
]

export const flattenedRoutes = flattenedData(privateRoutes)

export function buildTreeData(routes) {
  const flatRoutes = []
  const nodeMap = []
  const res = []
  function flattened(routes, res = []) {
    routes.forEach((r) => {
      const { name, meta, path, children } = r
      flatRoutes.push({ name, meta, path })
      if (children && children.length > 0) {
        flattened(r.children, res)
      }
    })
  }
  flattened(routes)

  flatRoutes.forEach((r) => {
    const node = { ...r, children: [] }
    nodeMap[r.name] = node
    const parentName = r.meta?.parent
    if (parentName) {
      const parentNode = nodeMap[parentName]
      if (parentNode) {
        parentNode.children.push(node)
      }
    } else {
      res.push(node)
    }
  })
  return res
}

// 过滤出权限可用routes
export function filterPermissionsRoutes(routes, p) {
  return routes.filter((r) => {
    if (p.includes(r.name)) {
      if (r.children) {
        r.children = filterPermissionsRoutes(r.children, p)
      }
      return true
    }
    if (r.children) {
      const filterC = filterPermissionsRoutes(r.children, p)
      if (filterC.length > 0) {
        r.children = filterC
        return true
      }
    }
    return false
  })
}

// tree to 扁平化
export function flattenedData(routes, res = []) {
  routes.forEach((r) => {
    res.push({ ...r })
    if (r.children?.length) {
      flattenedData(r.children, res)
    }
  })
  return res
}
