<template>
  <n-card :bordered="false" class="ai-warning-card">
    <div class="card-header">
      <h2 class="card-title">当月司机AI预警分析</h2>
    </div>
    <div class="chart-container" ref="chartRef"></div>
    <div class="legend">
      <div class="item"><span class="dot blue"></span> 疲劳闭眼: 10</div>
      <div class="item"><span class="dot cyan"></span> 疲劳打哈欠: 5</div>
      <div class="item"><span class="dot green"></span> 违规打电话: 15</div>
      <div class="item"><span class="dot yellow"></span> 违规抽烟: 0</div>
      <div class="item"><span class="dot orange"></span> 左顾右盼: 2</div>
      <div class="item"><span class="dot red"></span> 人脸丢失: 0</div>
    </div>
  </n-card>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import * as echarts from 'echarts';

const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

const initChart = () => {
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value);
  chartInstance.setOption({
    series: [{
      name: '预警类型', type: 'pie', radius: ['30%', '70%'],
      itemStyle: { borderRadius: 4, borderColor: 'var(--n-bg-color-secondary)', borderWidth: 2 },
      label: { show: false },
      data: [
        { value: 10, name: '疲劳闭眼', itemStyle: { color: '#36a2eb' } },
        { value: 5, name: '疲劳打哈欠', itemStyle: { color: '#4bc0c0' } },
        { value: 15, name: '违规打电话', itemStyle: { color: '#6dd230' } },
        { value: 0, name: '违规抽烟', itemStyle: { color: '#facc15' } },
        { value: 2, name: '左顾右盼', itemStyle: { color: '#ff9f40' } },
        { value: 0, name: '人脸丢失', itemStyle: { color: '#ff6384' } }
      ]
    }]
  });
};

const resizeChart = () => chartInstance?.resize();

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

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  chartInstance?.dispose();
});
</script>

<style scoped lang="scss">
.ai-warning-card {
  padding: 0.15rem;
  background: var(--n-bg-color-secondary);

  .card-header {
    margin-bottom: 0.15rem;
    .card-title {
      font-size: 0.18rem;
      font-weight: 600;
      color: var(--n-text-color-primary);
    }
  }

  .chart-container {
    width: 100%;
    height: 1.2rem;
  }

  .legend {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0.05rem;
    margin-top: 0.1rem;
    font-size: 0.12rem;
    color: var(--n-text-color-secondary);

    .item { display: flex; align-items: center; gap: 0.05rem; }
    .dot {
      width: 0.1rem; height: 0.1rem; border-radius: 50%; display: inline-block;
      &.blue { background: #36a2eb; }
      &.cyan { background: #4bc0c0; }
      &.green { background: #6dd230; }
      &.yellow { background: #facc15; }
      &.orange { background: #ff9f40; }
      &.red { background: #ff6384; }
    }
  }
}
</style>