<template>
  <div>
    <div class="FD">
      <div v-if="TZshow" class="eigenvalue">
        <h5>特征值</h5>
        <p>有效值：{{ this.spectrumList.Xrms }}</p>
        <p>平均值：{{ this.spectrumList.mean_value }}</p>
        <p>最大值：{{ this.spectrumList.max_value }}</p>
        <p>最小值：{{ this.spectrumList.min_value }}</p>
        <p>峰值：{{ this.spectrumList.Xp }}</p>
        <p>峰峰值：{{ this.spectrumList.Xpp }}</p>
        <p>波形因子：{{ this.spectrumList.Sf }}</p>
        <p>脉冲指标：{{ this.spectrumList.If }}</p>
        <p>裕度指标：{{ this.spectrumList.Ce }}</p>
        <p>偏度指标：{{ this.spectrumList.Cw }}</p>
        <p>峭度指标：{{ this.spectrumList.Cq }}</p>
      </div>
    </div>
    <!-- ECharts 图表容器 -->

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

<script>
import axios from "axios";
import * as echarts from "echarts"; // 导入 echarts 库

export default {
  name: "TimedomainCharts", // 组件名称
  props: {
    currentIndex: {
      type: Number,
      default: 0,
    },
    activeIndex: {
      type: Number,
      default: 0,
    },
    ids: {
      type: Array,
      default: () => [],
    },
    spectrumListTwo: {
      type: Object,
      default: () => ({}),
    },
    currentRow: {
      type: Object,
      default: () => ({}),
    },
    
    windCode: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      chartInstance: null,
      option: null,
      TZshow: false,
      spectrumList: {},
    };
  },
  watch: {
    // 监听 chartData 和 chartLabels 的变化，重新绘制图表
    chartData(newData) {
      this.updateChart(newData, this.chartLabels);
    },
    chartLabels(newLabels) {
      this.updateChart(this.chartData, newLabels);
    },
    spectrumListTwo(newValue) {
      this.spectrumList = newValue; // 将 spectrumListTwo 的新值赋给 spectrumList
      if (this.chartInstance) {
        this.updateChart(this.spectrumList.y, this.spectrumList.x); // 更新图表
      }
    },
    // 监听 spectrumList 的变化
    spectrumList: {
      handler(newValue) {
        if (this.chartInstance) {
          this.updateChart(newValue.y, newValue.x); // 只在 chartInstance 初始化后更新图表
        }
      },
      deep: true, // 深度监听
    },
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.initializeChart(); // 延迟2秒后调用
        this.getTime();
      }, 2000); // 2000毫秒，即2秒
    });
  },

  methods: {
    initializeChart() {
      const chartDom = this.$refs.chart;
      if (chartDom && !this.chartInstance) {
        this.chartInstance = echarts.init(chartDom); // Initialize chart only once
      }

      // Update the chart with the initial data if available
      this.$nextTick(() => {
        if (this.chartInstance) {
          this.updateChart(this.spectrumList.y, this.spectrumList.x); // 更新图表
        }
      });
    },

    // 更新图表数据
    updateChart(data, labels) {
      if (!this.chartInstance || !labels || !data) return; // Check if chartInstance, labels, or data are not available

      // Ensure labels is an array
      if (!Array.isArray(labels)) {
        console.error("Labels are not an array");
        return;
      }

      // Ensure data and labels have the same length
      if (labels.length !== data.length) {
        console.error("Data and labels length mismatch");
        return;
      }

      const maxX = Math.max(...labels);
      const maxAxisValue = Math.ceil(maxX / 5) * 5;
      const ticks = [];
      for (let i = 0; i <= maxAxisValue; i += 5) {
        ticks.push(i);
      }

      const option = {
        title: {
          text: this.spectrumList.title,
          left: "center",
        },
        toolbox: {
          feature: {
            dataZoom: { yAxisIndex: "none" },
            restore: {},
            saveAsImage: {},
            myCustomTool: {
              show: true,
              title: "上一条",
              icon: `image://${require("@/assets/analyse/08.png")}`,
              onclick: () => this.previousRow(),
            },
            myCustomTool2: {
              show: true,
              title: "下一条",
              icon: `image://${require("@/assets/analyse/09.png")}`,
              onclick: () => this.nextRow(),
            },
            myCustomTool3: {
              show: true,
              title: "特征值",
              icon: `image://${require("@/assets/analyse/10.png")}`,
              onclick: () => this.Show(),
            },
          },
        },
        xAxis: {
          type: "value", // Use numeric x-axis
          name: this.spectrumList.xaxis, // Set X-axis title
          nameLocation: "center", // Title position
          nameTextStyle: {
            fontSize: 14,
            color: "#333", // Title color
            padding: [10, 0, 0, 0], // Padding for title
          },
          axisLabel: {
            formatter: (value) => {
              return value; // Show values without formatting
            },
          },
          axisTick: {
            show: true, // Show tick marks
          },
          axisLine: {
            show: true, // Show axis line
          },
          data: ticks, // Set tick values
        },

        yAxis: {
          type: "value", // Y-axis type as numeric
          name: this.spectrumList.yaxis, // Set Y-axis title
          nameTextStyle: {
            fontSize: 14,
            color: "#333", // Title color
            padding: [10, 0, 0, 0], // Padding for title
          },
          axisLabel: {
            formatter: (value) => {
              return value; // Show values without formatting
            },
          },
          axisTick: {
            show: true, // Show tick marks
          },
          axisLine: {
            show: true, // Show axis line
          },
        },

        tooltip: {
          trigger: "axis",
          formatter: (params) => {
            const xValue = params[0].value[0]; // Get x value
            const yValue = params[0].value[1]; // Get y value
            return `X: ${xValue}<br/>Y: ${yValue}`;
          },
          axisPointer: {
            type: "line", // Crosshair line
          },
        },

        series: [
          {
            name: "数据系列",
            type: "line", // Line chart
            data: labels.map((item, index) => [item, data[index]]), // Map x, y values
            symbol: "none", // No symbols at data points
            symbolSize: 8, // Set data point size
            lineStyle: {
              color: "rgb(75, 192, 192)", // Line color
              width: 2, // Line width
            },
            itemStyle: {
              color: "rgb(75, 192, 192)", // Data point color
              borderColor: "#fff",
              borderWidth: 2,
            },
          },
        ],
      };

      this.chartInstance.setOption(option); // Update the chart with the new option
    },

    getTime() {
      this.$emit("handleLoading", null, true, this.activeIndex);
      const params = {
        ids: this.ids,
        windCode: "SKF001",
        // windCode: this.windCode,
        analysisType: "frequency",
      };
      axios
        .post("/WJapi/analysis/frequency", params)
        .then((res) => {
          const parsedData = JSON.parse(res.data);
          // 使用 $set 或者扩展运算符确保 Vue 检测到变化
          this.spectrumList = { ...parsedData }; // 或者 this.$set(this, 'spectrumList', parsedData);
          this.$nextTick(() => {
            if (this.chartInstance) {
              this.updateChart(this.spectrumList.y, this.spectrumList.x); // 更新图表
            }
          });
        })
        .catch((error) => {
          console.error(error);
        })
        .finally(() => {
          this.$emit("handleLoading", this.currentRow, false, this.activeIndex);
        });
    },

    previousRow() {
      this.$emit("update-previous-row", 2, this.activeIndex);
    },

    // 触发下一条
    nextRow() {
      this.$emit("update-next-row", 2, this.activeIndex);
    },
    Show() {
      this.TZshow = !this.TZshow;
    },
  },
};
</script>

<style lang="scss" scoped>
.line-chart {
  width: 100%;
  height: 300px;
}
.FD {
  width: 100%;
  height: 1px;
  position: relative;
}

.eigenvalue {
  position: absolute;
  top: 30px;
  right: 0;
  font-size: 10px;
  width: 100px;
  border: 1px solid black;
  padding: 5px;
  background: #fff;
  z-index: 99;
  h5 {
    line-height: 16px;
    height: 16px;
  }
}
</style>
