<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item,index) in levelList" :key="item.path" v-if="isVisible(item, index)">
        <span v-if="item.redirect==='noRedirect' || index===levelList.length-1 || index === 0" class="no-redirect">{{ item.meta.title }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>

export default {
  data() {
    return {
      levelList: [],
    }
  },
  watch: {
    $route(route) {
      // if you go to the redirect page, do not update the breadcrumbs
      if (route.path.startsWith('/redirect/')) {
        return
      }
      this.getBreadcrumb()
    }
  },
  created() {
    this.getBreadcrumb()
  },
  methods: {
    // 获取面包屑列表
    getBreadcrumb() {
      let node = this.findNode(this.$router.options.routes, this.$route.name);
      if (node) {
        let list = [];
        this.generateLevelList(node, list)
        this.levelList = list;
      }
    },

    // 从路由列表中找到当前路由对应的node
    findNode(routes, name) {
      for (let i = 0; i < routes.length; i++) {
        if (routes[i].name === name) {
          return routes[i];
        } else if (routes[i].children) {
          let node = this.findNode(routes[i].children, name);
          if (node) {
            return node;
          }
        }
      }
      return undefined;
    },

    // 根据节点生成面包屑列表
    generateLevelList(node, list) {
      if (node && node.meta && node.meta.title && (node.meta.breadcrumb !== false)) {
        list.unshift(node)
      }
      if (node.parent) {
        this.generateLevelList(node.parent, list);
      }
    },

    isHome(route) {
      const name = route && route.name;
      if (!name) {
        return false
      }
      return name.trim().toLocaleLowerCase() === 'Home'.toLocaleLowerCase()
    },

    // 此面包屑是否可见
    isVisible(item, index) {
      return !(index === 0 && item.children && item.children.filter(item => !item.hidden) && item.children.filter(item => !item.hidden).length === 1);
    },

    // 面包屑点击处理
    handleLink(item) {
      const {redirect, path} = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(path);
    }
  }
}
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
