<template>
  <div :ref="el => containerRef = el" style="width:100%;height:100%;min-height:150px;"></div>
</template>

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

const props = withDefaults(defineProps<{
  actual: number
  target: number
  label?: string
  unit?: string
}>(), { label: '', unit: '' })

const containerRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

function render() {
  if (!containerRef.value) return
  if (!chart) chart = echarts.init(containerRef.value)
  
  const pct = props.target > 0 ? Math.min(props.actual / props.target * 100, 100) : 0
  const isGood = props.actual >= props.target

  chart.setOption({
    series: [{
      type: 'gauge',
      startAngle: 220,
      endAngle: -40,
      min: 0,
      max: props.target * 1.3 || 1,
      progress: { show: true, width: 18, itemStyle: { color: isGood ? '#52c41a' : '#ff4d4f' } },
      axisLine: { lineStyle: { width: 18, color: [[0.3, '#ff4d4f'], [0.7, '#faad14'], [1, '#52c41a']] } },
      axisTick: { show: false },
      splitLine: { show: false },
      axisLabel: { show: false },
      pointer: { show: false },
      anchor: { show: false },
      title: { show: true, offsetCenter: [0, '30%'], fontSize: 12, color: '#999' },
      detail: {
        offsetCenter: [0, '-10%'],
        fontSize: 22,
        fontWeight: 700,
        color: isGood ? '#52c41a' : '#ff4d4f',
        formatter: (v: number) => `${props.actual?.toLocaleString()}${props.unit}`,
      },
      data: [{ value: props.actual, name: props.label }],
    }],
    grid: { top: 5, bottom: 5, left: 5, right: 5 },
  }, true)
}

watch(() => [props.actual, props.target], render)
onMounted(render)
onUnmounted(() => { chart?.dispose(); chart = null })
</script>
