<!--
 * @Author: your name
 * @Date: 2025-06-04 16:41:24
 * @LastEditTime: 2025-06-26 10:55:26
 * @LastEditors: milo-MacBook-Pro.local
 * @Description: In User Settings Edit
 * @FilePath: /jg/src/views/laserRangeFinder/components/scatterChart.vue
-->
<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>
      <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: {}, // 用于存储原始样式
    };
  },
  watch: {
    LeafRootOutlineData: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.initializeChart();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.initializeChart();
    window.addEventListener("keydown", this.handleKeyDown);
    // window.addEventListener("resize", this.chartInstance.resize);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.chartInstance.resize);
    window.removeEventListener("keydown", this.handleKeyDown);
  },
  methods: {
    // 初始化图表
    initializeChart() {
      this.$nextTick(() => {
        const chartDom = this.$refs.chart;
        this.chartInstance = echarts.init(chartDom);
        // if (this.LeafRootOutlineData?.firs_blade?.ydata?.length > 0) {
        //   this.updateChart();
        // }
        this.updateChart();
        // 保存初始样式
        this.originalChartStyle = {
          width: chartDom.style.width,
          height: chartDom.style.height,
          backgroundColor: chartDom.style.backgroundColor,
        };
      });
    },
    // 更新图表数据
    updateChart() {
      console.log("运行散点图");
      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: 100,
          },
          {
            start: 0,
            end: 100,
          },
        ],
        color: ["#46AFC5", "#1A285E", "#BC8F8F"], // 设置颜色
        xAxis: {
          type: "value",
          boundaryGap: false,
          name: "转速(r/min)",
          nameTextStyle: {
            // fontSize: 14, // 字体大小
            fontWeight: "bold", // 字体加粗
            // color: "#333", // 字体颜色
            padding: [20, 0, 0, 0], // 调整名称与 X 轴的距离
          },
          min: Math.floor(
            Math.min(
              ...this.LeafRootOutlineData.first_blade.xdata,
              ...this.LeafRootOutlineData.second_blade.xdata,
              ...this.LeafRootOutlineData.third_blade.xdata
            )
          ),
          max: Math.ceil(
            Math.max(
              ...this.LeafRootOutlineData.first_blade.xdata,
              ...this.LeafRootOutlineData.second_blade.xdata,
              ...this.LeafRootOutlineData.third_blade.xdata
            )
          ),
          nameLocation: "middle",
        },
        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.first_blade.ydata,
              ...this.LeafRootOutlineData.second_blade.ydata,
              ...this.LeafRootOutlineData.third_blade.ydata
            ) - 0.1
          ).toFixed(1),
          max: (
            Math.max(
              ...this.LeafRootOutlineData.first_blade.ydata,
              ...this.LeafRootOutlineData.second_blade.ydata,
              ...this.LeafRootOutlineData.third_blade.ydata
            ) + 0.1
          ).toFixed(1),
          boundaryGap: [0, "100%"],
          splitNumber: 10, // 指定网格线的数量
        },
        tooltip: {
          trigger: "axis",
          position: function (pt) {
            return [pt[0], "10%"];
          },
        },

        legend: {
          data: ["叶片1净空", "叶片2净空", "叶片3净空"],
          left: 0,
        },
        series: [
          {
            symbolSize: 5,
            name: "叶片1净空",
            data: this.LeafRootOutlineData?.first_blade.xdata.map(
              (item, ind) => [
                Number(item.toFixed(2)),
                this.LeafRootOutlineData?.first_blade.ydata[ind],
              ]
            ),
            type: "scatter",
          },
          {
            symbolSize: 5,
            name: "叶片2净空",
            data: this.LeafRootOutlineData?.second_blade.xdata.map(
              (item, ind) => [
                Number(item.toFixed(2)),
                this.LeafRootOutlineData?.second_blade.ydata[ind],
              ]
            ),
            type: "scatter",
          },
          {
            symbolSize: 5,
            name: "叶片3净空",
            data: this.LeafRootOutlineData?.third_blade.xdata.map(
              (item, ind) => [
                Number(item.toFixed(2)),
                this.LeafRootOutlineData?.third_blade.ydata[ind],
              ]
            ),
            type: "scatter",
          },
        ],
      };
      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);
      }
    },
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
  },
};
</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>
