<template>
  <div :id="props.ids" style="width: 100%; height: 100%">
  </div>
</template>
<script setup>
import * as echarts from "echarts";
import { ref, defineProps, onMounted, watch, nextTick } from "vue";
import { chartAdaptation } from "@/utils/tools";
const props = defineProps({
  pieData: {
    type: Array,
    default: []
  },
  ids: {
    type: String,
    default: ''
  }
});
const chartId = ref(props.ids || `chart-${Math.random().toString(36).substr(2, 9)}`);
let myChart = null;

// 确保DOM渲染完成后再初始化图表
onMounted(() => {
  nextTick(() => {
    initializeChart();
  });
});

// 监听数据变化
watch(() => props.pieData, (newData) => {
  if (myChart && newData && newData.length > 0) {
    updateChart();
  }
}, { deep: true, immediate: true });

const initializeChart = () => {
  const chartDom = document.getElementById(chartId.value);

  if (!chartDom) {
    console.error('图表容器未找到:', chartId.value);
    return;
  }

  try {
    myChart = echarts.init(chartDom);
    updateChart();

    // 自适应
    chartAdaptation(myChart);
    window.addEventListener('resize', () => {
      myChart && myChart.resize();
    });
  } catch (error) {
    console.error('图表初始化失败:', error);
  }
};

const updateChart = () => {
  if (!myChart || !props.pieData || props.pieData.length === 0) {
    console.log('图表或数据未准备好');
    return;
  }
  let option;
  option = {
    backgroundColor: "rgba(0,0,0,0)",
    tooltip: {
      trigger: 'item',
      formatter: "{a} <br/>{b}: {c} ({d}%)"
    },
    dataZoom: [
      {
        type: "slider",
        show: true,
        left: "98%",
        start: 1,
        end: 50,
        yAxisIndex: [0],
      },
    ],
    series: [
      {
        name: '',
        type: 'pie',
        radius: '60%',
        // right: -100,
        data: props.pieData,
        color: ['#0080FF', '#E2D101', '#FF8040', '#E80000'],
        itemStyle: {
          label: {
            textStyle: {
              color: '#07c8bd'
            }
          }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(9, 217, 162, 0.8)'
          }
        }

      }
    ]
  }
  myChart.setOption(option, true);
  console.log('图表配置已更新');
}
</script>
<style scoped></style>