<template>
  <div class="MAXdiv">
    <div class="TopBox">
      <div class="rightdiv">
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          height="250"
        >
          <el-table-column prop="time_stamp" label="时间" align="center" />
          <el-table-column
            prop="temp_channel"
            label="部件名称"
            align="center"
          />

          <!-- 自定义状态列样式 -->
          <el-table-column prop="status" label="温度状态" align="center">
            <template #default="{ row }">
              <span :class="{ 'warning-text': row.status !== '正常' }">
                {{ row.status }}
              </span>
            </template>
          </el-table-column>
        </el-table>

        <div class="fenye">
          <p>特征值越接近1表示危险</p>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            layout="total, prev, pager, next"
            :total="totalCount"
            :page-size="500"
          />
        </div>
      </div>

      <div class="leftdiv">
        <div class="stateBox">
          <h4>温度状态</h4>
          <div class="state">
            <p :style="{ backgroundColor: getStatusColor('主轴承温度') }">
              主轴承温度
            </p>
            <p :style="{ backgroundColor: getStatusColor('齿轮箱油温') }">
              齿轮箱油温
            </p>
            <p
              :style="{
                backgroundColor: getStatusColor('发电机驱动端轴承温度'),
              }"
            >
              发电机驱动端轴承温度
            </p>
            <p
              :style="{
                backgroundColor: getStatusColor('发电机非驱动端轴承温度'),
              }"
            >
              发电机非驱动端轴承温度
            </p>
          </div>
        </div>

        <div class="Btn">
          <div style="height: 200px">
            <bing :result="result" />
          </div>
          <div class="minp">
            <p class="PText">
              <span><i class="color1"></i>正常</span>
              <span><i class="color2"></i>危险</span>
            </p>
            <h4>诊断步骤：</h4>
            <p>1、选择风场风机与起止时间，点击“查询”;</p>
            <p>2、点击“查询”输出最终温度状态结果。</p>
          </div>
        </div>
      </div>
    </div>

    <div class="bottomBox">
      <div class="tu" v-for="(item, index) in chartList" :key="index">
        <el-empty v-if="!hasData(item.data)" description="暂无数据" />
        <zhexian
          v-else
          :title="item.title"
          :lineType="item.lineType"
          :lineColor="item.lineColor"
          :chartData="item.data"
          :fieldCode="fieldCode"
          :windTurbineNumber="windTurbineNumber"
            :bearingKey="item.bearingKey"
          
        />
      </div>
    </div>
  </div>
</template>

<script>
import Eecharts from "./Eecharts.vue";
import bing from "./bing.vue";
import Zhexian from "./zhexian.vue";

export default {
  components: { Eecharts, bing, Zhexian },
  props: {
    echartsdata: {
      type: Object,
      default: () => ({
        main_bearing: [],
        generator_drive_end: [],
        gearbox_oil: [],
        generator_nondrive_end: [],
      }),
    },
    codedata: {
      type: Array,
      default: () => [],
    },
    totalCount: {
      type: Number,
      default: 0,
    },
    totalPage: {
      type: Number,
      default: 0,
    },
    fieldCode: {
      type: String,
      default: "",
    },
    windTurbineNumber: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      tableData: [],
      currentPage: 1,
      total: 1,
      result: {},
      bearingStateColors: {
        innerRing: "#80808057",
        outerRing: "#80808057",
        rollingElement: "#80808057",
        cage: "#80808057",
      },
    };
  },
  computed: {
    chartList() {
      const list = [
        {
          title: "主轴承温度趋势图",
          data: this.echartsdata.main_bearing,
          lineType: "line",
          lineColor: "#02aae9",
          bearingKey: "innerRing",
        },
        {
          title: "发电机驱动端轴承温度趋势图",
          data: this.echartsdata.generator_drive_end,
          bearingKey: "rollingElement",
        },
        {
          title: "齿轮箱油温趋势图",
          data: this.echartsdata.gearbox_oil,
          lineType: "line",
          lineColor: "#02aae9",
          bearingKey: "outerRing",
        },
        {
          title: "发电机非驱动端轴承温度趋势图",
          data: this.echartsdata.generator_nondrive_end,
          bearingKey: "cage",
        },
      ];

      const sortedList = list.slice().sort((a, b) => {
        return this.hasData(b.data) - this.hasData(a.data);
      });

      console.log(
        "排序后的图表列表:",
        sortedList.map((i) => ({
          title: i.title,
          hasData: this.hasData(i.data),
        }))
      );

      return sortedList;
    },
  },
  watch: {
    codedata: {
      handler(newVal) {
        this.tableData = newVal;
        this.updateBearingStateColors();
        this.updateStatusCount(); // 统计调用
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    updateBearingStateColors() {
      // 四个温度类型对应状态颜色key
      const statusMap = {
        主轴承温度: "innerRing",
        齿轮箱油温: "outerRing",
        发电机驱动端轴承温度: "rollingElement", // 改成“驱动端”对应数据字段
        发电机非驱动端轴承温度: "cage", // 改成“非驱动端”对应数据字段
      };

      // 颜色映射，正常绿，异常黄，无数据灰
      const colorMap = {
        normal: "#8ae359",
        danger: "#eecb5f",
        unknown: "#80808057",
      };

      const updatedColors = {};

      // 遍历四个温度类型，分别判断它们对应的tableData是否有异常或报警
      for (const [label, key] of Object.entries(statusMap)) {
        const items = this.tableData.filter(
          (item) => item.temp_channel === label
        );
        if (items.length === 0) {
          updatedColors[key] = colorMap.unknown; // 无数据，灰色
        } else {
          const hasDanger = items.some(
            (item) => item.status === "异常" || item.status === "危险"
          );
          updatedColors[key] = hasDanger ? colorMap.danger : colorMap.normal;
        }
      }

      // 合并更新状态颜色对象
      this.bearingStateColors = {
        ...this.bearingStateColors,
        ...updatedColors,
      };
    },
    updateStatusCount() {
      let normalCount = 0;
      let dangerCount = 0;

      this.tableData.forEach((item) => {
        if (item.status === "正常") {
          normalCount++;
        } else if (
          item.status === "异常" ||
          item.status === "危险" ||
          item.status === "报警"
        ) {
          dangerCount++;
        }
      });

      this.result = {
        normal: normalCount,
        danger: dangerCount,
      };
    },

    getStatusColor(tempName) {
      const map = {
        主轴承温度: "innerRing",
        齿轮箱油温: "outerRing",
        发电机驱动端轴承温度: "rollingElement",
        发电机非驱动端轴承温度: "cage",
      };
      // 根据tempName返回对应颜色
      return this.bearingStateColors[map[tempName]] || "#80808057";
    },

    hasData(data) {
      if (!data) return false;

      if (
        typeof data === "object" &&
        Array.isArray(data.timestamps) &&
        Array.isArray(data.values)
      ) {
        return data.timestamps.length > 0 || data.values.length > 0;
      }

      return false;
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.$emit("updatePage", this.currentPage);
    },
  },
};
</script>

<style lang="scss" scoped>
h4 {
  margin-bottom: 5px;
  font-weight: 600;
}
.TopBox {
  height: 280px;
  display: flex;
  justify-content: space-around;
  .leftdiv {
    width: 50%;
    display: flex;
    justify-content: space-around;
    .stateBox {
      .state {
        display: flex;
        flex-direction: column;
        justify-content: center; /* 整体居中 */
        align-items: center;
        height: 200px;
        gap: 20px; /* 控制间距 */
        p {
          width: 200px;
          height: 40px;
          background: rgb(227, 227, 227);
          color: rgb(50, 50, 50);
          text-align: center;
          align-content: center;
          font-weight: 600;
        }
      }
      .btn-auto {
        margin-top: 10px;
        width: 100%;
      }
    }
    .Btn {
      width: 50%;
      display: flex;
      flex-direction: column; /* 垂直排列 */
      justify-content: space-between; /* 顶部和底部对齐 */
      min-height: 100px; /* 确保容器有足够高度 */
      margin: 10px 0;
      .PText {
        display: flex;
        justify-content: space-around;

        span {
          display: flex;
          align-items: center;
          i {
            width: 30px;
            height: 15px;
            margin-right: 5px;
          }
          .color1 {
            background-color: #8ae359;
          }
          .color2 {
            background-color: #eecb5f;
          }
          .color3 {
            background-color: #f7715f;
          }
        }
      }
      margin: 10px 0;
      .minp {
        font-size: 12px;
        margin-top: auto; /* 自动推到最底部 */
      }
    }
  }
  .rightdiv {
    width: 50%;
    .fenye {
      display: flex;
      //justify-content: center;
      justify-content: space-between;
      margin: 5px 0;
      font-size: 12px;
      line-height: 30px;
      span {
        font-weight: 600;
      }
    }
  }
}

.bottomBox {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;

  border: 1px solid rgb(231, 231, 231);
  padding: 10px;
  .tu {
    width: 49%;
    height: 350px;
  }
}
::v-deep .el-table__cell {
  padding: 2px 0;
  font-size: 12px;
}

.MAXdiv {
  overflow: hidden;
  overflow-y: auto;
  height: 70vh;
}

.warning-text {
  color: #e6a23c; /* Element UI的warning颜色 */
  font-weight: bold;
}
</style>
