<template>
  <div>
    <!-- ECharts 图表容器 -->
    <div class="section">
      <el-input
        size="small"
        v-model="xiaoval"
        placeholder="请输入查询范围"
        @input="handleInput"
      ></el-input>
      <span>—</span>
      <el-input
        size="small"
        v-model="daval"
        placeholder="请输入查询范围"
        @input="handleInput"
      ></el-input>
      <el-button size="small" @click="chaxun">确定</el-button>
      <div v-if="TZshow" class="eigenvalue">
        <h5>特征值</h5>
        <p>有效值：{{ this.Xrms }}</p>
        <p>平均值：{{ this.envelopeList.mean_value }}</p>
        <p>最大值：{{ this.envelopeList.max_value }}</p>
        <p>最小值：{{ this.envelopeList.min_value }}</p>
        <p>峰值：{{ this.envelopeList.Xp }}</p>
        <p>峰峰值：{{ this.envelopeList.Xpp }}</p>
        <p>波形因子：{{ this.envelopeList.Sf }}</p>
        <p>脉冲指标：{{ this.envelopeList.If }}</p>
        <p>裕度指标：{{ this.envelopeList.Ce }}</p>
        <p>偏度指标：{{ this.envelopeList.Cw }}</p>
        <p>峭度指标：{{ this.envelopeList.Cq }}</p>
      </div>
    </div>

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

<script>
import * as echarts from "echarts"; // 导入 echarts 库
import axios from "axios";
export default {
  name: "TimedomainCharts", // 组件名称
  props: {
    // 可以通过 props 接收外部传入的数据

    currentIndex: {
      type: Number,
      default: 0,
    },
    ids: {
      type: Array,
      default: () => [],
    },
    activeIndex: {
      type: Number,
      default: 0,
    },
    envelopeListTwo: {
      type: Object,
      default: () => ({}),
    },
    currentRow: {
      type: Object,
      default: () => ({}),
    },
    
    windCode: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      chartInstance: null,
      option: null,
      xiaoval: "",
      daval: "",
      envelopeList: {},
      TZshow: false,
    };
  },
  watch: {
    // 监听 chartData 和 chartLabels 的变化，重新绘制图表
    chartData(newData) {
      this.updateChart(newData, this.chartLabels);
    },
    chartLabels(newLabels) {
      this.updateChart(this.chartData, newLabels);
    },
    envelopeListTwo: {
      handler(newValue) {
        this.updateChart(newValue.y, newValue.x); // 更新图表
      },
      deep: true, // 确保监听对象的深层次变
    },
    envelopeList: {
      handler(newValue) {
        this.updateChart(newValue.y, newValue.x); // 更新图表
      },
      deep: true, // 确保监听对象的深层次变
    },
  },
  mounted() {
    this.initializeChart();
  },
  methods: {
    handleInput() {
      this.$emit("update:modelValue", {
        xiaoval: this.xiaoval,
        daval: this.daval,
      });
    },

    chaxun() {
      this.$emit("handleLoading", null, true, this.activeIndex);
      const params = {
        ids: this.ids,
        // windCode: "SKF001",
        windCode: this.windCode,
        analysisType: "envelope",
        fmin: this.xiaoval,
        fmax: this.daval,
      };
      axios
        .post("/WJapi/analysis/envelope", params)
        .then((res) => {
          this.envelopeList = JSON.parse(res.data);
          const defaultData =
            this.envelopeList.y || this.envelopeListTwo.y || [];
          const defaultLabels =
            this.envelopeList.x || this.envelopeListTwo.x || [];
          this.updateChart(defaultData, defaultLabels);
        })
        .catch((error) => {})
        .finally(() => {
          this.$emit("handleLoading", this.currentRow, false, this.activeIndex);
        });
    },
    initializeChart() {
      // 获取图表容器
      const chartDom = this.$refs.chart;
      // 初始化图表实例
      this.chartInstance = echarts.init(chartDom);

      // 初始化时使用空数据
      const defaultData = [];
      const defaultLabels = [];

      this.updateChart(defaultData, defaultLabels);
    },
    // 更新图表数据
    updateChart(data, labels) {
      // 获取 x 数组中的最大值
      const maxX = Math.max(...labels);
      // 计算最大值的下一个 5 的倍数
      const maxAxisValue = Math.ceil(maxX / 5) * 5;

      // 生成从 0 到 maxAxisValue 的刻度数组，间隔为 5
      const ticks = [];
      for (let i = 0; i <= maxAxisValue; i += 5) {
        ticks.push(i);
      }
      const option = {
        title: {
          text: this.envelopeList.title || this.envelopeListTwo.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", // 使用数值型 x 轴，确保每个 x 值都有展示
          name: this.envelopeList.xaxis || this.envelopeListTwo.xaxis, // 设置 X 轴标题
          nameLocation: "center", // 标题位置：可选 "start" | "center" | "end"
          nameTextStyle: {
            fontSize: 14,
            color: "#333", // 标题颜色
            padding: [10, 0, 0, 0], // 上、右、下、左的间距
          },
          // min: 0, // X 轴最小值
          // max: maxAxisValue, // X 轴最大值为计算的最大值
          // interval: 5, // X 轴每 5 个单位显示一个刻度
          axisLabel: {
            formatter: (value) => {
              // 格式化显示刻度为 5 的倍数
              return value;
            },
          },
          axisTick: {
            show: true, // 显示刻度线
          },
          axisLine: {
            show: true, // 显示轴线
          },
          data: ticks, // 设置刻度
        },

        yAxis: {
          type: "value",
          name: this.envelopeList.yaxis || this.envelopeListTwo.yaxis,
        },

        tooltip: {
          trigger: "axis",
          formatter: (params) => {
            // 获取原始的 x 数值和对应的 y 值
            const xValue = params[0].value[0]; // 获取原始的 x 数值
            const yValue = params[0].value[1]; // 获取对应的 y 数值
            return `X: ${xValue}<br/>Y: ${yValue}`; // 显示原始的 x 和 y 值
          },
          axisPointer: {
            type: "line", // 显示十字线
          },
        },

        series: [
          {
            name: "数据系列",
            type: "line", // 折线图
            data: labels.map((item, index) => [item, data[index]]), // 修改为 [x, y] 数组
            // smooth: true,
            symbol: "none", // 数据点的样式
            symbolSize: 8, // 数据点的大小
            lineStyle: {
              color: "#162961", 
              width: 1, // 线条宽度
            },
            itemStyle: {
              color: "#162961", 
              borderColor: "#fff",
              borderWidth: 1,
            },
          },
        ],
      };

      // 使用更新的配置更新图表
      this.chartInstance.setOption(option);
    },

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

    // 触发下一条
    nextRow() {
      this.$emit("update-next-row", 3, this.activeIndex);
    },

    Show() {
      this.TZshow = !this.TZshow;
    },
  },
};
</script>

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

.eigenvalue {
  position: absolute;
  top: 60px;
  right: 0;
  font-size: 10px;
  width: 100px;
  border: 1px solid black;
  padding: 5px;
  background: #fff;
  z-index: 99;

  h5 {
    line-height: 16px;
    height: 16px;
  }
}

.section {
  position: relative;
  display: flex;
  // line-height: 32px;
  .el-input {
    width: 150px;
  }
  .el-button {
    margin-left: 10px;
  }
}
</style>
