<template>
  <div class="pie-chart-container">
    <div class="chart-header">
       <TitleComponent title="报警类型分布" :fontLevel="2" />
      <el-select v-model="selectedTimeRange" placeholder="选择时间范围" size="small">
        <el-option label="今日" value="today" />
      </el-select>
    </div>
    <div ref="pieChartRef" class="chart-content"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import TitleComponent from '@/components/TitleComponent/index.vue';

// 定义props
const props = defineProps({
  alarmTypeData: {
    type: Array,
    default: () => []
  }
});

const selectedTimeRange = ref('today');
const pieChartRef = ref(null);
let chartInstance = null;

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

const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

const initChart = () => {
  if (pieChartRef.value) {
    chartInstance = echarts.init(pieChartRef.value);
  } else {
    console.warn('Chart container not found');
    return;
  }

  const option = {
   backgroundColor: '#fff',
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {d}%'
  },
  legend: {
    bottom: '5%',
    left: 'center',
    formatter: (name) => {
      // 计算每个数据项的百分比
      const data = option.series[0].data;
      const total = data.reduce((sum, item) => sum + item.value, 0);
      const item = data.find(item => item.name === name);
      const percentage = item ? Math.round((item.value / total) * 100) : 0;
      return `${name}(${percentage}%)`;
    }
  },
  // 添加图形组件，用于在半圆中心显示图片
  graphic: [
    {
      type: 'image',
      id: 'alarmImage',
      // 图片位置与半圆中心一致
      left: 'center',
      top: '50%',
      // 图片大小
      width: 60,
      height: 60,
      // 图片路径
      style: {
        image: '/src/assets/demo/baojing.png',
        // 保持图片原始比例
        width: 60,
        height: 60
      },
      // 图片中心点调整
      origin: [30, 30]
    }
  ],
  series: [
        {
          name: '报警类型分布',
          type: 'pie',
          radius: [100, 200],
          center: ['50%', '70%'],
          // adjust the start and end angle
          startAngle: 180,
          endAngle: 360,
          data: props.alarmTypeData,
          label: {
            show: true,
            position: 'inner',
            formatter: '{d}%',
            color: '#fff',
            fontSize: 14,
          }
        }
      ]
};

  chartInstance.setOption(option);
};
</script>

<style scoped lang="scss">
.pie-chart-container {
  width: 100%;
  height: 400px;
  background: #fff;
  padding: 20px;
  box-sizing: border-box;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.chart-content {
  width: 100%;
  height: calc(100% - 60px);
}

:deep(.el-select) {
  width: 80px;
}
</style>