<template>
  <div ref="chartRef"
    :class="className"
    :style="{ height: height, width: width }" />
</template>

<script setup>
import * as echarts from 'echarts'
import { useWindowResize } from '@/hooks'

defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '300px'
  }
})
let chart = null
const chartRef = ref(null)

const initChart = () => {
  chart = echarts.init(chartRef.value)

  chart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: {
      left: 'center',
      bottom: '10',
      data: ['北京', '上海', '广州', '深圳', '杭州'],
      textStyle: {
        color: '#888'
      }
    },
    series: [
      {
        name: '客户分布地图',
        type: 'pie',
        roseType: 'radius',
        radius: [15, 95],
        center: ['50%', '38%'],
        data: [
          { value: 320, name: '北京' },
          { value: 240, name: '上海' },
          { value: 149, name: '广州' },
          { value: 100, name: '深圳' },
          { value: 59, name: '杭州' }
        ],
        animationEasing: 'cubicInOut',
        animationDuration: 2000,
      }
    ]
  })
}

const resize = () => {
  chart.resize()
}
useWindowResize(resize)

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

onBeforeUnmount(() => {
  if (!chart) {
    return
  }
  chart.dispose()
  chart = null
})
</script>
