<template>
  <el-breadcrumb
    class="c-breadcrumb"
    separator="/"
  >
    <transition-group name="breadcrumb">
      <el-breadcrumb-item
        v-for="(item, index) in levelList"
        :key="item.path"
      >
        <span
          v-if="index === levelList.length - 1"
          class="last"
        >
          {{ item.meta.title }}
        </span>
        <span
          v-else-if="index === 0"
          class="placeholder"
        >
          {{ item.meta.title }}
        </span>
        <a
          v-else
          @click.prevent="onLink(item)"
        >
          {{ item.meta.title }}
        </a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import { compile } from 'path-to-regexp'

export default {
  name: 'Breadcrumb',
  computed: {
    levelList () {
      return this.$route.matched.filter(item => item.meta?.title)
    }
  },
  methods: {
    onLink (item) {
      const { redirect, name, path } = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      if (name) {
        this.$router.push({
          name,
          params: { ...this.$route.params }
        })
        return
      }
      this.$router.push(compile(path)(this.$route.params))
    }
  }
}
</script>

<style lang="scss" scoped>
.breadcrumb-enter-active,
.breadcrumb-leave-active {
  transition: all 0.5s;
}

.breadcrumb-enter,
.breadcrumb-leave-active {
  opacity: 0;
  transform: translateX(20px);
}

.breadcrumb-move {
  transition: all 0.5s;
}

.breadcrumb-leave-active {
  position: absolute;
}

.c-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  user-select: none;

  .last {
    color: #97a8be;
    cursor: auto;
  }

  .placeholder {
    font-weight: 700;
  }
}
</style>
