import usePermission from '@/hooks/permission'
import appClientMenus from '@/router/app-menus'
import { useAppStore } from '@/store'
import { cloneDeep } from 'lodash'
import { computed } from 'vue'
import { RouteRecordNormalized, RouteRecordRaw } from 'vue-router'

export default function useMenuTree() {
  const permission = usePermission()
  const appStore = useAppStore()
  const appRoute = computed(() => {
    if (appStore.menuFromServer) {
      return appStore.appAsyncMenus
    }
    return appClientMenus
  })
  const menuTree = computed(() => {
    const copyRouter = cloneDeep(appRoute.value || []) as RouteRecordNormalized[]
    copyRouter.sort((a: RouteRecordNormalized, b: RouteRecordNormalized) => {
      return (a.meta.order || 0) - (b.meta.order || 0)
    })
    function travel(_routes: RouteRecordRaw[], layer: number): RouteRecordRaw[] {
      if (!_routes?.length) return []

      const collector: any = _routes.map((element) => {
        // no access
        if (!permission.accessRouter(element)) {
          return null
        }

        // leaf node
        if (element.meta?.hideChildrenInMenu || !element.children) {
          element.children = []
          return element
        }

        // route filter hideInMenu true
        element.children = element.children.filter((x) => x.meta?.hideInMenu !== true)

        // Associated child node
        const subItem = travel(element.children, layer + 1)

        if (subItem.length) {
          element.children = subItem
          return element
        }

        // 子级全部被权限/隐藏规则过滤时，不再把父级当成可点击叶子（避免 push 父级 name 无对应页面）
        return null
      })
      return collector.filter(Boolean)
    }
    return travel(copyRouter, 0)
  })

  return {
    menuTree,
  }
}
