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

<script>
import * as echarts from 'echarts';
export default {
  props: {
    chartData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null,
      allNum:'',
    }
  },
  computed:{
    numL(){
      return this.chartData.reduce((sum, val) => sum + val.form_count, 0);
    }
  },
  watch: {
     chartData:{
            handler(val) { 
              console.log('chartData',val);           
                if (val.length) {
                    this.initChart()
                }
            },
            deep:true,
            immediate: true  // 组件创建时立即执行
        }
  },
  mounted(){
      this.initChart()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.chart.dispose();
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chartDom);
      this.updateChart();
    },
    updateChart() {
      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.numL}次`,
            fill: '#000',
            font: '20px Arial',
            textAlign: 'center',
            transform: 'translate(-50%,-50%)'
          },
          silent: true
        }
      };
      this.chart.setOption(option);
      window.addEventListener('resize', this.chart.resize);

    },
    handleResize() {
      this.chart && this.chart.resize();
    },
  }
}
</script>
<style>
.chartsT{
  width: 100%;
  height: 100%;
}
</style>
