<template>
  <div class="echarts-box" v-resize="resize">
    <div ref="chartRef" :class="className" :style="{ height: height, width: width }" />
  </div>
</template>

<script setup lang="ts">
import { ECOption, EChartsType } from '#/echarts'
import useSettingsStore from '@/store/modules/settings'

const settingsStore = useSettingsStore()
const echarts = inject<any>('echarts')
const chartRef = ref(null)
export interface pieChartData {
  chartName?: string
  data: {
    value: number
    name: string
  }[]
}

interface Props {
  className?: string
  width?: string
  height?: string
  autoResize?: boolean
  chartData: pieChartData
}
const props = withDefaults(defineProps<Props>(), {
  className: 'chart',
  width: '100%',
  height: '350px',
  autoResize: true
})

watch(
  () => props.chartData,
  (val) => {
    setOptions(val)
  },
  { deep: true }
)
let chart: EChartsType | null = null

const setOptions = (data: pieChartData) => {
  const options: ECOption = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      left: 'center'
    },
    series: [
      {
        name: data.chartName ?? '',
        type: 'pie',
        radius: ['45%', '75%'],
        center: ['50%', '60%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data.data
      }
    ]
  }
  chart!.setOption(options)
  //在页面初始化加载的时候绑定页面resize事件监听。补充resize事件：resize事件是在浏览器窗口大小改变时，会触发。
  //如当用户调整窗口大小，或者最大化、最小化、恢复窗口大小显示时触发 resize 事件。
  //我们一般使用这个事件去做窗口大小与对应元素的大小适配
  if (props.autoResize) {
    // window.addEventListener('resize', () => {
    //   chart!.resize()
    // })
  }
}
const initChart = () => {
  nextTick(() => {
    if (chart !== null && chart !== undefined) {
      chart!.dispose()
    }
    if (settingsStore.colorMode === 'dark') {
      chart = echarts.init(chartRef.value, 'chalk')
    } else {
      chart = echarts.init(chartRef.value, 'macarons')
    }
    setOptions(props.chartData)
  })
}
const resizeHandler = () => {
  chart!.resize()
}
const resize = () => {
  chart!.resize()
}

onMounted(() => {
  initChart()
})
onBeforeUnmount(() => {
  /* 页面组件销毁的时候，别忘了移除绑定的监听resize事件，否则的话，多渲染几次
      容易导致内存泄漏和额外CPU或GPU占用哦*/
  if (props.autoResize) {
    // window.removeEventListener('resize', () => {
    //   chart!.resize()
    // })
  }
  chart!.dispose()
})
watch(
  () => settingsStore.colorMode,
  (val) => {
    initChart()
  },
  {
    immediate: true,
    deep: true
  }
)
defineExpose({
  resize
})
</script>
<style lang="scss" scoped>
.echarts-box {
  width: 100%;
  height: 100%;
}
</style>
