<template>
  <div>
    <!-- 配色方案选择和图表类型切换 -->
    <div style="display: flex; align-items: center; padding-top: 20px">
      <div style="margin-right: 20px; display: flex; align-items: center">
        <el-select
          size="small"
          v-model="color1"
          @change="updateChartColor"
          placeholder="选择配色方案"
          style="width: 200px"
        >
          <el-option
            v-for="(scheme, index) in colorSchemes"
            :key="index"
            :label="scheme.label"
            :value="scheme.colors"
          >
            <span
              v-for="color in scheme.colors.slice(0, 8)"
              :style="{
                background: color,
                width: '20px',
                height: '20px',
                display: 'inline-block',
              }"
            ></span>
          </el-option>
        </el-select>
      </div>
      <!-- 点大小控制 -->
      <div style="display: flex; align-items: center">
        <el-slider
          v-model="pointSize"
          :min="1"
          :max="15"
          :step="1"
          label="点的大小"
          show-stops
          style="width: 150px"
          @change="updateChartColor"
        ></el-slider>
      </div>
    </div>

    <!-- 图表展示区域 -->
    <div style="height: 600px">
      <div
        v-loading="loading"
        :id="`plotly-3d-chart-` + index"
        ref="plotlyChart"
        style="height: 600px; background-color: #e5ecf6"
      >
        <el-empty v-if="isError" description="请求失败"></el-empty>
      </div>
    </div>
  </div>
</template>

<script>
import Plotly from "plotly.js-dist";
import axios from "axios";
import { myMixin } from "@/mixins/chartRequestMixin";
import { colorSchemes } from "@/views/overview/js/colors";
import { mapState } from "vuex";
export default {
  props: {
    fileAddr: {
      default: "",
      type: String,
    },
    index: {
      default: "",
      type: String,
    },
    setUpImgData: {
      default: () => [],
      type: Array,
    },
  },
  data() {
    return {
      color1: [], // 默认颜色
      // 配色方案列表（每个方案是一个颜色数组）
      colorSchemes: colorSchemes,
      chartData: {},
      chartType: "scatter", // 当前图表类型（默认是散点图）
      pointSize: 1, // 默认点大小
    };
  },
  mixins: [myMixin],
  computed: {
    ...mapState("themes", {
      themeColor: "themeColor",
    }),
  },
  watch: {
    themeColor: {
      handler(newval) {
        if (newval.length === 0) {
          this.color1 = this.colorSchemes[0].colors;
        } else {
          this.color1 = newval;
        }
        this.updateChartColor();
      },
      deep: true,
    },
    setUpImgData: {
      handler(newType) {
        this.renderChart();
      },
      deep: true,
    },
  },
  async mounted() {
    this.$nextTick(() => {
      this.color1 = this.colorSchemes[0].colors;
      this.getData();
    });
  },
  methods: {
    async getData() {
      if (this.fileAddr !== "") {
        try {
          this.loading = true;
          this.cancelToken = axios.CancelToken.source();

          const resultChartsData = await axios.get(this.fileAddr, {
            cancelToken: this.cancelToken.token,
          });
          if (typeof resultChartsData.data === "string") {
            let dataString = resultChartsData.data;
            dataString = dataString.trim(); // 去除前后空格
            dataString = dataString.replace(/Infinity/g, '"Infinity"'); // 替换 Infinity 为 "Infinity"
            try {
              const parsedData = JSON.parse(dataString);
              this.chartData = parsedData;
            } catch (error) {
              console.error("JSON 解析失败:", error);
            }
          } else {
            this.chartData = resultChartsData.data;
          }
          this.renderChart();
          this.isError = false;
          this.loading = false;
        } catch (error) {
          this.isError = true;
          this.loading = false;
        }
      }
    },
    // 更新配色方案
    updateChartColor() {
      this.renderChart(); // 当配色方案或点大小发生变化时重新渲染图表
    },
    // 切换图表类型
    setChartType(type) {
      this.chartType = type;
      this.renderChart(); // 切换图表类型时重新渲染图表
    },

    // 获取配色选项样式
    getOptionStyle(scheme) {
      return {
        background: `linear-gradient(to right, ${scheme
          .slice(0, 8)
          .join(", ")})`,
        color: "#fff",
        height: "30px",
        lineHeight: "30px",
        borderRadius: "0px",
      };
    },

    renderChart() {
      const uniqueColors = [...new Set(this.chartData.data[0].color)];
      if (!this.color1) {
        this.color1 = this.colorSchemes[0].colors;
      }
      const traces = uniqueColors.map((color, idx) => {
        const colorData = this.chartData.data[0].color.map((c) =>
          c === color ? 1 : 0
        );

        const trace = {
          x: this.chartData.data[0].xData.filter((_, i) => colorData[i] === 1),
          y: this.chartData.data[0].yData.filter((_, i) => colorData[i] === 1),
          z: this.chartData.data[0].zData.filter((_, i) => colorData[i] === 1),
          mode: this.chartType === "scatter" ? "markers" : "lines", // 根据选择的图表类型来设置模式
          type: "scatter3d",
          marker: {
            size: this.pointSize, // 使用动态点大小
            color: this.color1[idx], // 使用配色方案
            colorscale: "YlGnBu",
          },
          name: ` ${color}`,
          legendgroup: `group-${idx}`,
          hovertemplate:
            `${this.chartData.xaixs}:` +
            ` %{x} <br> ` +
            `${this.chartData.yaixs}:` +
            "%{y} <br>" +
            `${this.chartData.zaixs}:` +
            "%{z} <extra></extra>",
        };
        return trace;
      });
      const yData = [...new Set(this.chartData.data[0].yData)]; // 获取唯一的yData
      const totalTicks = 10; // 想要显示的刻度数量

      // 保证第一个和最后一个刻度
      const firstValue = yData[0];
      const lastValue = yData[yData.length - 1];

      // 计算中间部分的刻度值
      const interval = Math.floor((yData.length - 1) / 8); // 总长度减去最初和最后一个，计算间隔

      // 选择需要展示的刻度
      const tickvals = [firstValue]; // 先将第一个值放入刻度数组

      for (let i = 1; i < totalTicks - 1; i++) {
        const index = i * interval;
        tickvals.push(yData[index]);
      }

      tickvals.push(lastValue); // 最后将最后一个值放入刻度数组

      const ticktext = tickvals;
      const layout = {
        title: {
          text: this.chartData.data[0].title,
          font: {
            size: 16, // 设置标题字体大小（默认 16）
            weight: "bold",
          },
        },
        scene: {
          xaxis: {
            title: this.chartData.xaixs,
            gridcolor: "rgb(255,255,255)",
            tickcolor: "rgb(255,255,255)",
            backgroundcolor: "#e0e7f1",
            showbackground: true,
            // linewidth: 2, // 轴线宽度
            linecolor: "black", // 轴线颜色
            ticks: "outside", // 设置刻度线在轴线外
            fixedrange: true, // 防止缩放
            // tickwidth: 2,
            tickcolor: "black",
            tickangle: -10,
          },
          yaxis: {
            title: this.chartData.yaixs,
            type: "category", // 让 Y 轴按类别均匀分布
            categoryorder: "array", // 自定义顺序，确保间隔均匀
            categoryarray: [...new Set(this.chartData.data[0].yData)], // 以原始数据顺序排序
            tickvals: tickvals,
            ticktext: ticktext,
            gridcolor: "rgb(255,255,255)",
            tickcolor: "rgb(255,255,255)",
            backgroundcolor: "#e0e7f1",
            showbackground: true,
            // linewidth: 2, // 轴线宽度
            linecolor: "black", // 轴线颜色
            ticks: "outside", // 设置刻度线在轴线外
            // tickwidth: 2,
            tickcolor: "black",
            tickangle: 25,
          },
          zaxis: {
            title: this.chartData.zaixs,
            gridcolor: "rgb(255,255,255)",
            tickcolor: "rgb(255,255,255)",
            backgroundcolor: "#e0e7f1",
            showbackground: true,
            fixedrange: true, // 防止缩放
            // linewidth: 2, // 轴线宽度
            linecolor: "black", // 轴线颜色
            ticks: "outside", // 设置刻度线在轴线外
            // tickwidth: 2,
            tickcolor: "black",
            tickangle: -90,
          },
          aspectratio: {
            x: 2.2,
            y: 1.7,
            z: 1,
          },
          plot_bgcolor: "#e5ecf6",
          gridcolor: "#fff",
          bgcolor: "#e5ecf6", // 设置背景颜色
          camera: {
            up: {
              x: 0.200292643688136,
              y: 0.2488259353493132,
              z: 0.947612004346693,
            },
            center: {
              x: -0.052807476121180814,
              y: 0.02451796399554085,
              z: -0.022911006648570736,
            },
            eye: {
              x: -2.126379643342493,
              y: -2.551422475965373,
              z: 1.0917667684145647,
            },
            projection: {
              type: "orthographic",
            },
          },
        },
        margin: { t: 50, b: 50, l: 50, r: 50 },
        staticPlot: false,
        showlegend: true,
        legend: {
          itemsizing: "constant", // ✅ 统一图例 marker 大小
          font: {
            size: 12,
          },
          marker: {
            size: 10, // 图例中点的大小
          },
        },
      };
      const config = {
        modeBarButtonsToAdd: [
          {
            name: "还原", // 自定义按钮
            icon: Plotly.Icons.home,
            click: () => this.resetCamera(),
          },
        ],
        modeBarButtonsToRemove: [
          "sendDataToCloud",
          "autoScale2d",
          "hoverClosest3d",
          "resetCameraLastSave3d",
          "resetCameraDefault3d",
        ],
        displaylogo: false, // 可选：隐藏 Plotly logo
      };
      // 获取x轴和y轴的设置
      const getChartSetUp = (axisTitle) => {
        return this.setUpImgData.find((item) => item.text.includes(axisTitle));
      };

      // 更新x轴和y轴的范围与步长
      const xChartSetUp = getChartSetUp(layout.scene.xaxis.title);
      if (xChartSetUp) {
        layout.scene.xaxis.dtick = xChartSetUp.dtick;
        layout.scene.xaxis.range = [xChartSetUp.min, xChartSetUp.max];
      }
      const yChartSetUp = getChartSetUp(layout.scene.yaxis.title);
      if (yChartSetUp) {
        layout.scene.yaxis.dtick = yChartSetUp.dtick;
        layout.scene.yaxis.range = [yChartSetUp.min, yChartSetUp.max];
      }
      const zChartSetUp = getChartSetUp(layout.scene.zaxis.title);
      if (zChartSetUp) {
        layout.scene.zaxis.dtick = zChartSetUp.dtick;
        layout.scene.zaxis.range = [zChartSetUp.min, zChartSetUp.max];
      }

      try {
        // 假设这里是 WebGL 的相关初始化代码
        Plotly.react(`plotly-3d-chart-` + this.index, traces, layout).catch(
          (err) => {
            console.error("WebGL 错误: ", err);
            // 你可以根据错误类型做更多处理
            if (err.message.includes("shaderSource")) {
              // alert("着色器编译失败！");
            }
          }
        );
        // 监听图表的 relayout 事件，获取并输出相机视角
        const plotElement = document.getElementById(
          `plotly-3d-chart-` + this.index
        );

        plotElement.on("plotly_relayout", function (eventData) {
          // 在每次布局变更时，打印当前相机视角
          if (eventData["scene.camera"]) {
            console.log(
              "当前相机视角:",
              eventData["scene.camera"],
              eventData["scene.aspectratio"]
            );
          }
        });
      } catch (e) {
        console.error("捕获到 WebGL 错误:", e);
        // alert("图表渲染失败！");
      }
      // Plotly.newPlot(`plotly-3d-chart-` + this.index, traces, layout);
    },
    resetCamera() {
      Plotly.relayout(`plotly-3d-chart-` + this.index, {
        "scene.camera": {
          up: {
            x: 0.200292643688136,
            y: 0.2488259353493132,
            z: 0.947612004346693,
          },
          center: {
            x: -0.052807476121180814,
            y: 0.02451796399554085,
            z: -0.022911006648570736,
          },
          eye: {
            x: -2.126379643342493,
            y: -2.551422475965373,
            z: 1.0917667684145647,
          },
          projection: {
            type: "orthographic",
          },
        },
        "scene.aspectratio": {
          x: 2.2,
          y: 1.7,
          z: 1,
        },
      });
    },
  },
};
</script>

<style scoped>
/* #scene {
  background: #e5ecf6 !important;
}
.js-plotly-plot .plotly,
.js-plotly-plot .plotly div {
  background: #e5ecf6 !important;
} */
/* 样式可以根据需求自定义 */
#plotly-3d-chart {
  width: 100%;
  height: 600px;
}

::v-deep canvas {
  /* height: 400px !important; */
}
</style>
