<!--
 * @Author: your name
 * @Date: 2025-07-24 10:33:42
 * @LastEditTime: 2025-08-08 09:33:02
 * @LastEditors: bogon
 * @Description: In User Settings Edit
 * @FilePath: /performance-test/src/views/performance/components/chartsCom/Time3DBarChart.vue
-->
<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 from "plotly.js-dist";
import { myMixin } from "@/mixins/chartRequestMixin";
import { colorSchemes } from "@/views/overview/js/colors";
import { mapState } from "vuex";
export default {
  props: {
    index: {
      default: "",
      type: String,
    },
    chartData: {
      default: () => {},
      type: Object,
    },
    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,
    },
    chartData: {
      handler(newType) {
        console.log(newType, "newType");
        this.renderChart();
      },
      deep: true,
    },
  },
  async mounted() {
    this.$nextTick(() => {
      // this.getData();
      this.color1 = this.colorSchemes[0].colors;
      this.renderChart();
    });
  },

  methods: {
    formatDate(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear(); // 获取年份后两位
      const month = ("0" + (date.getMonth() + 1)).slice(-2); // 获取月份并确保两位数
      return `${year}-${month}`;
    },
    renderChart() {
      const colorMap = {}; // 记录每个 fault_detail 分配的颜色
      const colorPalette = [...colorSchemes[0].colors];

      let colorIndex = 0;
      const traces = [];

      if (!this.color1) {
        this.color1 = colorSchemes[0].colors;
      }

      this.chartData &&
        this.chartData.data.forEach((item) => {
          const fault = item.fault_detail;
          const yVal = item.fault_time_sum;
          const zVal = item.count;

          // 分配唯一颜色
          if (!colorMap[fault]) {
            colorMap[fault] = colorPalette[colorIndex % colorPalette.length];
            colorIndex++;
          }

          const trace = {
            type: "scatter3d",
            mode: "lines",
            x: [fault, fault, null],
            y: [yVal, yVal, null],
            z: [0, zVal, null],
            line: {
              color: colorMap[fault],
              width: 16,
            },
            name: fault,
            hovertemplate:
              `故障代码: %{x}<br>` +
              `累计时间: %{y}<br>` +
              `出现次数: %{z}<extra></extra>`,
            showlegend: true,
          };

          traces.push(trace);
        });
      const layout = {
        title: {
          text: "故障代码出现次数",
          font: { size: 16, weight: "bold" },
        },
        scene: {
          xaxis: {
            title: { text: "故障代码", standoff: 100 },
            showgrid: true,
            zeroline: false,
            gridcolor: "#fff",
            backgroundcolor: "#e0e7f1",
            showbackground: true,
            linecolor: "black",
            ticks: "outside",
            ticklen: 10,
            tickcolor: "black",
            // tickangle: -10,
          },
          yaxis: {
            title: { text: "累计时间" },
            showgrid: true,
            zeroline: false,
            gridcolor: "#fff",
            backgroundcolor: "#e0e7f1",
            showbackground: true,
            linecolor: "black",
            ticks: "outside",
            tickangle: 25,
          },
          zaxis: {
            title: { text: "出现次数" },
            showgrid: true,
            zeroline: false,
            gridcolor: "#fff",
            backgroundcolor: "#e0e7f1",
            showbackground: true,
            linecolor: "black",
            ticks: "outside",
            tickangle: -90,
          },
          bgcolor: "#e5ecf6",
          aspectratio: { x: 2.2, y: 1.7, z: 1 },
          aspectmode: "manual",
          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: {
          x: 1.02,
          y: 1,
          marker: { size: 10 },
          font: {
            size: 10,
          },
          itemsizing: "constant",
          itemwidth: 2, // 设置图例项的宽度
        },
      };

      const config = {
        modeBarButtonsToAdd: [
          {
            name: "还原",
            icon: Plotly.Icons.home,
            click: () => this.resetCamera(),
          },
        ],
        modeBarButtonsToRemove: [
          "sendDataToCloud",
          "resetCameraLastSave3d",
          "resetCameraDefault3d",
          "resetCameraLastSave",
          "zoom2d",
          "zoom3d",
          "plotlylogo2D",
          "plotlylogo3D",
        ],
        responsive: true,
        displaylogo: false,
      };

      // 设置轴范围和间距（如果配置了）
      const getChartSetUp = (axisTitle) => {
        return this.setUpImgData.find((item) => item.text.includes(axisTitle));
      };

      const xSetup = getChartSetUp(layout.scene.xaxis.title.text);
      if (xSetup) {
        layout.scene.xaxis.dtick = xSetup.dtick;
        layout.scene.xaxis.range = [xSetup.min, xSetup.max];
      }

      const ySetup = getChartSetUp(layout.scene.yaxis.title.text);
      if (ySetup) {
        layout.scene.yaxis.dtick = ySetup.dtick;
        layout.scene.yaxis.range = [ySetup.min, ySetup.max];
      }

      const zSetup = getChartSetUp(layout.scene.zaxis.title.text);
      if (zSetup) {
        layout.scene.zaxis.dtick = zSetup.dtick;
        layout.scene.zaxis.range = [zSetup.min, zSetup.max];
      }

      Plotly.newPlot(
        `plotly-3d-chart-${this.index}`,
        traces,
        layout,
        config
      ).then((gd) => {
        const toolbar = gd.querySelector(".modebar");
        const buttons = toolbar.querySelectorAll(".modebar-btn");
        const legends = document.querySelectorAll(".legendtext");

        legends.forEach((el) => {
          const fullText = el.textContent;
          el.setAttribute("data-fulltext", fullText);
        });
        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": "轨道式旋转",
        };

        buttons.forEach((btn) => {
          const dataTitle = btn.getAttribute("data-title");
          if (titleMap[dataTitle]) {
            btn.setAttribute("data-title", titleMap[dataTitle]);
          }
        });
      });

      const plotElement = document.getElementById(
        `plotly-3d-chart-${this.index}`
      );
      plotElement.on("plotly_relayout", (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; */
}
/* 放在你页面的样式中 */
.legendtext {
  max-width: 30px;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: top;
  position: relative;
  cursor: pointer;
}

.legendtext:hover::after {
  content: attr(data-fulltext);
  position: absolute;
  left: 100%;
  top: 0;
  transform: translateX(6px);
  max-width: 300px;
  background: rgba(0, 0, 0, 0.85);
  color: #fff;
  font-size: 12px;
  padding: 4px 6px;
  border-radius: 4px;
  z-index: 9999;
  white-space: normal;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.3);
}
</style>
