<template>
  <div ref="chartRef" :style="{ width: width, height: height }" class="chart-container"></div>
</template>

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

// 定义组件属性
const props = defineProps({
  title: {
    type: String,
    default: '柱状图'
  },
  // 图表宽度
  width: {
    type: String,
    default: '100%'
  },
  // 图表高度
  height: {
    type: String,
    default: '400px'
  },
  // 图表数据
  chartData: {
    type: Object,
    default: () => ({
      // x轴数据
      xAxisData: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      // 系列数据
      seriesData: [
        {
          name: 'Series 1',
          data: [120, 200, 150, 80, 70, 110, 130],
          color: '#409EFF'
        },
        {
          name: 'Series 2',
          data: [86, 99, 150, 320, 200, 130, 210],
          color: '#67C23A'
        }
      ]
    })
  },
  // 图表配置选项
  chartOptions: {
    type: Object,
    default: () => ({})
  }
});

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

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

  // 销毁已存在的图表实例
  if (chartInstance) {
    chartInstance.dispose();
  }

  // 创建新的图表实例
  chartInstance = echarts.init(chartRef.value);

  // 设置图表配置
  updateChart();
};

// 更新图表
const updateChart = () => {
  if (!chartInstance) return;
  const option = {
    title: {
      text: props.title,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: props.chartData.seriesData.map(item => item.name),
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: props.chartData.xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series: props.chartData.seriesData.map(item => ({
      name: item.name,
      type: 'bar',
      barWidth: '30%',
      emphasis: {
        focus: 'series'
      },
      itemStyle: {
        color: item.color,
        borderRadius: [4, 4, 0, 0]
      },
      data: item.data
    })),
    // 合并用户自定义配置
    ...props.chartOptions
  };

  chartInstance.setOption(option);
};

// 响应式更新图表
watch(() => [props.chartData, props.chartOptions], () => {
  updateChart();
}, { deep: true });

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 组件挂载时初始化图表
onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

// 组件卸载时销毁图表
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.chart-container {
  position: relative;
}
</style>
