<template>
  <div class="donut-chart" :class="{ 'donut-chart--legendless': !showLegend }">
    <div class="donut-body">
      <div ref="chartElement" class="donut-canvas" role="img" :aria-label="ariaLabel"></div>
      <div class="donut-center">
        <strong>{{ centerValue }}</strong>
        <span>{{ centerLabel }}</span>
      </div>
    </div>
    <div v-if="showLegend" class="donut-legend">
      <div v-for="item in resolvedItems" :key="item.name" class="legend-row">
        <i :style="{ background: item.resolvedColor }"></i>
        <span class="legend-name">{{ item.name }}</span>
        <span class="legend-val">{{ item.display }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, shallowRef } from 'vue'
import { PieChart } from 'echarts/charts'
import { TooltipComponent } from 'echarts/components'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'

import { useEcharts } from '../../composables/useEcharts.js'
import { resolveCssColor, useThemeColors } from '../../composables/useThemeColors.js'

use([TooltipComponent, PieChart, CanvasRenderer])

const props = defineProps({
  items: { type: Array, required: true },
  centerValue: { type: String, required: true },
  centerLabel: { type: String, required: true },
  showLegend: { type: Boolean, default: true }
})

const showLegend = computed(() => props.showLegend)

const chartElement = shallowRef(null)
const themeColors = useThemeColors()
const resolvedItems = computed(() => {
  const fallback = themeColors.value.chartPrimary

  return props.items.map((item) => ({
    ...item,
    value: Math.max(Number(item.value || 0), 0),
    resolvedColor: resolveCssColor(item.color, fallback)
  }))
})

const ariaLabel = computed(() =>
  `${props.centerLabel}${props.centerValue}，${resolvedItems.value.map((item) => `${item.name}${item.display}`).join('，')}`
)

const chartOptions = computed(() => ({
  backgroundColor: 'transparent',
  animation: true,
  animationDuration: 1200,
  animationDurationUpdate: 1200,
  animationEasing: 'linear',
  animationEasingUpdate: 'linear',
  tooltip: {
    trigger: 'item',
    confine: true,
    appendToBody: true,
    backgroundColor: 'rgba(255, 255, 255, 0.98)',
    borderColor: 'rgba(148, 163, 184, 0.24)',
    borderWidth: 1,
    padding: [9, 10],
    textStyle: {
      color: '#334155',
      fontSize: 12,
      fontWeight: 700
    },
    extraCssText: 'border-radius:4px;box-shadow:0 12px 28px rgba(15,23,42,.12);',
    formatter: (params) => `${params.marker}${params.name}: ${params.percent}%`
  },
  series: [
    {
      type: 'pie',
      radius: ['60%', '88%'],
      center: ['50%', '50%'],
      startAngle: 90,
      animationType: 'expansion',
      animationTypeUpdate: 'expansion',
      avoidLabelOverlap: true,
      padAngle: 1.5,
      minAngle: 2,
      label: { show: false },
      labelLine: { show: false },
      itemStyle: {
        borderColor: '#ffffff',
        borderWidth: 3,
        borderRadius: 4
      },
      emphasis: {
        scale: true,
        scaleSize: 3
      },
      data: resolvedItems.value.map((item) => ({
        name: item.name,
        value: item.value,
        itemStyle: { color: item.resolvedColor }
      }))
    }
  ]
}))

useEcharts(chartElement, chartOptions)
</script>

<style scoped>
.donut-chart {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 240px;
  gap: 10px;
}

.donut-chart--legendless {
  min-height: 0;
  justify-content: center;
}

.donut-chart--legendless .donut-body {
  margin-top: 0;
}

.donut-body {
  position: relative;
  width: 100%;
  height: 166px;
  margin: 0 auto;
  margin-top: 4px;
}

.donut-canvas {
  width: 100%;
  height: 100%;
}

.donut-center {
  position: absolute;
  inset: 0;
  display: grid;
  place-items: center;
  place-content: center;
  pointer-events: none;
  text-align: center;
  animation: donutCenterIn 620ms ease both;
  animation-delay: 360ms;
}

.donut-center strong {
  color: #1e293b;
  font-size: 17px;
  font-weight: 850;
  line-height: 1;
}

.donut-center span {
  margin-top: 4px;
  color: #64748b;
  font-size: 11px;
}

.donut-legend {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 6px 16px;
  animation: donutLegendIn 560ms ease both;
  animation-delay: 480ms;
}

.legend-row {
  display: flex;
  align-items: center;
  gap: 6px;
}

.legend-row i {
  width: 8px;
  height: 8px;
  border-radius: 2px;
  flex: 0 0 auto;
}

.legend-name {
  color: #475569;
  font-size: 12px;
}

.legend-val {
  margin-left: auto;
  color: #94a3b8;
  font-size: 11px;
}

@keyframes donutCenterIn {
  from {
    opacity: 0;
    transform: scale(.92);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes donutLegendIn {
  from {
    opacity: 0;
    transform: translateY(8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (prefers-reduced-motion: reduce) {
  .donut-center,
  .donut-legend {
    animation: none;
  }
}
</style>
