<template>
  <div ref="chartRef" :style="{ width: '100%', height: '400px' }"></div>
</template>

<script>
import { defineComponent, onMounted, ref } from 'vue'
import * as echarts from 'echarts'
import 'echarts-gl'

export default defineComponent({
  name: 'Pie3D',
  setup() {
    const chartRef = ref(null)
    let chart = null

    const initChart = () => {
      if (!chartRef.value) return

      chart = echarts.init(chartRef.value)
      const option = {
        backgroundColor: '#1a213c',
        tooltip: {
          formatter: '{b}: {c} ({d}%)',
          backgroundColor: 'rgba(0,0,0,0.7)',
          borderColor: '#1a213c',
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: 'center',
          textStyle: {
            color: '#fff'
          },
          formatter: function(name) {
            const data = option.series[0].data
            const total = data.reduce((sum, item) => sum + item.value, 0)
            const target = data.find(item => item.name === name)
            const percentage = ((target.value / total) * 100).toFixed(0)
            return `${name}  ${target.value}`
          }
        },
        series: [{
          type: 'pie',
          radius: ['30%', '55%'],
          center: ['40%', '50%'],
          roseType: false,
          zlevel: 10,
          startAngle: 35,
          selectedMode: 'single',
          selectedOffset: 10,
          data: [
            { value: 18, name: '红色', itemStyle: { color: '#ff4d4f' } },
            { value: 13, name: '橙色', itemStyle: { color: '#ff7a45' } },
            { value: 17, name: '黄色', itemStyle: { color: '#ffc53d' } },
            { value: 2, name: '蓝色', itemStyle: { color: '#40a9ff' } }
          ],
          label: {
            show: true,
            formatter: '{d}%',
            color: '#fff',
            position: 'outside',
            fontSize: 14,
            fontWeight: 'bold'
          },
          emphasis: {
            focus: 'self',
            scaleSize: 10,
            itemStyle: {
              shadowBlur: 20,
              shadowOffsetX: 5,
              shadowOffsetY: 5,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          itemStyle: {
            borderRadius: 4,
            borderColor: '#1a213c',
            borderWidth: 2
          },
          animationType: 'scale',
          animationEasing: 'elasticOut',
          animationDelay: function (idx) {
            return Math.random() * 200;
          }
        }]
      }

      chart.setOption(option)
    }

    onMounted(() => {
      initChart()
      window.addEventListener('resize', () => {
        chart && chart.resize()
      })
    })

    return {
      chartRef
    }
  }
})
</script>

<style scoped>
</style>