<template>
  <div class="chartsContent">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <h4 style="color: black; font-size: 16px; font-weight: 700">
          测量原始图
        </h4>
        <!-- <div style="font-size: 12px; color: #666">
          测点路径：XX公司\XX电场\XX风机 &nbsp; 采样时间：2024/3/10 12:23:33
        </div> -->
      </div>
      <div class="line-chart" ref="chart" style="width: 100%"></div>
    </el-card>
  </div>
</template>

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

export default {
  props: {
    key: {
      type: String,
      default: "",
    },
    type: {
      default: "",
    },
    LeafRootOutlineData: {
      // 叶根轮廓拟合图数据
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      currentIndex: 0, // 默认索引
      tableData: [], // 数据
      originalChartStyle: {}, // 用于存储原始样式
    };
  },
  mounted() {
    this.initializeChart();
    // 监听键盘事件
    window.addEventListener("keydown", this.handleKeyDown);
  },
  destroyed() {
    // 移除键盘事件监听
    window.removeEventListener("keydown", this.handleKeyDown);
  },
  methods: {
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
    // 初始化图表
    initializeChart() {
      this.$nextTick(() => {
        const chartDom = this.$refs.chart;
        this.chartInstance = echarts.init(chartDom);

        if (this.LeafRootOutlineData?.blade_root?.ydata?.length > 0) {
          this.updateChart();
        }
        // 保存初始样式
        this.originalChartStyle = {
          width: chartDom.style.width,
          height: chartDom.style.height,
          backgroundColor: chartDom.style.backgroundColor,
        };
      });
    },
    // 更新图表数据
    updateChart() {
      const option = {
        grid: {
          left: 80,
          bottom: 90,
          // right: 100,
        },
        toolbox: {
          feature: {
            dataZoom: { yAxisIndex: "none" },
            restore: {},
            saveAsImage: {},
            // myCustomTool: {
            //   show: true,
            //   title: "上一条",
            //   icon: `image://${new URL(
            //     "@/assets/analyse/08.png",
            //     import.meta.url
            //   )}`,

            //   onclick: () => this.previousRow(),
            // },
            // myCustomTool2: {
            //   show: true,
            //   title: "下一条",
            //   icon: `image://${new URL(
            //     "@/assets/analyse/09.png",
            //     import.meta.url
            //   )}`,
            //   // icon: `image://${require("@/assets/analyse/09.png")}`,
            //   onclick: () => this.nextRow(),
            // },
            myCustomTool3: {
              show: true,
              title: "全屏",
              icon: `image://${new URL(
                "@/assets/analyse/fullScreen.png",
                import.meta.url
              )}`,
              // icon: `image://${require("@/assets/analyse/fullScreen.png")}`,
              onclick: () => this.fullScreen(),
            },
            myCustomTool4: {
              show: true,
              title: "退出全屏",
              icon: `image://${new URL(
                "@/assets/analyse/exitFullScreen.png",
                import.meta.url
              )}`,
              // icon: `image://${require("@/assets/analyse/exitFullScreen.png")}`, // 替换为你自己的图标路径
              onclick: () => this.exitFullScreen(),
            },
          },
        },
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 1,
          },
          {
            start: 0,
            end: 1,
          },
        ],
        color: ["#46AFC5", "#1A285E"],
        xAxis: {
          type: "category",
          boundaryGap: false,
          name: "时间(s)",
          nameTextStyle: {
            // fontSize: 14, // 字体大小
            fontWeight: "bold", // 字体加粗
            // color: "#333", // 字体颜色
            padding: [20, 0, 0, 0], // 调整名称与 X 轴的距离
          },
          nameLocation: "middle",
          data: this.LeafRootOutlineData?.blade_root?.xdata.map((item) =>
            item.toFixed(2)
          ),
        },
        yAxis: {
          type: "value",
          name: "距离(m)",
          nameLocation: "middle",
          nameTextStyle: {
            // fontSize: 14, // 字体大小
            fontWeight: "bold", // 字体加粗
            // color: "#333", // 字体颜色
            padding: [0, 0, 40, 0], // 调整 padding
          },
          min:
            Math.min(
              ...this.LeafRootOutlineData.blade_root.ydata,
              ...this.LeafRootOutlineData.blade_tip.ydata
            ) - 1,
          max:
            Math.max(
              ...this.LeafRootOutlineData.blade_root.ydata.map((item) =>
                item.toFixed(4)
              ),
              ...this.LeafRootOutlineData.blade_tip.ydata.map((item) =>
                item.toFixed(4)
              )
            ) + 1,
          // boundaryGap: [0, "100%"],
          splitNumber: 10, // 指定网格线的数量
        },
        tooltip: {
          trigger: "axis",
          position: function (pt) {
            return [pt[0], "10%"];
          },
        },
        legend: {
          data: ["叶根轮廓", "叶尖轮廓"],
          left: 0,
        },
        series: [
          {
            name: "叶根轮廓",
            type: "line",
            // symbol: "none",
            // sampling: "lttb",
            showSymbol: false,

            data: this.LeafRootOutlineData.blade_root.ydata.map((item) =>
              item.toFixed(4)
            ),
            smooth: true, // 平滑曲线
          },
          {
            name: "叶尖轮廓",
            type: "line",
            showSymbol: false,

            data: this.LeafRootOutlineData.blade_tip.ydata.map((item) => item),
            smooth: true, // 平滑曲线
          },
        ],
      };
      this.chartInstance.setOption(option);
      this.chartInstance.resize();
      // ✅ 安全绑定 resize
      window.addEventListener("resize", this.handleResize);
    },
    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;
      if (screenfull.isEnabled) {
        screenfull.toggle(chartDom);
      }
    },
    fullScreen() {
      const chartDom = this.$refs.chart;
      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;
      if (screenfull.isEnabled) {
        screenfull.exit();
        // 监听全屏变化
        screenfull.on("change", this.handleFullScreenChange);
      }
    },
    // 处理全屏变化的回调
    handleFullScreenChange() {
      const chartDom = this.$refs.chart;
      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%;
  position: relative;
}
.line-chart {
  width: 100%;
  height: 400px;
  background-color: #fff;
  position: relative;
}
.line-chart > div {
  width: 100%;
  height: 400px;
}
.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>
