<template>
  <div class="chartsT">
      应用发布分类
      <div ref="chartDom" style="width:100%;height:100%"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "DonutChart",
 props: {
    chartData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null,
      allNum:'',
    }
  },
  watch: {
     chartData:{
          handler(val) {                
              if (val.length) {
                  this.initChart();
              }
          },
          deep:true,
          immediate: true  // 组件创建时立即执行
      }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.chart && this.chart.dispose();
  },
  methods: {
    handleResize() {
      this.chart && this.chart.resize();
    },
    initChart() {
      this.$nextTick(() => {
        this.chart = echarts.init(this.$refs.chartDom);
        this.updateChart();
      })
     
    },
    updateChart() {
     this.allNum = this.chartData.reduce((sum, val) => sum + val.form_count, 0);
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right:'right',
          data: this.chartData.map(item => item.name || '未命名')
        },
        series: [
          {
            name: '数量占比',
            type: 'pie',
            radius: ['30%', '70%'], // 创建环形图
            avoidLabelOverlap: false,
            label: {
              show: false,
            },
            itemStyle: {
              borderRadius: 8,
              borderColor: '#fff',
              borderWidth: 2
            },
            labelLine: {
              show: false
            },
            data: this.chartData.map(item => ({
              value: item.form_count,
              name: item.name || '未命名'
            }))
          }
        ],
        graphic: {
          type: 'text',
          left: 'center',
          top: 'middle',
          style: {
            text: `总计\n${this.allNum}个`,
            fill: '#000',
            font: '20px Arial',
            textAlign: 'center',
            transform: 'translate(-50%,-50%)'
          },
          silent: true
        }
        
      };
      this.chart.setOption(option);
      window.removeEventListener('resize', this.chart.resize);

    },
    
  },
  
};
</script>

<style>
.chartsT{
  width: 100%;
  height: 100%;
}
</style>
