<template>
  <div class="spotRate" :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: () => 0
    },
    label: {
      type: String,
      default: () => ''
    },
    colors: {
      type: Array,
      default: () => ['#FDC40A', '#FF5232', '#50F0A6', '#5FDFFA']
    }
  })

  const { id, setOption } = useEchart()

  var 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(18)
          },
          value: {
            color: '#fff',
            fontSize: fitChartSize(18)
          }
        }
      }
    },
    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: []
      }
    ]
  }

  watch(
    () => props.dataList,
    (newVal) => {
      if (newVal.length > 0) {
        nextTick(() => {
          defaultCofig.color = props.colors
          defaultCofig.series[0].data = props.dataList
          defaultCofig.series[0].label.formatter = () => {
            return `{value|${props.total}}` + '\n' + `{name|${props.label}}`
          }
          setOption({
            ...defaultCofig,
            ...props.config
          })
        })
      }
    },
    { immediate: true }
  )
</script>

<style scoped lang="scss">
  .spotRate {
    width: vw(640);
    height: vh(400);
  }
</style>
