<template>
  <div class="cpu-usage-chart" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  usage: {
    type: Number,
    default: 0
  },
  color: {
    type: String,
    default: '#1890ff'
  }
})

const chartRef = ref(null)
let chartInstance = null

const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
  
  const option = {
    series: [{
      type: 'gauge',
      startAngle: 90,
      endAngle: -270,
      pointer: { show: false },
      progress: {
        show: true,
        overlap: false,
        roundCap: true,
        clip: false,
        itemStyle: {
          color: props.color // 进度条颜色 - 蓝色
        }
      },
      axisLine: {
        lineStyle: {
          width: 10,
          color: [[1, '#f0f0f0']] // 背景环颜色 - 浅灰色
        }
      },
      axisTick: { show: false },
      splitLine: { show: false },
      axisLabel: { show: false },
      detail: {
        valueAnimation: true,
        offsetCenter: [0, '0%'],
        formatter: '{value}%',
        color: props.color, // 百分比数字颜色 - 蓝色
        fontSize: 24,
        fontWeight: 'bold'
      },
      title: {
        offsetCenter: [0, '30%'],
        color: '#666', // "使用率"文字颜色 - 灰色
        fontSize: 14
      },
      data: [{
        value: props.usage,
        name: '使用率'
      }]
    }],
    // title: {
    //   text: 'cpu',
    //   left: 'center',
    //   top: '10%',
    //   textStyle: {
    //     color: '#666', // "cpu"文字颜色 - 灰色
    //     fontSize: 14
    //   }
    // }
  }
  
  chartInstance.setOption(option)
}

// 监听窗口变化自动调整图表大小
const resizeHandler = () => {
  chartInstance?.resize()
}

// 监听props变化更新图表
watch(() => props.usage, (newVal) => {
  if (chartInstance) {
    chartInstance.setOption({
      series: [{
        data: [{
          value: newVal,
          name: '使用率'
        }]
      }]
    })
  }
})

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

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeHandler)
  chartInstance?.dispose()
})
</script>

<style scoped>
.cpu-usage-chart {
  width: 100%;
  height: 100%;
  background-color: white; /* 白色背景 */
}
</style>