<!--
 * @Author: chris
 * @Date: 2025-08-18 09:36:11
 * @LastEditors: chris
 * @LastEditTime: 2025-10-09 10:58:32
-->
<script setup>
import { LineChart } from 'echarts/charts';
// 引入标题，提示框，直角坐标系，数据集，内置数据转换器组件，组件后缀都为 Component
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components';
// 标签自动布局、全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features';
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers';

const props = defineProps({
  chartData: {
    type: Object,
    required: true,
    default: () => ({
      names: [],
      dates: [],
      values: []
    })
    // default: () => ({
    //   legend: ['蚜虫', '利蚂', '红蜘蛛', '大蚕蛾', '蝎蝽', '黄螟'],
    //   xAxis: ['2025/06/01', '2025/06/02', '2025/06/03', '2025/06/04', '2025/06/05', '2025/06/06', '2025/06/07'],
    //   series: [{ name: '蚜虫', data: [120, 200, 150, 80, 70, 110, 130]}, { name: '利蚂', data: [120, 200, 150, 80, 70, 110, 130]}, { name: '红蜘蛛', data: [120, 200, 150, 80, 70, 110, 130]}, { name: '大蚕蛾', data: [120, 200, 150, 80, 70, 110, 130]}, { name: '蝎蝽', data: [120, 200, 150, 80, 70, 110, 130]}, { name: '黄螟', data: [120, 200, 150, 80, 70, 110, 130]}]
    // })
  }
});

const { proxy } = getCurrentInstance()
const lineChartRef = ref(null)
let lineChart = null

registerComponents()

onMounted(() => {
  initLineChart()
})

onUnmounted(() => {
  if (lineChart) {
    lineChart.dispose();
    lineChart = null;
  }
});

watch(() => props.chartData, (newData) => {
  if (lineChart) {
    lineChart.setOption(createOption(newData));
  }
}, { deep: true });

function initLineChart() {
  if (lineChartRef.value) {
    lineChart = proxy.$echarts.init(lineChartRef.value);
    lineChart.setOption(createOption(props.chartData));
  }
}

function createSeries () {
  return props.chartData.values?.map((item) => {
    return {
      name: item.name,
      type: 'line',
      stack: 'Total',
      data: item.data
    }
  })
}

function createOption (data) {
  const series = createSeries();

  const option = {
    title: {
      text: '虫害趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: data.names
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category', 
      boundaryGap: false,
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: series
  };
  return option;
}

function registerComponents() {
  // 注册必须的组件
  proxy.$echarts.use([TitleComponent, TooltipComponent, GridComponent, DatasetComponent, TransformComponent, LineChart, LabelLayout, UniversalTransition, CanvasRenderer]);
}

function calcBoxSize () {}
</script>

<template>
  <div class="trend-chart">
    <div class="line-chart" ref="lineChartRef"></div>
  </div>
</template>

<style lang="scss" scoped>
.trend-chart, .line-chart {
  @apply h-100% w-100%;
}
</style>