<template>
  <div class="bar-chart">
    <h3 class="chart-title">{{ title }}</h3>
    <chartsCard
      :option="chartOption"
      :width="width"
      :height="height"
      @chart-ready="handleChartReady"
    />
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import chartsCard from './chartsCard.vue'

const props = defineProps({
  title: {
    type: String,
    default: '柱状图'
  },
  xData: {
    type: Array,
    required: true // X轴数据（通常是类别）
  },
  yData: {
    type: Array,
    required: true // Y轴数据（数值）
  },
  seriesName: {
    type: String,
    default: '数据' // 系列名称
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '400px'
  },
  color: {
    type: String,
    default: '#5793f3' // 柱子颜色
  },
  barWidth: {
    type: [String, Number],
    default: '40%' // 柱子宽度
  }
})

const chartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    borderColor: '#ddd',
    borderWidth: 1,
    textStyle: { color: '#333' },
    formatter: (params: any) => {
      const p = params[0]
      return `${p.name}<br/>${p.seriesName}: ${p.value}`
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: props.xData,
    axisTick: {
      show: false
    },
    axisLine: {
      lineStyle: {
        color: '#999'
      }
    },
    axisLabel: {
      color: '#666',
      interval: 0, // 强制显示所有标签
      rotate: 45 // 标签旋转角度
    }
  },
  yAxis: {
    type: 'value',
    axisTick: {
      show: false
    },
    axisLine: {
      show: false
    },
    axisLabel: {
      color: '#666'
    },
    splitLine: {
      lineStyle: {
        color: '#eee'
      }
    }
  },
  series: [
    {
      name: props.seriesName,
      type: 'bar',
      data: props.yData,
      barWidth: props.barWidth,
      itemStyle: {
        color: props.color,
        borderRadius: [4, 4, 0, 0] // 柱子圆角
      },
      emphasis: {
        itemStyle: {
          color: `${props.color}DD` // 高亮颜色
        }
      }
    }
  ]
}))

const handleChartReady = (chart: any) => {
  // 可添加交互逻辑
}
</script>

<style scoped lang="less">
.bar-chart {
  .chart-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    color: #333;
  }
}
</style>