<template>
  <!-- 图表容器 Canvas -->
  <div class="chart-container wrapper">
     <h2 class="card-title">AI预警分析</h2>
    <div class="chart-wrapper">
      <canvas
        ref="chartCanvasRef"
        width="180"
        height="180"
        class="chart-canvas"
      ></canvas>
      <div class="legend-container">
        <div v-for="(item, index) in chartData" :key="index" class="legend-item">
          <div class="color-block" :style="{ backgroundColor: item.color }"></div>
          <div class="legend-text">
            <span class="legend-name">{{ item.name }}</span>
            <span class="legend-value" :style="`color: ${item.color}`">{{ item.value }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';

// 1. 定义 TS 类型接口
interface ChartDataItem {
  name: string;
  value: number;
  color: string;
}

interface RingLayer {
  outer: number;
  inner: number;
}

// 2. 核心配置与数据（5个类别）
const chartData: ChartDataItem[] = [
  { name: '疲劳驾驶', value: 10, color: '#409EFF' },
  { name: '违规打电话', value: 15, color: '#52C41A' },
  { name: '违规抽烟', value: 0, color: '#FAAD14' },
  { name: '左顾右盼', value: 2, color: '#FA8C16' },
  { name: '人脸丢失', value: 0, color: '#F5222D' },
];

// 调整环形图层尺寸以适应新的 canvas 尺寸，增大环间距离
const ringLayers: RingLayer[] = [
  { outer: 80, inner: 72 },  // 第1层：疲劳驾驶
  { outer: 65, inner: 58 },   // 第2层：违规打电话
  { outer: 50, inner: 43 },   // 第3层：违规抽烟
  { outer: 35, inner: 28 },   // 第4层：左顾右盼
  { outer: 20, inner: 12 },    // 第5层：人脸丢失
];

// 3. 获取 Canvas 元素 Ref
const chartCanvasRef = ref<HTMLCanvasElement | null>(null);

// 4. 封装绘制核心函数
const drawChart = () => {
  const canvas = chartCanvasRef.value;
  if (!canvas) {
    console.error('Canvas element not found');
    return;
  }

  const ctx = canvas.getContext('2d');
  if (!ctx) {
    console.error('Failed to get 2D context');
    return;
  }

  // 清空画布（防止重复绘制）
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  const centerX = canvas.width / 2;
  const centerY = canvas.height / 2;
  const bgColor = '#2B4D79'; // 每层独立背景色
  const startAngle = -Math.PI / 2; // 12点钟方向起始

  // 步骤1：绘制每层独立的背景
  const drawBackground = () => {
    ringLayers.forEach((layer) => {
      ctx.beginPath();
      ctx.arc(centerX, centerY, layer.outer, 0, Math.PI * 2);
      ctx.arc(centerX, centerY, layer.inner, Math.PI * 2, 0, true);
      ctx.closePath();
      ctx.fillStyle = bgColor;
      ctx.fill();
    });
  };

  // 步骤2：按比例绘制数值扇区
  const drawSectors = () => {
    const validData = chartData.filter((item) => item.value > 0);
    const total = validData.reduce((sum, item) => sum + item.value, 0);
    if (total === 0) {
      console.warn('No valid data to draw');
      // 即使没有有效数据也绘制背景
      drawBackground();
      return;
    }

    // 先绘制背景
    drawBackground();

    chartData.forEach((item, index) => {
      if (item.value <= 0) return;
      const layer = ringLayers[index];
      if (!layer) return;

      // 计算扇区角度比例
      const angleRatio = item.value / total;
      const endAngle = startAngle + Math.PI * 2 * angleRatio;

      // 绘制扇区
      ctx.beginPath();
      ctx.moveTo(centerX, centerY);
      ctx.arc(centerX, centerY, layer.outer, startAngle, endAngle);
      ctx.lineTo(
        centerX + layer.inner * Math.cos(endAngle),
        centerY + layer.inner * Math.sin(endAngle)
      );
      ctx.arc(centerX, centerY, layer.inner, endAngle, startAngle, true);
      ctx.closePath();

      ctx.fillStyle = item.color;
      ctx.fill();
    });
  };

  // 执行绘制流程
  drawSectors();
};

// 5. 挂载后初始化图表（DOM 渲染完成后执行）
onMounted(() => {
  console.log('Component mounted, attempting to draw chart');
  // 使用 nextTick 确保 DOM 已完全渲染
  setTimeout(() => {
    drawChart();
  }, 0);
});

// 可选：监听数据变化重新绘制（如需动态更新数据可启用）
watch([() => chartData], () => {
  drawChart();
}, { deep: true });

// 导出绘制函数以便外部调用
defineExpose({
  drawChart
});
</script>

<style scoped lang="scss">
.chart-container {
  width: 100%;
  overflow: auto;
  background-image: url("@/assets/jinrun/module-bg.png");
  background-repeat: no-repeat;
}

.chart-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 100%;
}

.chart-canvas {
  // background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  display: block;
}

.legend-container {
  flex: 1;
  margin-left: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  width: 2.3rem;
height: 0.28rem;
background: #144f8025;
border-radius: 0.14rem;
padding-left: 0.3rem;
}

.color-block {
  width: .17rem;
  height: .1rem;
  border: 1px solid #e0e0e0;
  margin-right: .2rem;
}

.legend-text {
 display: flex;
    gap: 0.1rem;
    justify-content: space-between;
        width: 1.3rem;
    padding-left: .12rem;
}
// .legend-text:first-child{
//   display: inline-block;
//   text-align: left;
// }

.legend-name {
  font-size: 12px;
  color: #fff;
  margin-bottom: 2px;
}

.legend-value {
  font-size: 12px;
  color: #666;
}

.wrapper{
  overflow: visible;
  width: 4.6rem;
  height: 3rem;
  position: relative;
  padding: 0.15rem;
  padding-top: 0.45rem;
  
  .card-title {
    position: absolute;
    left: 0.25rem;
    top: -0.15rem;
    font-weight: 500;
    font-size: 0.2rem;
    color: #ffffff;
    text-shadow: 0rem 0rem 0rem rgba(5, 38, 68, 0.5);
  }
}
</style>