<template>
  <div style="width: 100%; height: 500px">
    <!-- 条件渲染日期范围选择器 -->
    <el-date-picker
      v-if="chartData.xaixs === '时间'"
      v-model="dateRange"
      type="daterange"
      align="right"
      unlink-panels
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      @change="onDateRangeChange"
      size="mini"
      style="margin: 20px 0 0 0"
    ></el-date-picker>

    <div
      v-loading="loading"
      :id="`plotDivBox-${index}`"
      style="width: 100%; height: 450px"
    >
      <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";

export default {
  mixins: [myMixin],
  props: {
    fileAddr: {
      default: "",
      type: String,
    },
    index: {
      type: String,
    },
    setUpImgData: {
      default: () => [],
      type: Array,
    },
  },
  data() {
    return {
      chartData: {},
      dateRange: [], // 用于存储选中的日期范围
      loading: false,
      isError: false,
    };
  },
  watch: {
    setUpImgData: {
      handler(newType) {
        this.drawBoxPlot();
      },
      deep: true,
    },
    dateRange: {
      handler(newRange) {
        this.drawBoxPlot(); // 日期范围变化时重新绘制图表
      },
      deep: true,
    },
  },
  mounted() {
    console.log(this.fileAddr, "fileAddr 连接");
    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;
          this.loading = false;
          this.isError = false;
          this.drawBoxPlot(); // 数据加载完成后绘制图表
        } catch (error) {
          this.loading = false;
          this.isError = true;
        }
      }
    },

    // 处理日期范围变化
    onDateRangeChange() {
      this.drawBoxPlot(); // 日期变化时重新绘制图表
    },

    // 判断时间戳是否在选择的日期范围内
    isInDateRange(timestamp) {
      const [startDate, endDate] = this.dateRange;
      if (!startDate || !endDate) return true;

      const date = new Date(timestamp);
      return date >= new Date(startDate) && date <= new Date(endDate);
    },

    // 判断xData是否为日期格式
    isDateType(xData) {
      if (xData) {
        const firstTimestamp = xData[0];
        return !isNaN(Date.parse(firstTimestamp)); // 判断是否是有效日期
      } else {
        return false;
      }
    },

    // 过滤数据
    filterData(group) {
      const filteredXData = [];
      const filteredYData = [];
      const filteredMedians = group.medians ? { x: [], y: [] } : null;

      if (this.isDateType(group.xData)) {
        group.xData.forEach((timestamp, index) => {
          if (this.isInDateRange(timestamp)) {
            filteredXData.push(timestamp);
            filteredYData.push(group.yData[index]);

            if (filteredMedians && this.isInDateRange(group.medians.x[index])) {
              filteredMedians.x.push(group.medians.x[index]);
              filteredMedians.y.push(group.medians.y[index]);
            }
          }
        });
      } else {
        filteredXData.push(...group.xData);
        filteredYData.push(...group.yData);

        if (group.medians) {
          filteredMedians.x.push(...group.medians.x);
          filteredMedians.y.push(...group.medians.y);
        }
      }

      return {
        ...group,
        xData: filteredXData,
        yData: filteredYData,
        medians: filteredMedians,
      };
    },

    // 绘制箱线图
    drawBoxPlot() {
      if (!this.chartData.data || this.loading) return; // 如果数据为空或正在加载则不绘制

      const chartData = this.chartData.data[0];
      const filteredData = this.filterData(chartData);

      const trace = {
        x: filteredData.xData,
        y: filteredData.yData,
        type: "box",
        marker: {
          color: "lightgray",
        },
        boxpoints: false,
        boxmean: false,
        name: filteredData.title,
        fillcolor: "#406DAB", // 设置箱线图填充颜色，带透明度
        hovertemplate:
          `${this.chartData.xaixs}:` +
          ` %{x} <br> ` +
          `${this.chartData.yaixs}:` +
          "%{y} <br>",
      };

      let trace2 = {};
      if (filteredData.medians && filteredData.medians.x.length > 0) {
        trace2 = {
          x: filteredData.medians.x,
          y: filteredData.medians.y,
          mode: "markers",
          marker: {
            color: "#406DAB",
            size: 3,
          },
          name: `${filteredData.title} - 中位点`,
          type: "scatter",
        };
      }

      const layout = {
        title: filteredData.title,
        xaxis: {
          title: this.chartData.xaixs,
          tickmode: "array",
        },
        yaxis: { title: this.chartData.yaixs },
        showlegend: true,
      };
      if (
        this.chartData.xaixs === "机组" ||
        this.chartData.xaixs === "机组名称"
      ) {
        layout.xaxis.tickvals = [...new Set(filteredData.xData)];
        layout.xaxis.ticktext = [...new Set(filteredData.xData)];
      }

      const getChartSetUp = (axisTitle) => {
        return this.setUpImgData.find((item) => item.text.includes(axisTitle));
      };

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

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

      this.$nextTick(() => {
        const plotDiv = document.getElementById(`plotDivBox-${this.index}`);
        if (plotDiv) {
          Plotly.newPlot(plotDiv, [trace, trace2], layout);
        }
      });
    },
  },
};
</script>

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