<template>
    <div class="btn-group">
        <div
            :class="['btn-item', { active: activeTabs === index }]"
            @click="handleActive(item,index)"
            v-for="(item, index) in baseList"
            :key="index + item"
        >
            {{ item.indicatorName }}
        </div>
    </div>
</template>

<script setup>
import {onMounted, onUnmounted, ref, watch} from 'vue'
import eventBus from "@/api/eventBus";

const props = defineProps({
    list: {
        type: Array,
        defalut: ()=>[],
    },
    keyStr: {
        type: String,
        defalut: '',
    },
    active: {
        type: String,
        defalut: '',
    },
});

onMounted(()=>{
    //监听来自 navigation 的 tab 高亮更新事件
    eventBus.on('updateTabActive', handleUpdateTabActive)
})

onUnmounted(()=>{
    eventBus.off('updateTabActive', handleUpdateTabActive)
})

const emit = defineEmits(["handleActive"])

const baseList = ref([])
const activeTabs = ref(0);
const handleActive = (item,index) => {
    activeTabs.value = index;
    emit('handleActive',{name:props.keyStr,id:item.id})
    eventBus.emit('handleActive',{id:item.id,key:props.keyStr,monitorItems:props.list})
};

// 处理来自 navigation 的 tab 高亮更新事件
function handleUpdateTabActive({indicatorId, indicatorName}) {
    // 在当前列表中查找匹配的指标
    const targetIndex = baseList.value.findIndex(item => 
        item.id === indicatorId || item.indicatorName === indicatorName
    );
    
    if (targetIndex !== -1) {
        activeTabs.value = targetIndex;
        // 触发父组件事件，确保数据也能正常更新
        emit('handleActive',{name:indicatorName,id:indicatorId})
    }
}

watch(()=>props.list,(newValue,oldValue)=>{
    if(newValue){
        baseList.value = newValue
    }
})

watch(()=>props.active,(newValue,oldValue)=>{
    if(newValue){
        const index = props.list.findIndex(item =>item.indicatorName===newValue)
        if(index!==-1){
            activeTabs.value = index
            handleActive(newValue,index)
        }
    }
})
</script>

<style lang="scss" scoped>
.btn-group {
    font-size: 11px;
    display: flex;
    align-items: center;
    .btn-item {
        border-radius: 2px;
        padding: 3px 8px;
        margin-left: 8px;
        cursor: pointer;
        flex: none;
        &.active {
            background: #4f4f4f;
        }
    }
}
</style>
