<template>
  <div
    :id="id"
    :style="{
      width: styleUtil.px2vw(width),
      height: styleUtil.px2vh(height)
    }"
  />
</template>

<script setup>
  import * as echarts from 'echarts'
  import styleUtil from '@/utils/styleUtil'
  import { fitChartSize } from '@/utils/dataUtil'
  import { guid } from '@/utils/util'

  const props = defineProps({
    width: {
      type: Number,
      default: () => 0
    },
    height: {
      type: Number,
      default: () => 0
    },
    config: {
      type: Object,
      default: () => {
        return {}
      }
    }
  })

  let id = ref(guid())
  let pieChart = null
  var colorList = ['#FDC40A', '#FF5232', '#50F0A6', '#5FDFFA', '']
  var title = ['企业', '农业', '工业', '纺织']
  var dataValue = ['15', '30', '35', '20']
  var dataList = title.map((item, index) => {
    return {
      name: item,
      value: dataValue[index]
    }
  })

  var defaultCofig = {
    color: colorList,
    legend: {
      orient: 'horizontal',
      bottom: '10%',
      left: '4%',
      data: dataList,
      itemWidth: fitChartSize(16),
      itemHeight: fitChartSize(16),
      itemGap: fitChartSize(10),
      formatter: (name) => {
        return name + '\u3000' + '19%'
      },
      textStyle: {
        color: '#ffffff',
        fontSize: fitChartSize(12)
      }
    },
    series: [
      {
        type: 'pie',
        center: ['50%', '40%'],
        radius: ['55%', '70%'],
        itemStyle: {
          borderWidth: fitChartSize(4),
          borderColor: '#093672'
        },
        label: {
          show: true,
          position: 'center',
          fontWeight: 'bold',
          formatter: function (o) {
            return `{value|123456}` + '\n' + `{name|整改率}`
          },
          rich: {
            value: {
              color: '#fff',
              fontSize: fitChartSize(24),
              fontWeight: 'bold',
              padding: [0, 0, 5, 0]
            },
            name: {
              color: '#7894A8',
              fontSize: fitChartSize(12)
            }
          }
        },
        labelLine: {
          show: false
        },
        data: dataList
      }
    ]
  }
  const resize = () => {
    if (pieChart) {
      pieChart.dispose()
      pieChart = null
      init()
    }
  }

  const init = () => {
    const dom = document.getElementById(id.value)
    pieChart = echarts.init(dom)
    pieChart.setOption({
      ...defaultCofig,
      ...props.config
    })
    // 监听窗口大小变化
    window.addEventListener('resize', resize)
  }

  onMounted(() => {
    init()
  })
</script>

<style scoped lang="scss"></style>
