<template>
  <!-- 给外层容器固定宽高基准 -->
  <div class="chart-wrap">
    <div ref="chartDom" class="chartDom"></div>
  </div>
</template>
<script setup>
import * as echarts from 'echarts';
import { watch, defineProps, onMounted, ref, onBeforeUnmount } from 'vue';

const props = defineProps({
  title: {
    type: String,
    default: '各测试类型分布'
  },
  legend: {
    type: Array,
    default: () => ['已完成', '运行中', '暂停中', '异常']
  },
  xAxis: {
    type: Array,
    default: () => ['功能测试', '稳定性测试', '兼容性测试', '性能测试', '回归测试']
  },
  series: {
    type: Array,
    default: () => []
  },
})

// 提升到全局作用域，watch可访问
let myChart = null;
let option = null;
const chartDom =ref(null)
const initChart = () => {
  if (!chartDom.value) return;
  // 避免重复实例
  if (myChart) myChart.dispose();
  myChart = echarts.init(chartDom.value);

  option = {
    title: {
      text: props.title
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: props.legend,
      right: '8%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      data: props.xAxis
    },
    yAxis: {
      type: 'value'
    },
    series: props.series
  };
  // 必须渲染配置
  myChart.setOption(option);
}

// 监听props变化，深度监听
watch(() => props, () => {
  if (!myChart || !option) return;
  // 更新数据
  option.title.text = props.title;
  option.legend.data = props.legend;
  option.xAxis.data = props.xAxis;
  option.series = props.series;
  myChart.setOption(option);
}, { deep: true })

// 窗口自适应
const resizeChart = () => {
  myChart && myChart.resize();
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

// 销毁释放资源
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  if (myChart) myChart.dispose()
})
</script>

<style lang="scss" scoped>
.chart-wrap {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  padding: 10px;

   .chartDom {
        width: 100%;
        height: 100%;
    }
}

</style>