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

<script setup>
  import styleUtil from '@/utils/styleUtil'
  import { fitChartSize } from '@/utils/dataUtil'
  import { useEchart } from '@/hooks/echart'

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

  const { id, chart, setOption, initChart } = useEchart()

  var colorList = ['#FDC40A', '#FF5232', '#50F0A6', '#5FDFFA']

  var defaultCofig = {
    color: colorList,
    legend: {
      orient: 'vertical',
      bottom: 'center',
      left: '70%',
      itemWidth: fitChartSize(20),
      itemHeight: fitChartSize(20),
      itemGap: fitChartSize(20),
      textStyle: {
        color: '#ffffff',
        fontSize: fitChartSize(20)
      }
    },
    series: [
      {
        type: 'pie',
        center: ['30%', '50%'],
        radius: ['40%', '55%'],
        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: []
      }
    ]
  }

  watch(
    () => props.dataList,
    (newVal) => {
      if (newVal.length > 0) {
        nextTick(() => {
          defaultCofig.legend.formatter = (name) => {
            let percent = props.dataList.find((item) => item.name == name).value
            return name + '\u3000' + `${percent}%`
          }
          defaultCofig.series[0].data = props.dataList
          defaultCofig.series[0].label.formatter = () => {
            return `{value|${props.total}}` + '\n' + `{name|舆情总数  }`
          }
          setOption({
            ...defaultCofig,
            ...props.config
          })
        })
      }
    },
    { immediate: true }
  )
</script>

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