<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
      v-loading="loading"
      :id="`plotly-3d-chart-` + index"
      ref="plotlyChart"
      style="height: 600px; background-color: #e5ecf6"
    ></div>
  </div>
</template>

<script>
import Plotly, { doCamera } 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: [], // 默认颜色
      chartData: {},
      chartType: "scatter", // 当前图表类型（默认是散点图）
      colorSchemes: [...colorSchemes],
      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.getData();
      // if (this.themeColor.length === 0) {
      this.color1 = this.colorSchemes[0].colors;
      // } else {
      //   this.color1 = this.themeColor;
      // }
    });
  },

  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"'); // 处理无效字符
            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;
        }
      }
    },
    // 格式化日期为 YY-MM 格式
    formatDate(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear(); // 获取年份后两位
      const month = ("0" + (date.getMonth() + 1)).slice(-2); // 获取月份并确保两位数
      return `${year}-${month}`;
    },
    renderChart() {
      // 提取 Y 轴数据中的月份，并去重
      const uniqueMonths = Array.from(
        new Set(
          this.chartData.data[0].yData.map((date) => this.formatDate(date))
        )
      );
      if (!this.color1) {
        this.color1 = colorSchemes[0].colors;
      }
      // 设置每个月份对应的颜色
      const monthColors = this.color1;
      // 为每个月份生成独立的 trace，每个 trace 对应一个月份
      const traces = uniqueMonths.map((month, monthIndex) => {
        const monthData = this.chartData.data[0].yData
          .map((date, index) => (this.formatDate(date) === month ? index : -1))
          .filter((index) => index !== -1);

        const trace = {
          x: monthData.map((index) => this.chartData.data[0].xData[index]), // 发电机转速
          y: monthData.map((index) => this.chartData.data[0].yData[index]), // 时间
          z: monthData.map((index) => this.chartData.data[0].zData[index]), // 有功功率
          mode: "markers",
          type: "scatter3d", // 3D 散点图
          marker: {
            size: this.pointSize,
            color: monthColors[monthIndex],
            opacity: 0.8,
            lighting: {
              ambient: 0.3, // 环境光（影响整体亮度）
              diffuse: 1, // 漫反射光（增加真实感）
              specular: 0.5, // 镜面反射（增强高光）
              roughness: 0.5, // 低值=光滑表面，高值=粗糙表面
              fresnel: 0.2, // 边缘高光强度
            },
          },
          name: month, // 图例项名称，格式为 YY-MM
          legendgroup: `month-${monthIndex}`, // 图例分组
          hovertemplate:
            `${this.chartData.xaixs}:` +
            ` %{x} <br> ` +
            `${this.chartData.yaixs}:` +
            "%{y} <br>" +
            `${this.chartData.zaixs}:` +
            "%{z} <br><extra></extra>",
        };

        return trace;
      });
      const layout = {
        title: {
          text: this.chartData.data[0].title,
          font: {
            size: 16,
            weight: "bold",
          },
        },
        scene: {
          xaxis: {
            title: {
              text: this.chartData.xaixs,
              standoff: 100,
            },
            gridcolor: "#fff",
            backgroundcolor: "#e0e7f1",
            showbackground: true,
            linecolor: "black",
            ticks: "outside",
            ticklen: 10,
            tickcolor: "black",
            zeroline: false,
            tickangle: -10,
            // nticks: 5,
            dtick: this.chartData.xaixs === "风速（m/s）" ? 1 : undefined,
            // range:
            //   this.chartData.xaixs === "发电机转速(r/min)" ||
            //   this.chartData.xaixs === "发电机转速（r/min）"
            //     ? [1000, 2000]
            //     : undefined,
            // range: this.chartData.xaixs === "桨距角(°)" ? [-1, 20] : undefined,
          },
          // 对 Y 轴不显示默认标题，只保留 tick 标签，并适当加大 standoff 以防止标签挤在一起
          yaxis: {
            title: {
              text: this.chartData.yaixs, // 隐藏默认标题
            },
            type: "category", // 让 Y 轴按类别均匀分布
            categoryorder: "category ascending", // 按类别字母顺序排列
            type: "date",
            tickformat: "%Y-%m",
            // dtick: "M3",//显式设置每3个月一个刻度
            gridcolor: "#fff",
            tickcolor: "#e5ecf6",
            backgroundcolor: "#e0e7f1",
            showbackground: true,
            linecolor: "black",
            ticks: "outside",
            tickcolor: "black",
            zeroline: false,
            tickangle: 25,
            nticks: 3,
          },
          zaxis: {
            title: {
              text: this.chartData.zaixs,
            },
            gridcolor: "#fff",
            tickcolor: "#fff",
            backgroundcolor: "#e0e7f1",
            showbackground: true,
            linecolor: "black",
            ticks: "outside",
            tickcolor: "black",
            zeroline: false,
            tickangle: -90,
            nticks: 3,
          },
          bgcolor: "#e5ecf6",
          aspectratio: {
            x: 2.2,
            y: 1.7,
            z: 1,
          },
          aspectmode: "manual",
          gridcolor: "#fff",
          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",
          "resetCameraLastSave3d",
          "resetCameraDefault3d",
          "resetCameraLastSave",
          "sendDataToCloud",
          "zoom2d", // 缩放按钮
          "zoom3d",
          "plotlylogo2D",
          "plotlylogo3D",
        ],
        responsive: true,
        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];
      }
      Plotly.newPlot(
        `plotly-3d-chart-` + this.index,
        traces,
        layout,
        config
      ).then(function (gd) {
        // 获取工具栏按钮
        const toolbar = gd.querySelector(".modebar");
        const buttons = toolbar.querySelectorAll(".modebar-btn");

        // 定义一个映射对象，方便修改按钮提示
        const titleMap = {
          "Download plot as a png": "保存图片",
          Autoscale: "缩放",
          Pan: "平移",
          "Zoom out": "放大",
          "Zoom in": "缩小",
          "Box Select": "选择框操作",
          "Lasso Select": "套索选择操作",
          "Reset axes": "重置操作",
          "Reset camera to default": "重置相机视角",
          "Turntable rotation": "转台式旋转",
          "Orbital rotation": "轨道式旋转",
        };

        // 遍历所有按钮，修改它们的 title
        buttons.forEach(function (button) {
          const dataTitle = button.getAttribute("data-title");

          // 如果标题匹配，修改属性值
          if (titleMap[dataTitle]) {
            button.setAttribute("data-title", titleMap[dataTitle]);
          }
        });
      });
      // 监听图表的 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"]
          );
        }
      });
    },
    // 还原视角
    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,
        },
      });
    },
    updateChartColor() {
      this.renderChart(); // 当配色方案或点大小发生变化时重新渲染图表
    },

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

<style scoped>
/* 样式可以根据需求自定义 */
#plotly-3d-chart {
  width: 100%;
  height: 600px;
}

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