<!--
  饼图组件
  支持基础饼图、环形图、图例配置、标签显示等
-->

<template>
  <BaseChart
    :option="chartOption"
    :height="height"
    :loading="loading"
    @ready="handleReady"
    @click="handleClick"
  />
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import BaseChart from './BaseChart.vue'
import { pieChartOption, echartsTheme, getAssetStatusColor } from '@/utils/echarts'
import type { PieChartConfig } from '@/types/charts'

/** Props */
interface Props {
  data: Array<{ name: string; value: number; [key: string]: any }>
  title?: string
  type?: 'pie' | 'doughnut'
  showLegend?: boolean
  showLabel?: boolean
  height?: string
  customColor?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  data: () => [],
  title: '',
  type: 'doughnut',
  showLegend: true,
  showLabel: true,
  height: '400px',
  customColor: false,
})

/** Emits */
interface Emits {
  (e: 'ready', chart: any): void
  (e: 'click', item: any): void
}

const emit = defineEmits<Emits>()

/** 加载状态 */
const loading = ref(false)

/** 图表配置 */
const chartOption = computed(() => {
  // 处理数据
  const chartData = props.data.map((item, index) => ({
    ...item,
    itemStyle: {
      color: props.customColor && item.status
        ? getAssetStatusColor(item.status)
        : echartsTheme.color[index % echartsTheme.color.length],
    },
  }))

  // 计算半径
  const radius = props.type === 'doughnut' ? ['40%', '70%'] : ['0%', '70%']

  return {
    ...pieChartOption,
    title: {
      ...pieChartOption.title,
      text: props.title,
    },
    legend: {
      ...pieChartOption.legend,
      show: props.showLegend,
    },
    series: [
      {
        ...pieChartOption.series![0],
        radius,
        data: chartData,
        label: {
          ...pieChartOption.series![0].label,
          show: props.showLabel,
          formatter: props.showLabel ? '{b}: {c} ({d}%)' : '',
        },
        emphasis: {
          ...pieChartOption.series![0].emphasis,
          itemStyle: {
            ...pieChartOption.series![0].emphasis.itemStyle,
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)',
          },
        },
      },
    ],
  }
})

/** 处理图表就绪 */
const handleReady = (chart: any) => {
  emit('ready', chart)
}

/** 处理点击事件 */
const handleClick = (params: any) => {
  const item = props.data.find((d) => d.name === params.name)
  if (item) {
    emit('click', { ...item, ...params })
  }
}

/** 暴露方法 */
defineExpose({
  loading,
})
</script>
