<template>
  <div>
    <div class="TopBox">
      <div class="leftdiv">
        <h4>轴承状态</h4>
        <div class="state">
          <p :style="{ backgroundColor: bearingStateColors.innerRing }">
            轴承内圈状态
          </p>
          <p :style="{ backgroundColor: bearingStateColors.outerRing }">
            轴承外圈状态
          </p>
          <p :style="{ backgroundColor: bearingStateColors.rollingElement }">
            轴承滚动体状态
          </p>
          <p :style="{ backgroundColor: bearingStateColors.cage }">
            轴承保持架状态
          </p>
        </div>

        <p class="PText">
          <span><i class="color1"></i>正常</span
          ><span><i class="color2"></i>报警</span
          ><span><i class="color3"></i>危险</span>
        </p>
        <div class="Btn">
          <el-button type="primary" size="small" @click="automaticDiagnosis"
            >自动诊断</el-button
          >
        </div>

        <h4>诊断步骤：</h4>
        <p class="minp">1、选择振动测点与起止时间，点击“查询”;</p>
        <p class="minp">2、对轴承“参数设置”输入相关信息;</p>
        <p class="minp">3、点击“自动诊断”输出最终轴承状态结果。</p>
      </div>

      <div class="rightdiv">
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          height="250"
        >
          <!-- <el-table-column fixed type="selection" width="55"> </el-table-column> -->
          <el-table-column prop="timeStamp" label="时间" align="center">
          </el-table-column>
          <el-table-column
            prop="samplingFrequency"
            label="采样频率(Hz)"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="rotationalSpeed"
            label="转速(rpm)"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="innerRingFault"
            label="轴承内圈故障"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="outerRingFault"
            label="轴承外圈故障"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="rollingElementFault"
            label="轴承滚动体故障"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="cageFault"
            label="轴承保持架故障"
            align="center"
          >
          </el-table-column>
        </el-table>
        <div class="fenye">
          <p><span>故障状态代码说明:</span>0代表正常，1代表报警，2代表危险</p>

          <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      layout="total, prev, pager, next, jumper"
      :total="totalCount"
      :page-size="10"
    ></el-pagination>
        </div>
      </div>
    </div>
    <div class="bottomBox">
      <div class="BtLeft">
        <h4>轴承状态趋势图</h4>
        <el-empty
          v-if="this.xData.length === 0 || this.yData.length === 0"
          description="暂无数据"
          style="padding: 17px 0"
        ></el-empty>
        <Eecharts
          v-else
          style="height: 250px"
          :xData="xData"
          :yData="yData"
          :yNames="[
            '轴承内圈状态',
            '轴承外圈状态',
            '轴承滚动体状态',
            '轴承保持架状态',
          ]"
          yAxisName="轴承故障状态"
        ></Eecharts>
      </div>
      <div class="BtRight">
        <h4>参数设置</h4>
        <div class="BtRightDiv">
          <p class="BtRightP">
            发动机到轴承测点转速传动比<span
              ><el-input v-model="transmissionRatio" size="small"     v-number-only></el-input
            ></span>
          </p>
          <h4>滚动轴承参数输入</h4>
          <div class="canshu">
            <p class="BtRightP">
              <span class="label-text">轴承节圆直径D(mm)</span>
              <span
                ><el-input
                  v-model="bearingPitchDiameter"
                  size="small"
                  v-number-only
                ></el-input
              ></span>
            </p>
            <p class="BtRightP">
              <span class="label-text">滚动体直径d(mm)</span>
              <span
                ><el-input
                  v-model="rollingElementDiameter"
                  size="small"
                  v-number-only
                ></el-input
              ></span>
            </p>
            <p class="BtRightP">
              <span class="label-text">滚动体个数Z(个)</span>
              <span
                ><el-input v-model="rollingElementCount" size="small"     v-number-only></el-input
              ></span>
            </p>
            <p class="BtRightP">
              <span class="label-text">接触角α(°)</span>
              <span
                ><el-input v-model="contactAngle" size="small"     v-number-only></el-input
              ></span>
            </p>
          </div>
          <h4>报警阈值输入</h4>
          <div class="canshu">
            <p class="BtRightP">
              <span class="label-text">振动速度报警阈值(mm/s)</span>
              <span
                ><el-input
                  v-model="vibrationSpeedAlarmThreshold"
                  size="small"
                  v-number-only
                ></el-input
              ></span>
            </p>
            <p class="BtRightP">
              <span class="label-text">振动速度危险阈值(mm/s)</span>
              <span
                ><el-input
                  v-model="vibrationSpeedDangerThreshold"
                  size="small"
                  v-number-only
                ></el-input
              ></span>
            </p>
            <p class="BtRightP">
              <span class="label-text">包络总值报警阈值(gE)</span>
              <span
                ><el-input
                  v-model="envelopeTotalAlarmThreshold"
                  size="small"
                  v-number-only
                ></el-input
              ></span>
            </p>
            <p class="BtRightP">
              <span class="label-text">包络总值危险阈值(gE)</span>
              <span
                ><el-input
                  v-model="envelopeTotalDangerThreshold"
                  size="small"
                  v-number-only
                ></el-input
              ></span>
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Eecharts from "./Eecharts.vue";
export default {
  components: { Eecharts },
  props: {
    codedata: {
      type: Array,
      default: () => [],
    },
    totalCount: {
      type: Number,
      default: 0,
    },
    totalPage: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      tableData: [],
      // 添加新的数据属性用于绑定输入框的值
      transmissionRatio: "",
      bearingPitchDiameter: "",
      rollingElementDiameter: "",
      rollingElementCount: "",
      contactAngle: "",
      vibrationSpeedAlarmThreshold: "",
      vibrationSpeedDangerThreshold: "",
      envelopeTotalAlarmThreshold: "",
      envelopeTotalDangerThreshold: "",
      // 分页

      currentPage: 1,
      total: 1,

      xData: [],
      yData: [],
      // 颜色判断
      bearingStateColors: {
        innerRing: "#80808057",
        outerRing: "#80808057",
        rollingElement: "#80808057",
        cage: "#80808057",
      },
      hasError: false, // 标志是否已经显示过错误提示
    };
  },
  created() {
    console.log(this.codedata, "11111111111111111111111111");

    // this.tableData = this.codedata;
  },
  watch: {
    codedata: {
      handler(newVal) {
        this.tableData = newVal;
      },
      immediate: true, // 组件创建时立刻执行一次
      deep: true, // 如果 codedata 是复杂对象，建议加上
    },
  },

  methods: {
    
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      
      this.currentPage = val // 子组件内部更新当前页
      this.$emit('updatePage', this.currentPage) // 通知父组件，把当前页传出去
    },
    automaticDiagnosis() {
      // 验证必填项
      const requiredFields = [
        { field: this.transmissionRatio, name: "发动机到轴承测点转速传动比" },
        { field: this.bearingPitchDiameter, name: "轴承节圆直径D(mm)" },
        { field: this.rollingElementDiameter, name: "滚动体直径d(mm)" },
        { field: this.rollingElementCount, name: "滚动体个数Z(个)" },
        { field: this.contactAngle, name: "接触角α(°)" },
        {
          field: this.vibrationSpeedAlarmThreshold,
          name: "振动速度报警阈值(mm/s)",
        },
        {
          field: this.vibrationSpeedDangerThreshold,
          name: "振动速度危险阈值(mm/s)",
        },
        {
          field: this.envelopeTotalAlarmThreshold,
          name: "包络总值报警阈值(gE)",
        },
        {
          field: this.envelopeTotalDangerThreshold,
          name: "包络总值危险阈值(gE)",
        },
      ];

      // 记录是否已弹出过错误提示
      let hasError = false;

      // 只检查必填项的字段是否为空
      // for (const { field, name } of requiredFields) {
      //   if (!field && !hasError) {
      //     // 弹出提示并标记已经出现错误提示
      //     this.$message.error(`${name} 是必填项`);
      //     hasError = true;  // 标记已经弹出过错误提示
      //     return;  // 停止执行后续逻辑
      //   }
      // }

      // 如果验证通过，继续执行后续逻辑
      const newProps = this.tableData.map(() => ({
        innerRingFault: Math.floor(Math.random() * 3).toString(),
        outerRingFault: Math.floor(Math.random() * 3).toString(),
        rollingElementFault: Math.floor(Math.random() * 3).toString(),
        cageFault: Math.floor(Math.random() * 3).toString(),
      }));

      this.tableData.forEach((row, index) => {
        this.$set(this.tableData, index, {
          ...row,
          ...newProps[index], // 用每一行自己生成的随机数
        });
      });

      // 更新颜色状态
      const fields = [
        { key: "innerRingFault", colorKey: "innerRing" },
        { key: "outerRingFault", colorKey: "outerRing" },
        { key: "rollingElementFault", colorKey: "rollingElement" },
        { key: "cageFault", colorKey: "cage" },
      ];

      fields.forEach(({ key, colorKey }) => {
        const values = newProps.map((item) => Number(item[key]));
        const maxVal = Math.max(...values);
        let color = "#80808057"; // 默认灰色
        if (maxVal === 0) color = "green"; // 无故障
        else if (maxVal === 1) color = "yellow"; // 警告
        else if (maxVal === 2) color = "red"; // 危险

        this.bearingStateColors[colorKey] = color; // 更新颜色
      });

      // 更新趋势图数据
      // 更新趋势图数据（用tableData，不是newProps）
      this.xData = this.tableData.map((item) => item.timeStamp);
      this.yData = fields.map(({ key }) =>
        this.tableData.map((item) => Number(item[key]))
      );
    },
  },
};
</script>

<style lang="scss" scoped>
h4 {
  margin-bottom: 5px;
  font-weight: 600;
}
.TopBox {
  height: 280px;
  display: flex;
  justify-content: space-around;
  .leftdiv {
    width: 29%;

    .state {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
      align-content: center;
      height: 100px;
      p {
        width: 150px;
        height: 40px;
        background: rgb(227, 227, 227);
        color: rgb(50, 50, 50);
        margin-bottom: 10px;
        text-align: center;
        align-content: center;
        font-weight: 600;
      }
    }
    .PText {
      display: flex;
      justify-content: space-around;
      span {
        display: flex;
        align-items: center;
        i {
          width: 30px;
          height: 15px;
          margin-right: 5px;
        }
        .color1 {
          background-color: green;
        }
        .color2 {
          background-color: yellow;
        }
        .color3 {
          background-color: red;
        }
      }
    }

    .Btn {
      display: flex;
      justify-content: space-around;
      margin: 10px 0;
    }
    .minp {
      font-size: 12px;
    }
  }
  .rightdiv {
    width: 69%;
    .fenye {
      display: flex;
      justify-content: space-between;
      margin: 5px 0;
      font-size: 12px;
      line-height: 30px;
      span {
        font-weight: 600;
      }
    }
  }
}

.bottomBox {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
  .BtLeft {
    border: 1px solid rgb(231, 231, 231);
    width: 49%;
    padding: 10px;
  }
  .BtRight {
    width: 49%;
    border: 1px solid rgb(231, 231, 231);
    padding: 10px;
    .BtRightDiv {
      padding: 0 10px;
      h4 {
        font-size: 14px;
      }
      .BtRightP {
        line-height: 30px;
        font-size: 12px;
        display: flex;
        margin-bottom: 5px;
        width: 50%;
        span {
          margin-left: 10px;
          .el-input {
            width: 100px;
          }
        }
        .label-text {
          width: 140px;
        }
      }
      .canshu {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
      }
    }
  }
}
::v-deep .el-table__cell {
  padding: 2px 0;
  font-size: 12px;
}
</style>