import { keyViewMap, attach } from '@/constant/view'
import { ref, watch } from 'vue'
import router from '@/router'
import user from './user'
import navs, {MUST_JOIN_NAVS} from './navs'

const auth = ref({})


const setCurrentAuth = () => {
  let viewName = router.currentRoute.value.name
  
  viewName = attach[viewName] ? attach[viewName] : viewName

  let key = Object.keys(keyViewMap).find(key => keyViewMap[key] === viewName) || viewName
  let authParent = user.value.permission.find(item => item.resourceKey === key)

  if (!navs.value.some(item => item.name !== viewName) && !MUST_JOIN_NAVS.includes(viewName)) {
    router.replace({name: 'login'})
  }

  if (authParent) {
    let viewAuths = authParent.children.map(item => item.resourceKey.substr(key.length + 1))
    let newValue = {}
    viewAuths.forEach(key => newValue[key] = true)
    auth.value = newValue
  } else {
    auth.value = {}
  }
}

setTimeout(() => {
  watch(
    router.currentRoute, 
    setCurrentAuth, 
    { immediate: true }
  )
})

watch(() => user.value.permission, setCurrentAuth)

export default auth