<!--
  仪表盘组件
  用于展示百分比、利用率等指标
-->

<template>
  <BaseChart
    :option="chartOption"
    :height="height"
    :loading="loading"
    @ready="handleReady"
  />
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import BaseChart from './BaseChart.vue'
import { gaugeChartOption, echartsTheme } from '@/utils/echarts'
import type { GaugeChartConfig } from '@/types/charts'

/** Props */
interface Props {
  value: number
  min?: number
  max?: number
  title?: string
  unit?: string
  height?: string
  color?: string[]
  showDetail?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  value: 0,
  min: 0,
  max: 100,
  title: '',
  unit: '%',
  height: '300px',
  color: () => [echartsTheme.color[5], echartsTheme.color[4], echartsTheme.color[6]],
  showDetail: true,
})

/** Emits */
interface Emits {
  (e: 'ready', chart: any): void
}

const emit = defineEmits<Emits>()

/** 加载状态 */
const loading = ref(false)

/** 图表配置 */
const chartOption = computed(() => {
  // 计算颜色分段
  const splitNumber = 10
  const step = (props.max - props.min) / splitNumber

  return {
    ...gaugeChartOption,
    title: {
      ...gaugeChartOption.title,
      text: props.title,
    },
    series: [
      {
        ...gaugeChartOption.series![0],
        min: props.min,
        max: props.max,
        splitNumber,
        axisLine: {
          ...gaugeChartOption.series![0].axisLine,
          lineStyle: {
            width: 18,
            color: props.color.map((c, i) => [
              (props.min + step * (i + 1)) / props.max,
              c,
            ]),
          },
        },
        detail: {
          ...gaugeChartOption.series![0].detail,
          show: props.showDetail,
          valueAnimation: true,
          formatter: (value: number) => {
            return props.unit === '%' ? `${value.toFixed(1)}%` : `${value.toFixed(1)}${props.unit}`
          },
        },
        data: [
          {
            value: props.value,
          },
        ],
        title: {
          offsetCenter: [0, '90%'],
          fontSize: 14,
          color: echartsTheme.textColor2,
        },
      },
    ],
  }
})

/** 处理图表就绪 */
const handleReady = (chart: any) => {
  emit('ready', chart)
}

/** 暴露方法 */
defineExpose({
  loading,
})
</script>
