<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"
            :style="getOptionStyle(scheme.colors)"
          ></el-option>
        </el-select>
      </div>
    </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
      v-loading="loading"
      :id="`plotly-3d-chart-` + index"
      ref="plotlyChart"
      style="height: 600px"
    >
      <el-empty v-if="isError" description="请求失败"></el-empty>
    </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: [
        "#DBEEBC",
        "#A8D7BE",
        "#8ECAC1",
        "#77BDC2",
        "#64ADC2",
        "#559ABE",
        "#4884B7",
        "#406DAB",
        "#3856A0",
        "#314291",
        "#28357A",
        "#1A285E",
        "#FF7F50",
        "#FFD700",
        "#90EE90",
      ], // 默认颜色
      chartData: {},
      chartType: "scatter", // 当前图表类型（默认是散点图）
      colorSchemes: [...colorSchemes],
      pointSize: 2, // 默认点大小
    };
  },
  mixins: [myMixin],
  computed: {
    ...mapState("themes", {
      themeColor: "themeColor",
    }),
  },
  watch: {
    themeColor: {
      handler() {
        this.color1 = this.themeColor;
        this.updateChartColor();
      },
      deep: true,
    },
    setUpImgData: {
      handler(newType) {
        this.renderChart();
      },
      deep: true,
    },
  },
  async mounted() {
    this.getData();
    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().toString().slice(2); // 获取年份后两位
      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],
          },
          name: month, // 图例项名称，格式为 YY-MM
          legendgroup: `month-${monthIndex}`, // 图例分组
          hovertemplate:
            `${this.chartData.xaixs}:` +
            ` %{x} <br> ` +
            `${this.chartData.yaixs}:` +
            "%{y} <br>" +
            `${this.chartData.zaixs}:` +
            "%{z} <br>",
        };

        return trace;
      });

      const layout = {
        title: this.chartData.data[0].title,
        scene: {
          xaxis: {
            title: this.chartData.xaixs, // X 轴标题
            gridcolor: "rgb(255,255,255)",
            tickcolor: "rgb(255,255,255)",
            backgroundcolor: "#e5ecf6",
            showbackground: true,
          },
          yaxis: {
            title: this.chartData.yaixs, // Y 轴标题
            tickformat: "%y-%m", // 设置 Y 轴的时间格式为 YY-MM
            gridcolor: "rgb(255,255,255)",
            tickcolor: "rgb(255,255,255)",
            backgroundcolor: "#e5ecf6",
            showbackground: true,
          },
          zaxis: {
            title: this.chartData.zaixs, // Z 轴标题
            gridcolor: "rgb(255,255,255)",
            tickcolor: "rgb(255,255,255)",
            backgroundcolor: "#e5ecf6",
            showbackground: true,
          },
          // aspectratio: {
          //   x: 1,
          //   y: 3,
          //   z: 1,
          // },
          plot_bgcolor: "#e5ecf6",
          gridcolor: "#fff",
          // camera: {
          //   center: { x: 0, y: 0, z: 0 },
          //   eye: { x: 0, y: 0, z: 2.5 },
          //   up: { x: 0, y: 0, z: 1 },
          // },
        },
        margin: { t: 50, b: 50, l: 50, r: 50 },
        staticPlot: false,
        showlegend: true,
        legend: {
          marker: {
            size: 10, // 图例中点的大小
          },
        },
      };
      // 获取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];
      }
      console.log(zChartSetUp, yChartSetUp, xChartSetUp, "xChartSetUp");
      Plotly.newPlot(`plotly-3d-chart-` + this.index, traces, layout);
    },

    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: 500px;
}

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