<template>
  <div>
    <div class="FD">
      <!-- 光标 -->
      <div v-if="BGshow" class="eigenvalue">
        <el-checkbox-group v-model="checkedGB" @change="handlecursor">
          <el-checkbox v-for="(item, index) in GBcheckList" :key="index" :label="item.val">
            {{ item.val }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <!-- 特征值 -->
      <div v-if="PXshow" class="eigenvalue">
        <el-checkbox-group v-model="checkedValues" @change="handleCheckChange">
          <el-checkbox v-for="(item, index) in PXcheckList" :key="index" :label="item.val">
            {{ item.val }}
          </el-checkbox>
        </el-checkbox-group>
      </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,
      BGshow: false,
      PXshow: false,
      spectrumList: {},

      GBcheckList: [
        { val: "添加光标" , checked: false},
        { val: "谐波光标" , checked: false},
        { val: "边带光标" , checked: false},
        { val: "移动峰值" , checked: false},
      ],
      PXcheckList: [
        { val: "Fr", checked: false },
        { val: "BPFI", checked: false },
        { val: "BPFO", checked: false },
        { val: "BSF", checked: false },
        { val: "FTF", checked: false },
        { val: "3P", checked: false },
      ],
      Fr: [],
      BPFI: [],
      BPFO: [],
      BSF: [],
      FTF: [],
      B3P: [],

      checkedGB: [],
      checkedValues: [],


      cursorLines: [], // 存储添加的光标线
      cursorPoints: [], // 用于存储参考点（浮动点）数据

    };
  },
  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: {
      handler(newValue) {
        if (!newValue) return;
        console.log(newValue, "newValue");
        if (this.chartInstance) {
          this.updateChart(newValue.y, newValue.x); // 只在 chartInstance 初始化后更新图表
        }
      },
      deep: true, // 深度监听
    },
  },
  destroyed() {
  if (this.chartInstance) {
    this.chartInstance.getZr().off('dblclick', this.handleDoubleClick)
  }
},

  mounted() {
    
    this.$nextTick(() => {
      setTimeout(() => {
        this.initializeChart(); // 延迟2秒后调用
        this.getTime();
      }, 500); // 500毫秒，即0.5秒
    });
  },

  methods: {
    initializeChart() {
      const chartDom = this.$refs.chart;
      if (chartDom && !this.chartInstance) {
        this.chartInstance = echarts.init(chartDom); // 仅初始化一次
      }

      // 使用 $nextTick 确保数据更新后再渲染图表
      this.$nextTick(() => {
        if (this.chartInstance && this.spectrumList.y && this.spectrumList.x) {
          this.updateChart(this.spectrumList.y, this.spectrumList.x); // 更新图表
        }
      });

       // 绑定双击事件
    this.chartInstance.getZr().on('dblclick', this.handleDoubleClick)
    },

    handleDoubleClick(event) {
    // 只有勾选了“添加光标”时才响应
    if (!this.checkedGB.includes('添加光标')) return
    // 转换鼠标位置为图表的 x 轴数值
    const pointInGrid = this.chartInstance.convertFromPixel({ seriesIndex: 0 }, [event.offsetX, event.offsetY])
    const xValue = pointInGrid[0]
    // 添加参考线（使用“光标”命名）
    this.cursorLines.push({ xAxis: xValue, val: '光标' })
    // 更新图表：添加参考线
    this.updateCursorLines()
    // 自动取消勾选
    this.checkedGB = this.checkedGB.filter(val => val !== '添加光标')
    this.handlecursor() // 同步 checked 状态
  },



  updateCursorLines() {
    const cursorLine = {
      type: 'line',
      markLine: {
        silent: true,
        lineStyle: { color: '#FF0000', type: 'dotted', width: 2 },
        symbol: ['none', 'none'],
        label: {
          show: true,
          formatter: ({ data }) => `光标`,
          position: 'end',
        },
        data: this.cursorLines.map(({ xAxis, val }) => ({ xAxis, val })),
      },
    }

    // 更新图表，仅更新 series
    if (this.chartInstance) {
      this.chartInstance.setOption(
        {
          series: [
            {
              name: '数据系列',
              type: 'line',
              data: this.spectrumList.x.map((x, i) => [x, this.spectrumList.y[i]]),
              symbol: 'none',
              lineStyle: { color: '#162961', width: 1 },
              itemStyle: { color: '#162961', borderColor: '#fff', borderWidth: 1 },
              large: true,
            },
            ...this.generateSeries({
              Fr: this.Fr,
              BPFI: this.BPFI,
              BPFO: this.BPFO,
              BSF: this.BSF,
              FTF: this.FTF,
              B3P: this.B3P,
            }),
            cursorLine,
          ],
        },
        { replaceMerge: ['series'] }
      )
    }
  },



    // 更新图表数据
    updateChart(data, labels) {
      if (
        !this.chartInstance ||
        !Array.isArray(labels) ||
        !Array.isArray(data) ||
        labels.length !== data.length
      ) {
        console.error("Invalid data or labels");
        return;
      }

      const createMarkLine = (dataSource, color) => ({
        type: "line",
        markLine: {
          silent: false,
          lineStyle: { color, type: "solid", width: 2 },
          symbol: ["arrow", "none"],
          label: {
            show: true,
            position: "end",
            formatter: ({ data }) => data.val,
          },
          emphasis: {
            lineStyle: { color: "#FF6A00", width: 4 },
            label: {
              show: true,
              formatter: ({ value }) => `特征值: ${value}`,
              color: "#000",
              backgroundColor: "#FFF",
              padding: [2, 4],
              borderRadius: 3,
              fontSize: 12,
            },
          },
          data: dataSource.map(({ Xaxis, val }) => ({ xAxis: Xaxis, val })),
        },
      });

      const markLines = [
        { data: this.Fr, color: "#A633FF" },
        { data: this.BPFI, color: "#23357e" },
        { data: this.BPFO, color: "#42a0ae" },
        { data: this.BSF, color: "#008080" },
        { data: this.FTF, color: "#af254f" },
        { data: this.B3P, color: "#FFD700" },
      ].map(({ data, color }) => createMarkLine(data, color));

      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(),
            },
            myCustomTool4: {
              show: true,
              title: "光标",
              icon: `image://${require("@/assets/analyse/12.png")}`,
              onclick: () => this.Show("2"),
            },
            myCustomTool5: {
              show: true,
              title: "特征频率",
              icon: `image://${require("@/assets/analyse/13.png")}`,
              onclick: () => this.Show("3"),
            },
          },
        },
        xAxis: {
          type: "value",
          name: this.spectrumList.xaxis,
          nameLocation: "center",
          nameTextStyle: {
            fontSize: 14,
            color: "#333",
            padding: [10, 0, 0, 0],
          },
        },
        yAxis: {
          type: "value",
          name: this.spectrumList.yaxis,
          nameTextStyle: {
            fontSize: 14,
            color: "#333",
            padding: [10, 0, 0, 0],
          },
        },
        tooltip: {
          trigger: "axis",
          formatter: ([
            {
              value: [x, y],
            },
          ]) => `X: ${x}<br/>Y: ${y}`,
          axisPointer: { type: "line" },
        },
        dataZoom: [
          { type: "inside", start: 0, end: 10 },
          {
            type: "slider",
            start: 0,
            end: 10,
            handleSize: "80%",
            showDataShadow: false,
          },
        ],
        series: [
          {
            name: "数据系列",
            type: "line",
            data: labels.map((x, i) => [x, data[i]]),
            symbol: "none",
            lineStyle: { color: "#162961", width: 1 },
            itemStyle: {
              color: "#162961",
              borderColor: "#fff",
              borderWidth: 1,
            },
            large: true,
            progressive: 2000,
          },
          ...markLines,
        ],
      };

      this.chartInstance.setOption(option);
    },

    // 处理复选框变化 特征值
    handleCheckChange() {
      this.PXcheckList.forEach((item) => {
        item.checked = this.checkedValues.includes(item.val);
      });

      // 构建新的特征频率数据
      const newFeatureLines = {
        Fr: this.checkedValues.includes("Fr") ? this.spectrumList.fn_Gen : [],
        BPFI: this.checkedValues.includes("BPFI") ? this.spectrumList.BPFI : [],
        BPFO: this.checkedValues.includes("BPFO") ? this.spectrumList.BPFO : [],
        BSF: this.checkedValues.includes("BSF") ? this.spectrumList.BSF : [],
        FTF: this.checkedValues.includes("FTF") ? this.spectrumList.FTF : [],
        B3P: this.checkedValues.includes("3P")
          ? Array.isArray(this.spectrumList.B3P)
            ? this.spectrumList.B3P
            : [{ Xaxis: this.spectrumList.B3P, val: "3P" }]
          : [],
      };

      // 仅更新 `series`，避免重新渲染整个 ECharts 组件
      if (this.chartInstance) {
        this.chartInstance.setOption(
          {
            series: this.generateSeries(newFeatureLines),
          },
          { replaceMerge: ["series"] }
        );
      }
    },

    generateSeries(featureLines) {
      const createMarkLine = (dataSource, color) => ({
        type: "line",
        markLine: {
          silent: false,
          lineStyle: { color, type: "dashed", width:1 },
          symbol: ["arrow", "none"],
          label: {
            show: true,
            position: "end",
            formatter: ({ data }) => data.val,
          },
          emphasis: {
            lineStyle: { color: "#FF6A00", width: 2 },
            label: {
              show: true,
              formatter: ({ value }) => `特征值: ${value}`,
              color: "#000",
            },
          },
          data: dataSource.map(({ Xaxis, val }) => ({ xAxis: Xaxis, val })),
        },
      });

      const markLines = [
        { data: featureLines.Fr, color: "#A633FF" },
        { data: featureLines.BPFI, color: "#23357e" },
        { data: featureLines.BPFO, color: "#42a0ae" },
        { data: featureLines.BSF, color: "#008080" },
        { data: featureLines.FTF, color: "#af254f" },
        { data: featureLines.B3P, color: "#FFD700" },
      ].map(({ data, color }) => createMarkLine(data, color));

      return [
        {
          name: "数据系列",
          type: "line",
          data: this.spectrumList.x.map((x, i) => [x, this.spectrumList.y[i]]),
          symbol: "none",
          lineStyle: { color: "#162961", width: 1 },
          itemStyle: { color: "#162961", borderColor: "#fff", borderWidth: 1 },
          large: true,
        },
        ...markLines,
      ];
    },

    // 处理复选框变化 光标
    handlecursor(){
      this.GBcheckList.forEach((item) => {
        item.checked = this.checkedGB.includes(item.val);
        console.log(  item.checked ,"item.checked");
      });

    },

    getTime() {
      this.$emit("handleLoading", null, true, this.activeIndex);
      const params = {
        ids: this.ids,
        windCode: this.windCode,
        analysisType: "frequency",
      };
      axios
        .post("/WJapi/analysis/frequency", params)
        .then((res) => {
          console.log(res, "频谱图数据");
          this.spectrumList = { ...JSON.parse(res.data) };
          console.log(this.spectrumList, "频谱图数据1");
          const XrmsValue = this.spectrumList?.Xrms;
          // 通过 $emit 传递 XrmsValue 给父组件
          this.$emit("updateXrms", XrmsValue);
          this.PXcheckList.forEach((item) => {
            if (item.checked) {
              switch (item.val) {
                case "Fr":
                  this.Fr = this.spectrumList.fn_Gen;
                  break;
                case "BPFI":
                  this.BPFI = this.spectrumList.BPFI;
                  break;
                case "BPFO":
                  this.BPFO = this.spectrumList.BPFO;
                  break;
                case "BSF":
                  this.BSF = this.spectrumList.BSF;
                  break;
                case "FTF":
                  this.FTF = this.spectrumList.FTF;
                  break;
                case "3P":
                  this.B3P = Array.isArray(this.spectrumList.B3P)
                    ? this.spectrumList.B3P
                    : [{ Xaxis: this.spectrumList.B3P, val: "3P" }];
                  break;
                default:
                  break;
              }
            }
          });
        })
        .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(value) {
      const stateMap = {
        1: { TZshow: true, BGshow: false, PXshow: false },
        2: { TZshow: false, BGshow: true, PXshow: false },
        3: { TZshow: false, BGshow: false, PXshow: true },
      };

      if (stateMap[value]) {
        // Toggle the state for the given value
        this.TZshow = value === "1" ? !this.TZshow : false;
        this.BGshow = value === "2" ? !this.BGshow : false;
        this.PXshow = value === "3" ? !this.PXshow : false;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.line-chart {
  width: 100%;
  height: 280px;
}

.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>
