<template>
  <div class="alarmRate" :id="id" />
</template>

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

  const props = defineProps({
    config: {
      type: Object,
      default: () => {
        return {}
      }
    },
    dataList: {
      type: Array,
      default: () => []
    },
    total: {
      type: Number,
      default: () => 123456
    },
    colors: {
      type: Array,
      default: () => ['#FDC40A', '#FF5232', '#50F0A6', '#5FDFFA']
    }
  })

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

  let params = null

  let defaultCofig = {
    color: [],
    legend: {
      orient: 'vertical',
      y: 'center',
      left: '50%',
      itemWidth: fitChartSize(18),
      itemHeight: fitChartSize(18),
      itemGap: fitChartSize(6),
      formatter: (name) => {
        let obj = props.dataList.find((item) => item.name == name)
        return `{name|${name}} {value|${obj?.value}}{value|%}`
      },
      textStyle: {
        rich: {
          name: {
            color: '#fff',
            fontSize: fitChartSize(20)
          },
          value: {
            color: '#fff',
            fontSize: fitChartSize(20)
          }
        }
      }
    },
    series: [
      {
        type: 'pie',
        center: ['24%', '50%'],
        radius: ['35%', '50%'],
        itemStyle: {
          borderWidth: fitChartSize(4),
          borderColor: '#093672'
        },
        label: {
          show: true,
          position: 'center',
          fontWeight: 'bold',
          rich: {
            value: {
              color: '#fff',
              fontSize: fitChartSize(20),
              fontWeight: 'bold',
              padding: [0, 0, 5, 0]
            },
            name: {
              color: '#fff',
              fontSize: fitChartSize(22)
            }
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  }

  let getTotal = () => {
    return props.dataList.reduce((per, cur) => {
      return per + cur.value
    }, 0)
  }

  watch(
    () => props.dataList,
    () => {
      if (props.dataList.length > 0) {
        setTimeout(() => {
          init()
        }, 1000)
      }
    },
    { immediate: true }
  )

  const init = () => {
    if (!params) {
      defaultCofig.color = props.colors
      defaultCofig.series[0].data = props.dataList
      defaultCofig.series[0].label.formatter = () => {
        return `{value|${getTotal()}}` + '\n' + `{name|告警总数}`
      }
      params = {
        ...defaultCofig,
        ...props.config
      }
    } else {
      params.series[0].data = props.dataList
      params.series[0].label.formatter = () => {
        return `{value|${getTotal()}}` + '\n' + `{name|告警总数}`
      }
    }
    setOption(params)
  }
</script>

<style scoped lang="scss">
  .alarmRate {
    width: 100%;
    height: vh(400);
  }
</style>
