<template>
    <el-scrollbar ref="scrollbar" :wrap-style="{ 'align-content': 'center' }">
        <div class="app-tag">
            <el-tag closable size="default" v-for="(tag, index) in tags" :key="tag.labelName"
                :disable-transitions="true" :effect="$route.path === tag.path ? 'dark' : 'plain'"
                @close="handleClose(tag, index)" @click="handleClick(tag, index)">
                <el-tooltip effect="light" :content="tag.labelName" placement="top">
                    {{ tag.labelName.length > 4 ? tag.labelName.substring(0, 4) + '..' : tag.labelName }}
                </el-tooltip>
            </el-tag>
        </div>
    </el-scrollbar>

</template>
<script setup>
import store from '@/store'
import { nextTick, ref, watch } from 'vue'
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter()
let tags = ref([])
const scrollbar = ref()
// 生命周期
onMounted(() => {
    tags.value = store.getters.getStateTagsList
    nextTick(() => {
        autoScroll(router.currentRoute.value.path)
    })
})
// 根据路由变化更新标签
watch(() => router.currentRoute.value.path, (newVal, oldVal) => {
    if (newVal != oldVal) {
        // 找到path对应的tag
        autoScroll(router.currentRoute.value.path)
    }
})
// 关闭标签
const closeTag = (tag) => {
    store.commit('mutationCloseTag', tag)
}
// 处理关闭
const handleClose = (tag, index) => {
    if (tags.value.length === 1) { // 如果只有一个标签则不能关闭
        return
    }
    closeTag(tag) // 删除当前tag
    if (router.path === tag.path) { // 如果关闭的标签不是当前路由的话，不做路由跳转
        return
    } else {
        if (index === (tags.value.length - 1)) { // 关闭最后一个标签,则路由跳转至最后一个
            router.push(this.tags[index].path)
        } else { // 路由跳转至下一个标签页
            if (index === 0) {
                router.push(tags.value[0].path)
            } else {
                router.push(tags.value[index - 1].path)
            }
        }
    }
}
// 点击tags具体标签
const handleClick = (tag) => {
    router.push(tag.path)
    autoScroll(router.currentRoute.value.path)
}
// 设置滚动
const autoScroll = (path) => {
    // 找到path对应的tag
    tags.value.forEach((item, index) => {
        if (item.path === path) {
            scrollbar.value.setScrollLeft(index * 80)
        }
    })
}
</script>
<style scoped>
.app-tag {
    display: flex;
}

.app-tag .el-tag {
    display: flex;
    cursor: pointer;
    height: 30px;
    min-width: 80px;
    max-width: 80px;
    margin-right: 2px;
}

.app-tag .el-tag:hover {
    color: #000;
    background-color: #5A9CF8;
}
</style>
