<template>
    <div class="chart-wrapper">
        <div ref="chartRef" :style="{
            width: '100%',
            height: containerHeight + 'px',
            minHeight: '300px'
        }" class="chart-container"></div>
    </div>

</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
    title: {
        type: String,
        default: '使用人数'
    },
    data: {
        type: Array,
        required: true
    },

    width: {
        type: String,
        default: '100%'
    },
    height: {
        type: String,
        default: '600px'
    }
})

const chartRef = ref(null)
const chartInstance = ref(null)



// 动态计算容器高度（核心逻辑）
const containerHeight = computed(() => {
    const minItemHeight = 40 // 每个条目的最小高度
    const baseHeight = 150   // 标题+边距等固定高度
    return Math.min(
        props.data.length * minItemHeight + baseHeight,
        props.data.length * minItemHeight + baseHeight,
    )
})

const options = {
    // 调整布局留白
    title: {
        text: props.title,
        left: 'center',
        top: '0%',
    },
    grid: {
        left: '5%',   // 给y轴标签留足空间
        right: '10%',
        containLabel: true
    },

    dataset: {
        source: props.data
    },
    xAxis: {
        type: 'value',
        axisLabel: {
            formatter: '{value} '
        }
    },
    yAxis: {
        type: 'category',
        axisLabel: {
            fontSize: 12,
            margin: 15,
            // 自动换行策略
            formatter: value => {
                const maxLineLength = 10 // 每行最多字符数
                const regex = new RegExp(`(.{1,${maxLineLength}})`, 'g')
                return value.match(regex)?.join('\n') || value
            }
        },
        // 动态间距配置
        boundaryGap: [0.1, 0.1] // 上下留白比例
    },
    series: [{
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
            color: params => params.data[1] > 0 ? '#37A2FF' : '#ccc',
            borderRadius: [0, 5, 5, 0]
        },
        label: {
            show: true,
            position: 'right',
            color: '#666'
        }
    }],
    tooltip: {
        trigger: 'axis',
        formatter: params => {
            return `${params[0].data[0]}<br/>使用次数: ${params[0].data[1]}`
        }
    },
}


// 初始化图表
const initChart = () => {
    if (!chartRef.value) return

    chartInstance.value = echarts.init(chartRef.value)
    chartInstance.value.setOption(options)

    // 绑定点击事件
    chartInstance.value.on('click', handleClick)
}

// 点击事件处理
const handleClick = (params) => {
    console.log('图表点击:', params)
}

// 窗口变化时自动调整
const handleResize = () => {
    chartInstance.value?.resize()
}

onMounted(() => {
    initChart()
    // chartRef.value.style.touchAction = 'none'
    window.addEventListener('resize', updateSize)
})

onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    chartInstance.value?.dispose()
})


const updateSize = () => {
    const width = chartRef.value.offsetWidth
    chartOptions.value.grid = {
        left: width < 600 ? '15%' : '20%',
        right: '5%'
    }
    chartInstance.setOption(chartOptions.value)
}

// 监听配置变化
watch(() => props.data, (newVal) => {
    options.dataset.source = newVal
    chartInstance.value?.setOption(options)
}, { deep: true })
</script>

<style scoped>
.chart-wrapper {
    touch-action: none;
    /* ✅ 完全禁用父级触摸 */
    pointer-events: none;
}

.chart-container {
    /* pointer-events: auto; */
    /* 恢复图表区域事件 */
    /* min-height: 300px; */
}
</style>