<template>
  <div class="donut-chart-container">
    <div v-if="loading" class="chart-loading">
      <div class="loading-spinner"></div>
    </div>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

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

// 接收 barOptionData: { names: string[], values: number[], total: number }
const props = defineProps<{
  data: {
    names: string[]
    values: number[]
    total: number
  }
  loading?: boolean
}>()

const chartRef = ref<HTMLDivElement>()
const chartInstance = shallowRef<echarts.ECharts>()

function initChart() {
  if (!chartRef.value) return
  
  chartInstance.value = echarts.init(chartRef.value)
  updateChart()
}

function updateChart() {
  if (!chartInstance.value || props.loading) return
  if (!props.data?.names?.length) return

  const option = pieOption(props.data)
  chartInstance.value.setOption(option)
}

function handleResize() {
  chartInstance.value?.resize()
}

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

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chartInstance.value?.dispose()
})

watch(() => props.data, updateChart, { deep: true })
watch(() => props.loading, (loading) => {
  if (!loading) {
    updateChart()
  }
})
</script>

<style scoped>
.donut-chart-container {
  position: relative;
  width: 100%;
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.chart-loading {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #E8E8E8;
  border-top-color: #2D8CF0;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
