<template>
  <div ref="chart" style="height: 100%;width: 100%;"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  props: {
    // chartData: {
    //   type: Array, // 数据形式为 [[x1, y1], [x2, y2], ...]
    //   required: true,
    // },
  },
  mounted() {
    console.log('chartData',this.chartData);
    
    // this.initChart();
  },
  methods: {
    calculateTrendLine(data) {
      // 计算趋势线的斜率和截距
      const n = data.length;
      let sumX = 0,
        sumY = 0,
        sumXY = 0,
        sumX2 = 0;

      data.forEach(([x, y]) => {
        sumX += x;
        sumY += y;
        sumXY += x * y;
        sumX2 += x * x;
      });

      const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
      const intercept = (sumY - slope * sumX) / n;

      // 根据斜率和截距生成趋势线数据
      const minX = Math.min(...data.map(([x]) => x));
      const maxX = Math.max(...data.map(([x]) => x));
      const trendLine = [
        [minX, slope * minX + intercept],
        [maxX, slope * maxX + intercept],
      ];

      return trendLine;
    },
    initChart() {
      const chart = echarts.init(this.$refs.chart);

      // 计算趋势线数据
      const trendLine = this.calculateTrendLine(this.chartData);

      const option = {
        title: {
          text: '散点图（带趋势线）',
          left: 'center',
          textStyle: {
            fontSize: 16,
          },
        },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            if (params.seriesName === '数据点') {
              return `X: ${params.data[0]}<br>Y: ${params.data[1]}`;
            }
            return '';
          },
        },
        xAxis: {
          type: 'value',
        //   name: 'X',
          min: 0,
        },
        yAxis: {
          type: 'value',
        //   name: 'Y',
          min: 0,
        },
        series: [
          {
            name: '数据点',
            type: 'scatter',
            data: this.chartData,
            symbolSize: 10,
            itemStyle: {
              color: '#4C76F3',
            },
          },
          {
            name: '趋势线',
            type: 'line',
            data: trendLine,
            lineStyle: {
              color: '#F56C6C',
              type: 'dashed',
            },
            symbol: 'none', // 去掉趋势线的点
          },
        ],
      };

      chart.setOption(option);
      this.chartInstance = chart;
    },
  },
 
};
</script>

<style>
.chart-container {
  width: 100%;
  height: 400px;
}
</style>