<template>
  <!-- 饼图 -->
  <div ref="pieChart" :style="{ height: `${height}px` }" class="chart_width"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import throttle from 'lodash/throttle'
import { getScorePerformanceAnalysis } from '@/utils/common'

// 定义 props 类型
interface Props {
  height?: string | number
  color?: string[]
  data?: Array<{ value: number; name: string }>
  refresh?: boolean
  position?: 'outside' | 'inside'
  unit?: string
  radius?: string
}

const props = withDefaults(defineProps<Props>(), {
  height: '',
  color: () => getScorePerformanceAnalysis(),
  data: () => [],
  refresh: false,
  position: 'outside',
  unit: '%',
  radius: '80%'
})

// 定义 emits
const emit = defineEmits<{
  (e: 'refresh', value: boolean): void
}>()

// 模板引用
const pieChart = ref<HTMLElement | null>(null)
let myChart: echarts.ECharts | null = null

// 加载图表的函数
const LoadEchart = (): void => {
  if (myChart) {
    myChart.dispose()
  }
  if (!pieChart.value) return

  myChart = echarts.init(pieChart.value)

  const option: echarts.EChartsOption = {
    tooltip: {
      show: false,
      trigger: 'item'
    },
    // 调色板
    color: props.color && props.color.length > 0 ? props.color : getScorePerformanceAnalysis(),
    legend: {
      show: false
    },
    series: []
  }

  if (props.position === 'outside') {
    option.series = [
      {
        type: 'pie',
        radius: props.radius,
        center: ['50%', '50%'],
        avoidLabelOverlap: true,
        label: {
          position: 'outside',
          color: '#666666',
          formatter: `{b}: {d}${props.unit}`,
          fontSize: 14
        },
        labelLine: {
          show: true
        },
        data: props.data
      }
    ]
  } else {
    option.series = [
      {
        type: 'pie',
        radius: props.radius,
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        label: {
          position: 'inside',
          color: '#fff',
          formatter: `{b}: {d}${props.unit}`,
          fontSize: 14
        },
        data: props.data
      }
    ]
  }

  myChart.setOption(option, true)
  emit('refresh', false)

  // 注意：原逻辑每次 LoadEchart 都会添加 resize 监听，会导致监听器重复添加。
  // 为保持逻辑完全一致，此处保留原行为。建议实际使用时将监听器移至 onMounted 中只添加一次。
  window.addEventListener('resize', handleResize)
}

// 节流处理窗口大小变化
const handleResize = throttle(() => {
  LoadEchart()
}, 500)

// 监听 data 变化（深度监听）
watch(
  () => props.data,
  () => {
    LoadEchart()
  },
  { deep: true }
)

// 监听 refresh 变化
watch(
  () => props.refresh,
  (value) => {
    if (value) {
      LoadEchart()
    }
  }
)

// 生命周期
onMounted(() => {
  LoadEchart()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
})
</script>

<style lang="scss" scoped>
.chart_width {
  width: 100%;
  height: 300px; // 设置图表高度
  overflow: hidden;
}
</style>