<template>
  <div class="radar-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 { raderOption } from './bindEcharts'

// 接收 raderOptionData: API 返回的原始数据
// 数据结构: [{ subjectTypeName: string, areaVoList: [{ areaName: string, amount: number }] }]
const props = defineProps<{
  data: Array<{
    subjectTypeName: string
    areaVoList: Array<{
      areaName: string
      amount: 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?.length) return

  const option = raderOption(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>
.radar-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>
