<template>
  <div class="semi-donut-chart-container">
    <div ref="chartRef" class="chart"></div>
    <div class="chart-legend">
      <div v-for="(item, index) in legendData" :key="index" class="legend-item">
        <span class="legend-dot" :style="{ background: colors[index] }"></span>
        <span class="legend-label">{{ item.name }}</span>
        <span class="legend-value">{{ item.value }}%</span>
      </div>
    </div>
  </div>
</template>

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

const props = defineProps<{
  data: {
    names: string[]
    values: number[]
  }
}>()

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

const colors = ['rgba(105, 177, 255, 1)', 'rgba(255, 192, 105, 1)', 'rgba(135, 232, 222, 1)']

const legendData = computed(() => {
  return props.data.names.map((name, index) => ({
    name,
    value: props.data.values[index]
  }))
})

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

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

  const option = semiDonutOption(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 })
</script>

<style scoped>
.semi-donut-chart-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 40px;
  padding: 24px 40px;
  height: 320px;

  .chart {
    width: 240px;
    height: 240px;
    flex-shrink: 0;
  }

  .chart-legend {
    display: flex;
    flex-direction: column;
    gap: 16px;
    flex-shrink: 0;

    .legend-item {
      display: flex;
      align-items: center;
      gap: 8px;
      white-space: nowrap;

      .legend-dot {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        flex-shrink: 0;
      }

      .legend-label {
        font-size: 14px;
        color: #3B414B;
      }

      .legend-value {
        font-size: 14px;
        font-weight: 700;
        color: #3B414B;
        margin-left: 8px;
      }
    }
  }
}
</style>
