<template>
  <div>
    <div style="display: flex; align-items: center">
      <div
        style="margin-right: 20px; display: flex; align-items: center"
        v-if="comType === 'generalDrawing'"
      >
        <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>
        <!-- <span style="margin-left: 10px">自定义颜色</span> -->
      </div>
      <div>
        <el-button size="small" @click="toggleChartType">
          切换为{{ chartType === "line" ? "面积图" : "折线图" }}
        </el-button>
      </div>
    </div>
    <!-- 总图组件 -->
    <div
      v-if="comType === 'generalDrawing'"
      :id="`power-curve-plot${inds}`"
      style="width: 100%; height: 550px"
    ></div>
    <!-- 分图组件  -->
    <template v-else-if="comType === 'graph'">
      <div :id="`chart-${inds}`" style="width: 100%; height: 550px"></div>
    </template>
  </div>
</template>
<script>
import Plotly from "plotly.js-dist";
import { colorSchemesLine } from "@/views/overview/js/colors";
export default {
  props: {
    lineMarkerData: Object,
    comType: String,
    inds: String,
  },
  name: "PowerCurvePlot",
  data() {
    return {
      chartType: "line", // 默认图表类型是折线图
      graphData: [], //分图数据length data
      color1: [], // 默认颜色
      // 配色方案列表（每个方案是一个颜色数组）
      colorSchemes: [...colorSchemesLine],
      config: {
        powerConfig: {
          mode: "lines+markers",
          name: "合同功率曲线",
          line: {
            color: "red",
            width: 1, // 设置线条的宽度为1
          },
          marker: { color: "red", size: 4 },
        },
        lableConfig: {
          title: { text: "", x: 0.5 },
          plot_bgcolor: "#e5ecf6", // Chart background color
          xaxis: {
            title: "风速(m/s)",
            // range: [0, 26],
            tickmode: "linear",
            gridcolor: "rgb(255,255,255)",
            showgrid: true,
            zeroline: false,
            tickcolor: "rgb(255,255,255)",
            dtick: 1,
            tickangle: -45,
          },
          yaxis: {
            title: "功率(kW)",
            gridcolor: "rgb(255,255,255)",
            showgrid: true,
            zeroline: false,
            tickcolor: "rgb(255,255,255)",
          },
          legend: {
            orientation: "h",
            xanchor: "center",
            x: 0.5,
            y: -0.2,
          },
        },
        colors: [
          "#636EFA",
          "#EF553B",
          "#00CC96",
          "#AB63FA",
          "#FFA15A",
          "#19D3F3",
          "#FF6692",
          "#B6E880",
          "#FF97FF",
          "#FECB52",
          "#636EFB",
          "#EF553C",
          "#00CC97",
          "#AB63FB",
          "#FFA15B",
          "#19D3F4",
          "#FF6693",
          "#B6E881",
          "#FF97FE",
          "#FECB51",
          "#1F77B4",
          "#FF7F0E",
          "#2CA02C",
          "#D62728",
          "#9467BD",
          "#8C564B",
          "#E377C2",
          "#7F7F7F",
          "#BCBD22",
          "#17BECF",
          "#1A55F2",
          "#FF5733",
          "#33FF57",
          "#3375FF",
          "#FF33A6",
          "#57FF33",
          "#3380FF",
          "#FF8033",
          "#57FF80",
          "#8033FF",
          "#FF3380",
          "#FFD733",
        ],
      },
      powerCurveData: {
        turbines: [],
        contractPowerCurve: [],
      },
    };
  },
  mounted() {
    this.updateCharts(); // 初次渲染
  },
  watch: {
    lineMarkerData: {
      deep: true,
      handler() {
        this.updateCharts(); // 数据变化时更新
      },
    },
    comType(newType, oldType) {
      if (newType !== oldType) {
        this.updateCharts(); // 类型变化时更新
      }
    },
  },
  methods: {
    updateCharts() {
      // console.log(this.lineMarkerData, "this.lineMarkerData");
      this.powerCurveData.turbines =
        this.lineMarkerData.data?.filter(
          (item) => item.enginName !== "合同功率曲线"
        ) || [];

      this.powerCurveData.contractPowerCurve =
        this.lineMarkerData.data?.filter(
          (item) => item.enginName === "合同功率曲线"
        ) || [];

      if (this.comType === "generalDrawing" && this.lineMarkerData?.data) {
        this.renderPlot();
      } else if (this.comType === "graph" && this.lineMarkerData?.data) {
        this.$nextTick(() => {
          this.initializeEngineCharts();
        });
      }
    },
    renderPlot() {
      const data = [];
      this.powerCurveData.turbines.forEach((turbine, index) => {
        data.push({
          x: turbine.xData,
          y: turbine.yData.map((val) => (val !== null ? val : 0.0)),
          mode: "lines",
          name: turbine.enginName,
          fill: this.chartType === "line" ? "none" : "tonexty",
          line: {
            color:
              this.color1.length > 0
                ? this.color1[index % this.color1.length]
                : this.config.colors[index % this.config.colors.length],
          },
        });
      });

      data.push({
        x: this.powerCurveData.contractPowerCurve[0].xData,
        y: this.powerCurveData.contractPowerCurve[0].yData,
        mode: this.config.powerConfig.mode,
        name: this.config.powerConfig.name,
        line: this.config.powerConfig.line,
        marker: this.config.powerConfig.marker,
      });
      // console.log(this.powerCurveData, "this.powerCurveData");
      const layout = {
        title: "有功功率曲线分析" + this.lineMarkerData.engineTypeName,
        plot_bgcolor: this.config.lableConfig.plot_bgcolor,
        xaxis: this.config.lableConfig.xaxis,
        yaxis: this.config.lableConfig.yaxis,
        legend: this.config.lableConfig.legend,
      };
      Plotly.newPlot(`power-curve-plot${this.inds}`, data, layout);
    },
    //初始化分图
    initializeEngineCharts() {
      const fentuCharts = this.powerCurveData.turbines.filter(
        (item) =>
          item.enginCode === this.lineMarkerData?.formInfoFieldEngineCode
      );
      // console.log(this.powerCurveData.turbines, "this.powerCurveData.turbines");
      // console.log(fentuCharts, "fentuCharts");
      if (fentuCharts[0]?.enginName || fentuCharts[0]?.enginCode) {
        const highlightedData = [];
        const nonHighlightedData = [];
        const layout = {
          title:
            fentuCharts[0]?.enginName ||
            fentuCharts[0]?.enginCode + "风机有功功率曲线分析",
          plot_bgcolor: this.config.lableConfig.plot_bgcolor,
          xaxis: this.config.lableConfig.xaxis,
          yaxis: this.config.lableConfig.yaxis,
          legend: this.config.lableConfig.legend,
        };
        // 先渲染其他的风机数据
        this.powerCurveData.turbines.forEach((turbine, index) => {
          const isHighlighted =
            turbine?.enginCode ===
              this.lineMarkerData?.formInfoFieldEngineCode ||
            turbine?.enginName === this.lineMarkerData?.formInfoFieldEngineCode;

          const trace = {
            x: turbine.xData,
            y: turbine.yData.map((val) => (val !== null ? val : 0.0)),
            mode: "lines",
            name: turbine.enginName,
            fill: this.chartType === "line" ? "none" : "tonexty",
            line: {
              color: isHighlighted ? "#1c77b3" : "#d3d3d3",
            },
          };

          if (isHighlighted) {
            highlightedData.push(trace); // 高亮的线条放入 highlighedData
          } else {
            nonHighlightedData.push(trace); // 非高亮的线条放入 nonHighlightedData
          }
        });
        // 先添加非高亮的风机数据
        const data = [...nonHighlightedData, ...highlightedData]; // 高亮的风机数据最后添加
        // 添加合同功率曲线
        data.push({
          x: this.powerCurveData.contractPowerCurve[0].xData,
          y: this.powerCurveData.contractPowerCurve[0].yData,
          mode: "lines+markers",
          name: this.powerCurveData.contractPowerCurve[0].enginName,
          line: {
            color: "red",
            width: 1, // 设置线条的宽度为1
          },
          marker: { color: "red", size: 4 },
        });
        Plotly.newPlot(`chart-${this.inds}`, data, layout);
      }
    },
    // 切换图表类型
    toggleChartType() {
      this.chartType = this.chartType === "line" ? "bar" : "line"; // 切换图表类型
      // 重新绘制图表
      this.updateCharts();
    },
    updateChartColor(color) {
      // 更新图表颜色
      // this.color1 = color;
      this.updateCharts();
    },
    // 根据配色方案设置每个选项的样式
    getOptionStyle(scheme) {
      return {
        background: `linear-gradient(to right, ${scheme.join(", ")})`,
        color: "#fff",
        height: "30px",
        lineHeight: "30px",
        borderRadius: "4px",
      };
    },
  },
};
</script>

<style scoped>
/* You can add styles for your component here */
</style>
