<!--
 * @Author: chris
 * @Date: 2025-10-21 11:42:40
 * @LastEditors: chris
 * @LastEditTime: 2025-11-17 10:19:34
-->
<script setup name="pie-chart">
import LEchart from '@/uni_modules/lime-echart_1.0.5/components/l-echart/l-echart.vue'

const props = defineProps({
  echarts: {
    type: Object,
    required: true,
  },
  chartData: {
    type: Object,
    default: () => ({
      datas: [
        {
          name: '红蜘蛛',
          value: 100,
          itemStyle: {
            color: '#ffa502',
          },
        },
        {
          name: '蚜虫',
          value: 170,
          itemStyle: {
            color: '#ff6b6b',
          },
        },
        {
          name: '果蝇',
          value: 140,
          itemStyle: {
            color: '#5f27cd',
          },
        },
        {
          name: '其他',
          value: 300,
          itemStyle: {
            color: '#54a0ff',
          },
        },
      ],
    }),
  },
})

const pieChartRef = ref(null)
let pieChart = null

watch(() => props.chartData, () => {
  refreshChart()
})

onMounted(async () => {
  await initChart()
})

async function initChart() {
  if (!pieChartRef.value)
    return
  pieChart = await pieChartRef.value.init(props.echarts)
  refreshChart()
}

onUnmounted(() => {
  if (pieChart)
    pieChart.dispose()
})

function refreshChart() {
  if (!pieChart)
    return
  pieChart.showLoading()
  pieChart.setOption(createOptions())
  pieChart.hideLoading()
}

function createOptions() {
  const options = {
    title: {
      text: '虫情分布状况',
      top: '2%',
      textStyle: {
        color: '#333',
        fontSize: 16,
        fontWeight: 'bold',
      },
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
      borderColor: '#333',
      textStyle: {
        color: '#fff',
      },
      formatter: '{b}: {c} ({d}%)',
    },
    legend: {
      bottom: '3%',
      left: 'center',
      textStyle: {
        color: '#333',
      },
    },
    series: [
      {
        name: '虫情分布',
        type: 'pie',
        radius: ['40%', '70%'],
        // center: ['35%', '50%'],
        // top: '3%',
        // left: '3%',
        // right: '3%',
        // bottom: '3%',
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold',
            // color: 'red',
          },
        },
        labelLine: {
          show: false,
        },
        data: props.chartData.datas,
      },
    ],
  }

  return options
}
</script>

<template>
  <view class="pie-chart">
    <l-echart id="pieChart" ref="pieChartRef" type="2d" />
  </view>
</template>

<style lang="scss" scoped>
.pie-chart {
  width: 100%;
  height: 300px;
}
</style>
