<template>
  <div :id="'chart-post' + id" style="width: 100%; height: 100%"></div>
</template>

<script>
export default {
  name: "ChartPost"
}
</script>
<script setup>
import {ref, onMounted, getCurrentInstance, watch, onBeforeUnmount} from 'vue'

  const { proxy } = getCurrentInstance()

  const props = defineProps({
    id: {
      type: Number,
      default: () => 0
    },
    list: {
      type: Array,
      default: () => []
    }
  })

  let myChart = null;

  const init = () => {
    let data = [
      { value: 300, name: '哺乳母猪' },
      { value: 200, name: '空怀母猪' },
      { value: 124, name: '怀孕母猪' },
      { value: 300, name: '后备母猪' },
    ]
    let options = {
      tooltip: {
        trigger: 'item'
      },
      color: ['#5579EE', '#9966FF', '#66CC33', '#FAC858'],
      legend: {
        left: 'center',
        top: 'bottom'
      },
      series: [
        {
          type: 'pie',
          radius: '45%',
          center: ['50%', '40%'],
          data: data,
          tooltip: {
            valueFormatter: function (value) {
              return value + ' 头';
            }
          },
          // emphasis: {
          //   itemStyle: {
          //     shadowBlur: 1,
          //     shadowOffsetX: 0,
          //     shadowColor: 'rgba(0, 0, 0, 0.5)'
          //   }
          // },
          label: {
            fontsize: 12,
            formatter: function (data) { //这个参数是一个对象
              let str = `${data.name}\n${data.value}头(${data.percent}%)`
              return str
            }
          },
          labelLine: {
            normal: {
              lineStyle: {
                // color: 'rgba(255, 255, 255, 0.3)'
              },
              // smooth: 0.2,
              length: 6,
              length2: 1,
            }
          },
        }
      ]
    }
    myChart.setOption(options)
  }

  onMounted(() => {
    myChart = proxy.$echarts.init(document.getElementById('chart-post' + props.id))
    init()
    window.addEventListener('resize', () => {
      myChart.resize()
    })
  })

  watch(() => props.list, () => {
    myChart.clear()
    init()
  }, { deep: true })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', () => {
      myChart.resize()
    })
  })
</script>

<style scoped>

</style>
