<template>
  <el-menu
    :background-color="config.backgroundColor"
    :text-color="config.textColor"
    :active-text-color="config.activeTextColor"
  >
    <template v-for="menu in menuList" :key="menu.index">
      <SubMenu v-if="menu.children" :menu="menu" />
      <MenuItem v-else :menu="menu" />
    </template>
  </el-menu>
</template>

<script>
import { computed } from 'vue'
import { useModel } from '@/store'
import { menus } from '@/router/routes'
import SubMenu from './SubMenu.vue'
import MenuItem from './MenuItem.vue'

const getAuthMenu = (menuList, authList) => menuList.reduce((acc, menu) => {
  const exists = authList.filter(x => x.code === menu.route.name)[0]
  if (!exists) {
    return acc
  }

  if (menu.children) {
    menu.children = getAuthMenu(menu.children, authList)
  }

  return acc.concat({
    ...menu,
    index: Math.random().toString(36).substring(2)
  })
}, [])

export default {
  components: {
    SubMenu,
    MenuItem,
  },

  props: {
    config: Object,
  },

  setup(props) {
    const { user } = useModel('user')
    const menuList = computed(() => getAuthMenu(menus, user.menuList))
    
    return {
      menuList,
    }
  }
}
</script>
