<template lang="">
  <div class="tag-list">
    <el-tag v-for="(tag,index) in tagsList" :key="tag.name" closable :class="{'isActive':tagsActiveIndex===index}"
     @click="tagClick(tag,index)" @close="tagClose(index)">
      {{ tag.name }}
    </el-tag>
  </div>
</template>
<script setup>
import { useRoute, useRouter } from 'vue-router'
import { watch, ref } from 'vue'
const route = useRoute()
const router = useRouter()
const tagsList = ref([])
const tagsActiveIndex = ref(1)

const tagClick = (item, index) => {
  router.push(item.path)
  tagsActiveIndex.value = index
}
const tagClose = (index) => {
  const _path = tagsList.value[tagsActiveIndex.value].path
  tagsList.value.splice(index, 1)

  if (tagsActiveIndex.value === index) {
    tagsActiveIndex.value = index > 0 ? index - 1 : 1
    router.push(tagsList.value[tagsActiveIndex.value].path)
  } else {
    const hasIndex = tagsList.value.findIndex((v) => v.path === _path)
    tagsActiveIndex.value = hasIndex
  }
}

watch(
  () => route,
  (newValue, oldValue) => {
    const hasIndex = tagsList.value.findIndex((v) => v.path === newValue.path)
    if (hasIndex < 0 && newValue.meta.title !== '') {
      tagsList.value.push({
        name: newValue.meta.title,
        path: newValue.path
      })
      tagsActiveIndex.value = tagsList.value.length - 1
    } else {
      // tagsActiveIndex.value = hasIndex;
    }
  },
  { immediate: true, deep: true }
)
</script>
<style lang="scss" scoped>
.tag-list {
  .el-tag{
    background: rgba(69, 85, 82, 0.10);
    color:rgba(69, 85, 82, 1);
    margin-right: 10px;
    cursor: pointer;
    &.isActive {
      background: rgba(69, 85, 82, 0.10);
      color:rgba(69, 85, 82, 1);
      ::v-deep{
        .el-icon{
          color:rgba(69, 85, 82, 1);
        }

      }
    }
  }
}
:deep(.el-tag__close){
  color:rgba(69, 85, 82, 1) !important;
}
:deep(.el-tag__close:hover){
  background-color: transparent !important;
}
</style>
