import { config } from '@/router'
import { attach } from '@/constant/view'
import user from './user'
import { watch, ref } from 'vue'
// 所有权限都有的router
export const MUST_JOIN_NAVS = ['viewLayout', 'login', 'register', 'forget', 'scene', 'sceneVisitor']
// router对应的icon
const ICON_MAP = { 
  estate: 'iconfire_scenes', 
  home: 'iconfire_home', 
  vrmodel: 'iconfire_scenes', 
  camera: 'iconfire_camera', 
  dispatch: 'iconfire_management', 
  organization: 'iconfire_organization', 
  teaching: 'iconfire_study',
  user: 'iconfire_user',
  role:'iconfire_role_management',
}

const getNames = (config) => {
  let names = []
  config.forEach(item => {
    names.push(item.name)
    item.children && names.push(...getNames(item.children))
  })
  return names
}

const _getNavs = (items, notJoinNavs) => {
  let ret = []
  for (let i = 0; i < items.length; i++) {
    if (~notJoinNavs.indexOf(items[i].name)) {
      continue
    } else {
      if (items[i].children && items[i].name !== 'organization') {
        ret.push(..._getNavs(items[i].children, notJoinNavs))
      } else if (ICON_MAP[items[i].name]){
        let item = {
          ...items[i], 
          icon: ICON_MAP[items[i].name]
        }
        ret.push(item)
        // delete item.component
      }
    }
  }
  console.log('_getNavs',ret);
  return ret
}

const getNavs = () => {
  
  let names = getNames(config)
  let showNames = user.value.permission.map(item => item.viewName)
  console.log('showNames',showNames,user.value.permission);
  let notJoinNavs = names.filter(name => 
    ~Object.keys(attach).indexOf(name) || (
      !~showNames.indexOf(name) && 
      !~MUST_JOIN_NAVS.indexOf(name)
    )
  )
  return _getNavs(config, notJoinNavs)
}

const navs = ref([])

watch(
  () => user.value.permission, 
  () => navs.value = getNavs()
)
setTimeout(() => navs.value = getNavs())

export default navs