<template>
  <div class="player">
    <div
      v-for="item in records"
      :key="item.name"
      :class="{active: item.name === $route.name}"
      @click="item.name !== $route.name && gotoRecord(item)"
      >
      <span>{{item.meta.title}}</span>
      <i class="el-icon-close" @click.stop="delRecord(item)"></i>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const records = ref([])
    return { records }
  },
  watch: {
    '$route': {
      immediate: true,
      handler() {
        if (this.$route.name !== 'viewLayout') {
          let index = this.records.findIndex(record => record.name === this.$route.name)
          if (~index) {
            this.records.splice(index, 1, this.$route)
          } else {
            this.records.push(this.$route)
          }
        }
      }
    }
  },
  methods: {
    delRecord(record) {
      let index = this.records.indexOf(record)
      if (!~index) return;
      this.records.splice(index, 1);

      if (this.records.length <= index) {
        index = index - 1
      }

      if (~index) {
        this.$router.replace({path: this.records[index].path})
      } else {
        this.$router.push({name: 'viewLayout'})
      }
    },
    gotoRecord(record) {
      this.$router.push({path: record.path})
    }
  }
}
</script>


<style lang="scss" scoped>
@import "./style.scss";
</style>