<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
    },
    list: {
      type: Array,
      default: () => []
    },
    title: {
      type: [String, Number],
      default: () => ''
    },
    subTitle: {
      type: [String, Number],
      default: () => ''
    }
  })

  const { id, setOption } = useEchart()

  watch(
    () => props.list,
    (val) => {
      setTimeout(() => {
        init()
      }, 1000)
    },
    { immediate: true }
  )

  let params = null

  const getSeriesData = () => {
    return props.list.map((item) => {
      return {
        ...item,
        value: parseFloat(item.value)
      }
    })
  }

  const getTotal = () => {
    return props.list.reduce((per, cur) => {
      return per + cur.count
    }, 0)
  }

  const formatLabel = () => {
    return () => `{value|${getTotal()}}` + '\n' + `{name|${props.subTitle}}`
  }

  let defaultCofig = {
    color: ['#A665F1', '#0063FF', '#00D0FF', '#01FEFE', '#FC2638', '#FED958'],
    legend: {
      x: 'left',
      y: '74%',
      itemHeight: fitChartSize(12),
      itemWidth: fitChartSize(12),
      itemGap: fitChartSize(10),
      formatter: function (name) {
        return '{name|' + name + '}'
      },
      textStyle: {
        rich: {
          name: {
            color: '#fff',
            fontSize: fitChartSize(14)
          },
          value: {
            color: '#00D5F6',
            fontSize: fitChartSize(14)
          }
        }
      }
    },
    series: [
      {
        type: 'pie',
        center: ['50%', '40%'],
        radius: ['55%', '70%'],
        itemStyle: {
          borderWidth: fitChartSize(4),
          borderColor: '#093672'
        },
        label: {
          show: true,
          position: 'center',
          fontWeight: 'bold',
          formatter: formatLabel(),
          rich: {
            value: {
              color: '#fff',
              fontSize: fitChartSize(24),
              fontWeight: 'bold',
              padding: [0, 0, 5, 0]
            },
            name: {
              color: '#fff',
              fontSize: fitChartSize(12)
            }
          }
        },
        labelLine: {
          show: false
        },
        data: getSeriesData()
      }
    ]
  }

  const init = () => {
    if (!params) {
      params = defaultCofig
    } else {
      params.series[0].label.formatter = formatLabel()
      params.series[0].data = getSeriesData()
    }
    setOption(params)
  }
</script>

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