import util from '@/libs/util.js'
import { frameInRoutes } from '@/router/routes'

export default {
  methods: {
    handleMenuSelect (index, indexPath) {
      if (/^d2-menu-empty-\d+$/.test(index) || index === undefined) {
        this.$message.warning(this.$t('page.layout.menu.temp_menu'))
      } else if (/^https:\/\/|http:\/\//.test(index)) {
        util.open(index)
      } else {
        this.getRouterAuthPath(index, indexPath)
      }
    },
    /**
     * 点击菜单时进行权限过滤，查找第一个有权限的子路由
     * @param {String} index 选中菜单项的 index (path)
     * @param {Array} indexPath 选中菜单项的 index path
     */
    getRouterAuthPath (index, indexPath) {
      // 首页或子级路由直接访问
      if (index === '/index' || !indexPath || indexPath.length > 1) {
        this.$router.push({ path: index })
        return
      }

      // 查找一级路由下是否存在子路由
      let router = null
      for (const value of frameInRoutes) {
        if (value.path === index) {
          router = value.children
          break
        }
      }

      // 不存在子路由则直接进入
      if (!router) {
        this.$router.push({ path: index })
        return
      }

      // 存在子路由时，跳转第一个有权限的子页面
      for (const value of router) {
        const newPath = index + '/' + value.path
        if (this.$permission(newPath)) {
          this.$router.push({ path: newPath })
          break
        }
      }
    }
  }
}
