<template>
  <div class="chartsContent">
    <el-card class="boxchart" shadow="never" v-if="type === 'LeafRootOutline'">
      <div slot="header" class="clearfix">
        <h4 style="color: black; font-size: 16px; font-weight: 700">
          叶根轮廓拟合图
        </h4>
        <div style="font-size: 12px; color: #666">
          <!-- 江西大唐国际新能源有限公司\金华山风电场\01#风机 2024/3/1 11:00:00 -->
        </div>
      </div>
      <div class="line-chart" :ref="`chart${keys}`"></div>
    </el-card>
    <el-card
      class="boxchart"
      shadow="never"
      v-else-if="type === 'LeafTipProfile'"
    >
      <div slot="header" class="clearfix">
        <h4 style="color: black; font-size: 16px; font-weight: 700">
          叶尖轮廓拟合图
        </h4>
        <!-- <div style="font-size: 12px; color: #666">
          江西大唐国际新能源有限公司\金华山风电场\01#风机 2024/3/1 11:00:00
        </div> -->
      </div>
      <div class="line-chart" :ref="`chart${keys}`" style="width: 100%"></div>
    </el-card>
  </div>
</template>

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

export default {
  props: {
    keys: {
      type: String,
      default: "",
    },
    type: {
      default: "",
    },
    LeafRootOutlineData: {
      // 叶根轮廓拟合图数据
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      currentIndex: 0, // 默认索引
      tableData: [], // 数据
      originalChartStyle: {}, // 用于存储原始样式
      // 控制标注的显示/隐藏
      markPointVisible: false,
      markLineVisible: false,
    };
  },
  watch: {
    LeafRootOutlineData: {
      handler(newVal, oldVal) {
        console.log("newVal, oldVal LeafRootOutlineData", newVal, oldVal);
        this.updateChart(); // 更新图表
      },
      deep: true, // 深度监听
      immediate: true, // 立即触发
    },
    // 监听标注的显示状态变化
    markPointVisible(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.updateChart();
      }
    },
    markLineVisible(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.updateChart(); // 更新图表
      }
    },
  },
  mounted() {
    this.initializeChart();
    // 监听键盘事件
    window.addEventListener("keydown", this.handleKeyDown);
  },
  destroyed() {
    // 移除键盘事件监听
    window.removeEventListener("keydown", this.handleKeyDown);
    if (this.chartInstance) {
      this.chartInstance.dispose(); // 销毁图表实例
      this.chartInstance = null;
    }
  },
  methods: {
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
    // 初始化图表
    initializeChart() {
      this.$nextTick(() => {
        const chartDom = this.$refs[`chart${this.keys}`];
        this.chartInstance = echarts.init(chartDom);

        if (this.LeafRootOutlineData?.first_blade?.ydata?.length > 0) {
          this.updateChart();
          // 保存初始样式
          this.originalChartStyle = {
            width: chartDom.style.width,
            height: chartDom.style.height,
            backgroundColor: chartDom.style.backgroundColor,
          };
        }
      });
    },
    updateChart() {
      if (!this.chartInstance) {
        console.warn("图表实例未初始化，无法更新图表");
        this.initializeChart();
        return;
      }

      // 1) 原始数据 → 四舍五入到4位（保持数值类型）
      const xRaw = (this.LeafRootOutlineData?.first_blade?.xdata || []).map(
        (v) => Number(Number(v).toFixed(4))
      );

      const y1Raw = this.LeafRootOutlineData.first_blade.ydata.map((v) =>
        Number(Number(v).toFixed(4))
      );
      const y2Raw = this.LeafRootOutlineData.second_blade.ydata.map((v) =>
        Number(Number(v).toFixed(4))
      );
      const y3Raw = this.LeafRootOutlineData.third_blade.ydata.map((v) =>
        Number(Number(v).toFixed(4))
      );
      const yAvgRaw = this.LeafRootOutlineData.avg_blade.ydata.map((v) =>
        Number(Number(v).toFixed(4))
      );

      // 2) 计算 minValue（按你的旧规则：三条曲线最小值 - 0.1）
      const minYAmongThree = Math.min(
        Math.min(...y1Raw),
        Math.min(...y2Raw),
        Math.min(...y3Raw)
      );
      const minValue = Number((minYAmongThree - 0.1).toFixed(4));

      // 3) 归一化 Y：y' = y - minValue，并统一保留4位
      const y1 = y1Raw.map((v) => Number((v - minValue).toFixed(4)));
      const y2 = y2Raw.map((v) => Number((v - minValue).toFixed(4)));
      const y3 = y3Raw.map((v) => Number((v - minValue).toFixed(4)));
      // const yAvg = yAvgRaw.map((v) => Number((v - minValue).toFixed(4)));

      // 4) 基于“归一化后的数据”计算等比例范围
      const allY = [...y1, ...y2, ...y3];

      const minX = Math.min(...xRaw);
      const maxX = Math.max(...xRaw);
      const xRange = Number((maxX - minX).toFixed(4));

      const maxY = Math.max(...allY); // 归一化后理论上 ≥ 0.1
      const { clientWidth: w, clientHeight: h } = this.chartInstance.getDom();
      const aspectRatio = w / h;

      // 让单位像素一致：目标 yRange = xRange / (w/h)
      const targetYRange = Number((xRange / aspectRatio).toFixed(4));

      // y 轴从 0 起步；若数据超过目标范围，用数据的范围
      const yMin = 0;
      const yMax = Number(Math.max(maxY, targetYRange).toFixed(4));
      const xLabels = xRaw.map((v) => v.toFixed(1));
      const yLabels = Array.from(
        new Set([...y1, ...y2, ...y3].map((v) => v.toFixed(1)))
      );
      const option = {
        grid: { left: 80, right: 40, top: 40, bottom: 60 },
        color: ["#46AFC5", "#3286BB", "#3856A0", "#1A285E"],
        toolbox: {
          feature: {
            dataZoom: { yAxisIndex: "none" },
            restore: {},
            saveAsImage: {},
            myCustomTool1: {
              show: true,
              title: "标注",
              icon: `image://${new URL(
                "@/assets/analyse/mark.png",
                import.meta.url
              )}`,
              onclick: () => this.WhetherToDisplay(),
            },
            myCustomTool2: {
              show: true,
              title: "全屏",
              icon: `image://${new URL(
                "@/assets/analyse/fullScreen.png",
                import.meta.url
              )}`,
              onclick: () => this.fullScreen(),
            },
            myCustomTool3: {
              show: true,
              title: "退出全屏",
              icon: `image://${new URL(
                "@/assets/analyse/exitFullScreen.png",
                import.meta.url
              )}`,
              onclick: () => this.exitFullScreen(),
            },
          },
        },
        xAxis: {
          type: "value",
          name: "距离(m)",
          nameLocation: "middle",
          nameTextStyle: { fontWeight: "bold", padding: [20, 0, 0, 0] },
          min: 0,
          // max: maxX,
          splitNumber: 15,
          data: [...new Set(xLabels)],

          splitLine: { show: true, lineStyle: { color: "rgb(220,220,220)" } },
        },
        yAxis: {
          type: "value",
          name: "距离(m)",
          nameLocation: "middle",
          nameTextStyle: { fontWeight: "bold", padding: [0, 0, 40, 0] },
          min: yMin,
          // max: yMax,
          splitNumber: [...new Set(yLabels)].length,
          data: [...new Set(yLabels)],
        },
        tooltip: {
          trigger: "axis",
          valueFormatter: (v) => (typeof v === "number" ? v.toFixed(4) : v),
          position: (pt) => [pt[0], "10%"],
        },
        legend: {
          data:
            this.keys === "blade_tip"
              ? ["叶尖1轮廓", "叶尖2轮廓", "叶尖3轮廓"]
              : ["叶根1轮廓", "叶根2轮廓", "叶根3轮廓"],
          left: 0,
        },
        series: [
          {
            name: this.keys === "blade_tip" ? "叶尖1轮廓" : "叶根1轮廓",
            type: "line",
            showSymbol: false,
            data: xRaw.map((x, i) => [x, y1[i]]),
            smooth: true,
          },
          {
            name: this.keys === "blade_tip" ? "叶尖2轮廓" : "叶根2轮廓",
            type: "line",
            showSymbol: false,
            data: xRaw.map((x, i) => [x, y2[i]]),
            smooth: true,
          },
          {
            name: this.keys === "blade_tip" ? "叶尖3轮廓" : "叶根3轮廓",
            type: "line",
            showSymbol: false,
            data: xRaw.map((x, i) => [x, y3[i]]),
            smooth: true,
          },
          // {
          //   name: "平均轮廓",
          //   type: "line",
          //   showSymbol: false,
          //   data: xRaw.map((x, i) => [x, yAvg[i]]),
          //   smooth: true,
          // },
        ],
      };

      this.chartInstance.setOption(option, true);
      // ======== 动态高度计算 ========
      this.$nextTick(() => {
        // 获取 X 轴和 Y 轴的最大刻度文本长度

        const maxYLabelLen = [...new Set(yLabels)].length;

        //   // 设置 DOM 高度
        const chartDom = this.$refs[`chart${this.keys}`];

        const chartWidth = chartDom.clientWidth;
        const grid =
          option.grid && option.grid[0]
            ? option.grid[0]
            : { left: 0, right: 0 };
        const xAxisWidth =
          chartWidth - (parseInt(grid.left) || 0) - (parseInt(grid.right) || 0);
        const xAxisWidthPerLabel = xAxisWidth / 15;

        //   // 默认高度
        let baseHeight = 400;
        //   // 如果 y 轴的刻度文本比 x 轴长，则增加高度
        if (maxYLabelLen > [...new Set(xLabels)].length) {
          // const diff = maxYLabelLen - maxXLabelLen;
          baseHeight = maxYLabelLen * xAxisWidthPerLabel;
        } else if (maxYLabelLen < [...new Set(xLabels)].length) {
          const xAxisWidthPerLabelAll =
            xAxisWidth / [...new Set(xLabels)].length;
          baseHeight = maxYLabelLen * xAxisWidthPerLabelAll;
        }
        chartDom.style.height = baseHeight + "px";
        console.log(
          "每个刻度线的距离",
          xAxisWidthPerLabel,
          `chart${this.keys}`,
          baseHeight
        );
        //   // 重新调整 ECharts 大小
        this.chartInstance.resize();
      });
      // 防止重复绑定 resize 事件
      if (this._onResizeEqualScale) {
        window.removeEventListener("resize", this._onResizeEqualScale);
      }
      this._onResizeEqualScale = () => this.updateChart();
      window.addEventListener("resize", this._onResizeEqualScale);
    },
    // 标注是否显示
    WhetherToDisplay() {
      // 切换显示状态
      this.markPointVisible = !this.markPointVisible;
      this.markLineVisible = !this.markLineVisible;
    },
    previousRow() {
      let newIndex =
        this.currentIndex > 0
          ? this.currentIndex - 1
          : this.tableData.length - 1;
      this.$emit("update:currentIndex", newIndex);
    },
    nextRow() {
      console.log("下一条");
      let newIndex =
        this.currentIndex < this.tableData.length - 1
          ? this.currentIndex + 1
          : 0;
      this.$emit("update:currentIndex", newIndex);
    },
    toggleFullScreen() {
      const chartDom = this.$refs[`chart${this.keys}`];
      if (screenfull.isEnabled) {
        screenfull.toggle(chartDom);
      }
    },
    fullScreen() {
      const chartDom = this.$refs[`chart${this.keys}`];
      if (screenfull.isEnabled) {
        // 设置全屏样式
        chartDom.style.position = "absolute";
        chartDom.style.top = 0;
        chartDom.style.left = 0;
        chartDom.style.width = "100vw";
        chartDom.style.height = "100vh";
        chartDom.style.backgroundColor = "#ffffff";

        // 进入全屏
        screenfull.request(chartDom);
        this.chartInstance.resize();

        // 监听全屏变化
        screenfull.on("change", this.handleFullScreenChange);
      }
    },
    exitFullScreen() {
      const chartDom = this.$refs[`chart${this.keys}`];
      if (screenfull.isEnabled) {
        screenfull.exit();
        // 监听全屏变化
        screenfull.on("change", this.handleFullScreenChange);
      }
    },
    // 处理全屏变化的回调
    handleFullScreenChange() {
      const chartDom = this.$refs[`chart${this.keys}`];
      if (!screenfull.isFullscreen) {
        // 退出全屏时恢复样式
        chartDom.style.position = this.originalChartStyle.position || "";
        chartDom.style.top = this.originalChartStyle.top || "";
        chartDom.style.left = this.originalChartStyle.left || "";
        chartDom.style.width = this.originalChartStyle.width || "100%";
        chartDom.style.height = this.originalChartStyle.height || "400px";
        chartDom.style.backgroundColor =
          this.originalChartStyle.backgroundColor || "#fff";

        // 调整图表尺寸
        this.chartInstance.resize();

        // 可选：移除事件监听（如果不再需要）
        screenfull.off("change", this.handleFullScreenChange);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-card__body {
  width: 100%;
  // height: 250px;
  position: relative;
}
.chartsContent {
  .boxchart {
    overflow: hidden !important;
    :deep(.el-card__body) {
      width: 100%;
      overflow: hidden !important;
    }
  }
}

.line-chart {
  width: 100%;
  // height: 400px;
  background-color: #fff;
  position: relative;
}
.line-chart > div {
  width: 100%;
  height: 100%;
}
.eigenvalue {
  position: absolute;
  top: 0;
  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>
