<template>
  <div ref="chartRef" style="width: 100%; height: 230px"></div>
</template>

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

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

const initChart = () => {
  if (!chartRef.value) return;

  chartInstance = echarts.init(chartRef.value);

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '8%',
      top: '15%',
      containLabel: true,
    },
    legend: {
      data: ['黑星病', '火疫病', '叶腐病'],
      right: 10,
      top: 10,
      textStyle: {
        color: '#000',
      },
      itemWidth: 12,
      itemHeight: 10,
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月'],
      axisLine: {
        lineStyle: {
          color: '#fff',
        },
      },
      axisLabel: {
        color: '#333',
        fontSize: 12,
      },
      axisTick: {
        alignWithLabel: true, // 刻度线与标签对齐
        lineStyle: {
          color: 'rgba(255,255,255,0.3)', // 浅灰色刻度线
        },
      },
    },
    yAxis: {
      type: 'value',
      max: 1000,
      axisLine: {
        show: false,
      },
      axisLabel: {
        show: false, // 隐藏Y轴刻度
      },
      splitLine: {
        show: false, // 隐藏网格线
      },
    },
    series: [
      {
        name: '黑星病',
        type: 'bar',
        barWidth: '15%',
        itemStyle: {
          borderRadius: 4,
          color: '#3685FE', // 橙色
        },
        data: [400, 400, 300, 300, 300, 400],
      },
      {
        name: '火疫病',
        type: 'bar',
        barWidth: '15%',
        itemStyle: {
          borderRadius: 4,
          color: '#25BF82', // 绿色
        },
        data: [400, 500, 500, 500, 500, 400],
      },
      {
        name: '叶腐病',
        type: 'bar',
        barWidth: '15%',
        itemStyle: {
          borderRadius: 4,
          color: '#FFD500', // 蓝绿色
        },
        data: [400, 600, 700, 700, 700, 400],
      },
    ],
  };

  chartInstance.setOption(option);

  // 窗口大小变化时自适应
  const resizeChart = () => {
    chartInstance?.resize();
  };
  window.addEventListener('resize', resizeChart);

  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeChart);
    chartInstance?.dispose();
  });
};

onMounted(() => {
  initChart();
});
</script>
