<!--
 * @Author: your name
 * @Date: 2024-09-11 14:30:17
 * @LastEditTime: 2025-01-20 09:16:32
 * @LastEditors: bogon
 * @Description: In User Settings Edit
 * @FilePath: /performance-test/src/views/performance/components/chartsCom/BarChart.vue
-->

<template>
  <div>
    <!-- 图表控制面板 -->
    <div style="display: flex; align-items: center">
      <div style="margin-right: 20px; display: flex; align-items: center">
        <el-color-picker
          size="small"
          v-model="color1"
          show-alpha
          @change="updateChartColor"
        ></el-color-picker>
        <span style="margin-left: 10px">自定义颜色</span>
      </div>
      <div>
        <el-button size="small" @click="toggleChartType">
          切换为{{ chartType === "bar" ? "折线图" : "柱状图" }}
        </el-button>
      </div>
    </div>

    <!-- 图表容器 -->
    <div
      v-loading="loading"
      :id="`bar-chart${inds}`"
      style="width: 100%; height: 400px"
    >
      <el-empty v-if="isError" description="请求失败"></el-empty>
    </div>
  </div>
</template>

<script>
import { nextTick } from "vue"; // 导入 nextTick
import Plotly from "plotly.js-dist";
import axios from "axios";
import { myMixin } from "@/mixins/chartRequestMixin";

export default {
  props: {
    fileAddr: {
      default: "",
      type: String,
    },
    inds: {
      type: Number,
      default() {
        return 0;
      },
    },
  },
  mixins: [myMixin],
  data() {
    return {
      chartData: {
        analysisTypeCode: "",
        engineCode: "",
        engineTypeName: "",
        xaixs: "",
        yaixs: "",
        data: [
          // {
          //   xData: ["2024-01-01", "2024-01-02", "2024-01-03", "2024-01-04", "2024-01-05"],
          //   yData: [10, 20, 30, 40, 50],
          //   title: "数据集1",
          // },
        ],
      },
      chartType: "bar", // 当前图表类型 ('bar' 或 'scatter')
      color1: "#406DAB", // 默认颜色
      // normalRangeMin: 5, // 最低范围
      // normalRangeMax: 18, // 最高范围
    };
  },
  mounted() {
    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,
          });
          this.chartData = resultChartsData.data;
          // 使用 nextTick 来确保 DOM 渲染完成后绘制图表
          nextTick(() => {
            this.drawChart();
            this.isError = false;
            this.loading = false;
          });
        } catch (error) {
          console.error("Error loading data:", error);
          this.isError = true;
          this.loading = false;
        }
      }
    },
    // 绘制图表
    drawChart() {
      if (this.chartData.data.length === 0) return;

      const chartDataset = this.chartData.data[0];
      const trace = {
        x: chartDataset.xData, // 横坐标数据
        y: chartDataset.yData, // 纵坐标数据
        type: this.chartType, // 当前图表类型 ('bar' 或 'scatter')
        marker: {
          color: this.color1, // 柱状图颜色
        },
        line: {
          color: this.color1, // 折线图颜色
        },
        name: chartDataset.title || "数据", // 图例名称
      };

      // Normal Range Lines
      const normalRangeLine = {
        x: chartDataset.xData, // 横坐标数据
        y: Array(chartDataset.xData.length).fill(this.normalRangeMin), // 最低值线
        mode: "lines",
        name: "LCL", // 图例名称（最低范围）
        line: {
          color: "red",
          width: 2,
          dash: "dash", // 虚线
        },
      };

      const normalRangeMaxLine = {
        x: chartDataset.xData, // 横坐标数据
        y: Array(chartDataset.xData.length).fill(this.normalRangeMax), // 最高值线
        mode: "lines",
        name: "UCL", // 图例名称（最高范围）
        line: {
          color: "red",
          width: 2,
          dash: "dash", // 虚线
        },
      };

      const layout = {
        title: this.chartData.analysisTypeCode || "图表", // 图表标题
        xaxis: {
          title: this.chartData.xaixs || "X轴", // 横坐标标题
        },
        yaxis: {
          title: this.chartData.yaixs || "Y轴", // 纵坐标标题
        },
        margin: {
          l: 50,
          r: 50,
          t: 50,
          b: 50,
        },
        autosize: true, // 开启自适应
      };

      // 渲染图表
      Plotly.newPlot(
        `bar-chart${this.inds}`,

        // [trace, normalRangeLine, normalRangeMaxLine],
        [trace],
        layout,
        {
          responsive: true,
        }
      );
    },
    // 切换图表类型
    toggleChartType() {
      this.chartType = this.chartType === "bar" ? "scatter" : "bar";
      this.drawChart();
    },
    // 更新图表颜色
    updateChartColor() {
      this.drawChart();
    },
  },
};
</script>

<style scoped>
/* 样式可以根据需求自定义 */
</style>
