<template>
  <div class="gear-container">
    <div class="gear-header">
      <div class="header-title">
        <p class="title">齿轮诊断状态总览</p>
        <p class="sub-title">共 {{ statusSummary.total }} 个监测点</p>
      </div>
      <div class="header-stat">
        <div
          v-for="item in statusCards"
          :key="item.key"
          class="stat-item"
          :class="`is-${item.key}`"
        >
          <el-divider direction="vertical" class="header-divider"></el-divider>
          <div class="stat-item-content">
            <div class="icon-wrap">
              <i :class="item.icon"></i>
            </div>
            <div class="stat-content">
              <p class="label">{{ item.label }}</p>
              <p class="count">{{ item.count }}</p>
              <p class="ratio">占比 {{ item.ratio }}</p>
            </div>
          </div>
          <div class="stat-nobox"></div>
        </div>
      </div>
    </div>
    <div class="gear">
      <div class="TopBox">
        <div class="rightdiv">
          <div class="monitor-panel">
            <h4>齿轮监测点列表</h4>
            <div v-if="!tableData.length" class="monitor-empty">
              <el-empty description="暂无监测点数据"></el-empty>
            </div>
            <div v-else class="monitor-list">
              <div
                v-for="(row, index) in tableData"
                :key="row.id || `${row.functionTypeName}-${index}`"
                class="monitor-item"
                :class="{
                  'is-active':
                    selectedFunctionTypeName &&
                    selectedFunctionTypeName === rowFunctionTypeName(row),
                }"
                @click="selectMonitorPoint(row)"
              >
                <div
                  class="index-badge"
                  :class="`is-${statusTagType(row.status)}`"
                >
                  {{ bearingTableIndex(index) }}
                </div>
                <div class="item-main">
                  <p class="item-name">
                    {{ monitorDisplayName(row) }}
                  </p>
                  <p class="item-line">监测类型：{{ monitorTypeText(row) }}</p>
                  <!-- <p class="item-line">型号：{{ row.brandType }}</p>
                  <p class="item-line">品牌：{{ row.brand }}</p> -->
                </div>
                <div class="item-right">
                  <span
                    class="status-pill"
                    :class="`is-${statusTagType(row.status)}`"
                  >
                    <i class="status-dot"></i>
                    {{ formatStatusText(row.status) }}
                  </span>
                  <!-- <el-button
                    type="text"
                    class="detail-btn"
                    @click.stop="handleDetail(row)"
                  >
                    <i class="el-icon-arrow-right"></i>
                  </el-button> -->
                </div>
              </div>
            </div>
          </div>
          <div class="fenye">
            <p></p>
            <el-pagination
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              layout="total, prev, pager, next"
              :total="totalCount"
              :page-size="pageSize"
              small
            ></el-pagination>
          </div>
        </div>
      </div>
      <div class="bottomBox">
        <div class="BtLeft">
          <h4>齿轮状态趋势图：</h4>
          <p class="status-legend">
            <span class="legend-label">状态码说明:</span>
            <span class="legend-item is-normal"
              ><i class="legend-dot"></i>0 正常</span
            >
            <span class="legend-item is-warning"
              ><i class="legend-dot"></i>1 报警</span
            >
            <span class="legend-item is-danger"
              ><i class="legend-dot"></i>2 危险</span
            >
          </p>
          <el-empty
            v-if="!filteredTrendChartList.length"
            description="暂无数据"
            style="padding: 46px 0"
          ></el-empty>
          <div v-else class="mpoint-charts">
            <el-carousel :key="trendCarouselKey">
              <el-carousel-item
                v-for="(chart, index) in filteredTrendChartList"
                :key="`${chart.title}-${index}`"
              >
                <div class="mpoint-chart-item">
                  <!-- <p class="mpoint-chart-title">{{ chart.title }}</p> -->
                  <Eecharts
                    style="height: 260px"
                    :xData="chart.xData"
                    :yData="chart.yData"
                    :yNames="chart.yNames"
                    yAxisName="故障状态"
                    :jumpContext="chart.jumpContext"
                  ></Eecharts>
                </div>
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import Eecharts from "./mpointEecharts.vue";
import bingTwo from "./bingTwo.vue";
export default {
  components: { Eecharts, bingTwo },
  props: {
    codedata: {
      type: Array,
      default: () => [],
    },
    totalCount: {
      type: Number,
      default: 0,
    },
    totalPage: {
      type: Number,
      default: 0,
    },
    fieldCode: {
      type: String,
      default: "",
    },
    windTurbineNumber: {
      type: String,
      default: "",
    },
    echartsdata: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      tableData: [],
      // 添加新的数据属性用于绑定输入框的值
      transmissionRatio: "",
      bearingPitchDiameter: "",
      rollingElementDiameter: "",
      rollingElementCount: "",
      contactAngle: "",
      vibrationSpeedAlarmThreshold: "",
      vibrationSpeedDangerThreshold: "",
      envelopeTotalAlarmThreshold: "",
      envelopeTotalDangerThreshold: "",
      // 分页
      currentPage: 1,
      total: 1,
      pageSize: 10,
      xData: [],
      yData: [],
      // 颜色判断
      bearingStateColors: {
        innerRing: "#80808057",
        outerRing: "#80808057",
        rollingElement: "#80808057",
        cage: "#80808057",
      },
      hasError: false, // 标志是否已经显示过错误提示
      result: {},
      dialogVisible: false,
      loading: false, // 控制加载状态
      statistics: {},
      trendChartList: [],
      selectedFunctionTypeName: "",
      selectedMonitorId: "",
    };
  },
  created() {},
  watch: {
    codedata: {
      handler(newVal) {
        this.tableData = newVal;
        const exists = this.tableData.some(
          (row) =>
            this.resolveFunctionTypeNameByRow(row) ===
            this.selectedFunctionTypeName,
        );
        if (!exists) {
          if (this.tableData.length) {
            this.selectedFunctionTypeName = this.resolveFunctionTypeNameByRow(
              this.tableData[0],
            );
            this.selectedMonitorId = this.tableData[0]?.id
              ? String(this.tableData[0].id)
              : "";
          } else {
            this.selectedFunctionTypeName = "";
            this.selectedMonitorId = "";
          }
        }
      },
      immediate: true, // 组件创建时立刻执行一次
      deep: true, // 如果 codedata 是复杂对象，建议加上
    },
    echartsdata: {
      handler(newVal) {
        const list = Array.isArray(newVal) ? newVal : [];
        this.trendChartList = list
          .map((item) => {
            const title = item?.pointNameCn || "未命名测点";
            const inner = Array.isArray(item?.innerDatas)
              ? item.innerDatas
              : [];
            const xData = inner.map((d) => d?.timeStamp || "");
            const seriesY = inner.map((d) => {
              const v = d?.status;
              return v === null || v === undefined || v === ""
                ? null
                : Number(v);
            });
            const pointIds = inner.map((d) => d?.id);
            const pointRows = inner.map((d) => {
              const pid = d?.id;
              return (
                this.tableData.find((r) => String(r?.id) === String(pid)) ||
                null
              );
            });
            const normalizedFunctionTypeName = this.normalizeFunctionTypeName(
              item?.functionTypeName ||
                inner.find((d) => d?.functionTypeName)?.functionTypeName ||
                pointRows.find((r) => r?.functionTypeName)?.functionTypeName ||
                item?.functionTypeNameCn ||
                item?.pointNameCn ||
                item?.mesurePointName ||
                "",
            );
            return {
              title,
              xData,
              yData: [seriesY],
              yNames: [title],
              functionTypeName: normalizedFunctionTypeName,
              jumpContext: {
                companyCode: this.fieldCode,
                windCode: this.fieldCode,
                windTurbineNumber: this.windTurbineNumber,
                itemKey: item?.itemKey ?? item?.item_key,
                functionTypeName: normalizedFunctionTypeName,
                id: item?.id,
                mesurePointName: item?.mesurePointName || title,
                detectionPointCn: item?.pointNameCn || title,
                rotationalSpeed: item?.rotationalSpeed,
                samplingFrequency: item?.samplingFrequency,
                otherData:
                  item?.otherData && typeof item.otherData === "object"
                    ? { ...item.otherData }
                    : undefined,
                pointIds,
                pointRows,
              },
            };
          })
          .filter((it) => it.xData.length);
        if (!this.selectedFunctionTypeName && this.tableData.length) {
          this.selectedFunctionTypeName = this.resolveFunctionTypeNameByRow(
            this.tableData[0],
          );
          this.selectedMonitorId = this.tableData[0]?.id
            ? String(this.tableData[0].id)
            : "";
        }
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    statusSummary() {
      const rows = Array.isArray(this.tableData) ? this.tableData : [];
      const total = rows.length;
      const summary = { total, normal: 0, warning: 0, danger: 0 };
      rows.forEach((row) => {
        const code = Number(row?.status);
        if (code === 0) summary.normal += 1;
        else if (code === 1) summary.warning += 1;
        else if (code === 2) summary.danger += 1;
      });
      return summary;
    },
    statusCards() {
      const { total, normal, warning, danger } = this.statusSummary;
      const toRatio = (count) =>
        total > 0 ? `${((count / total) * 100).toFixed(0)}%` : "0%";
      return [
        {
          key: "normal",
          label: "正常",
          count: normal,
          ratio: toRatio(normal),
          icon: "el-icon-check",
        },
        {
          key: "warning",
          label: "报警",
          count: warning,
          ratio: toRatio(warning),
          icon: "el-icon-warning-outline",
        },
        {
          key: "danger",
          label: "危险",
          count: danger,
          ratio: toRatio(danger),
          icon: "el-icon-warning",
        },
      ];
    },
    filteredTrendChartList() {
      const selected = this.selectedFunctionTypeName;
      if (!selected) return this.trendChartList;
      return this.trendChartList.filter(
        (chart) => this.chartFunctionTypeName(chart) === selected,
      );
    },
    trendCarouselKey() {
      return `trend-${this.selectedFunctionTypeName || "all"}`;
    },
  },

  methods: {
    normalizeFunctionTypeName(name) {
      return typeof name === "string" ? name.trim() : "";
    },
    rowFunctionTypeName(row) {
      return this.normalizeFunctionTypeName(
        row?.functionTypeName ? String(row.functionTypeName) : "",
      );
    },
    resolveFunctionTypeNameByRow(row) {
      const direct = this.rowFunctionTypeName(row);
      if (direct) return direct;
      const rowId =
        row?.id !== undefined && row?.id !== null ? String(row.id) : "";
      if (!rowId) return "";
      const chart = this.trendChartList.find((item) => {
        const rows = item?.jumpContext?.pointRows;
        if (!Array.isArray(rows)) return false;
        return rows.some(
          (r) =>
            r?.id !== undefined && r?.id !== null && String(r.id) === rowId,
        );
      });
      return chart ? this.chartFunctionTypeName(chart) : "";
    },
    monitorDisplayName(row) {
      return row?.functionTypeName || row?.detectionPointCn || "-";
    },
    chartFunctionTypeName(chart) {
      return this.normalizeFunctionTypeName(
        chart?.jumpContext?.functionTypeName
          ? String(chart.jumpContext.functionTypeName)
          : "",
      );
    },
    statusTagType(status) {
      const code = Number(status);
      if (code === 0) return "success";
      if (code === 1) return "warning";
      if (code === 2) return "danger";
      return "info";
    },
    formatStatusText(status) {
      if (status === null || status === undefined || status === "") return "/";
      const code = Number(status);
      if (code === 0) return "正常";
      if (code === 1) return "报警";
      if (code === 2) return "危险";
      if (code === -1) return "未定义";
      return String(status);
    },
    monitorTypeText(row) {
      return "振动-加速度";
    },
    selectMonitorPoint(row) {
      this.selectedMonitorId =
        row?.id !== undefined && row?.id !== null ? String(row.id) : "";
      this.selectedFunctionTypeName = this.resolveFunctionTypeNameByRow(row);
    },
    handleDetail(row) {
      const itemKey = row.itemKey ?? row.item_key;
      const payload = {
        /** 与故障诊断页「单位」一致（selecttree 的 companyCode / codeNumber） */
        companyCode: this.fieldCode,
        windCode: this.fieldCode,
        windTurbineNumber: this.windTurbineNumber,
        itemKey,
        id: row.id,
        mesurePointName: row.mesurePointName,
        detectionPointCn: row.detectionPointCn,
        timeStamp: row.timeStamp,
        /** 频谱特征线需要 RPM → Hz；接口字段可能为 rotationalSpeed / otherData.RPM */
        rotationalSpeed: row.rotationalSpeed,
        samplingFrequency: row.samplingFrequency,
        otherData:
          row.otherData && typeof row.otherData === "object"
            ? { ...row.otherData }
            : undefined,
      };
      try {
        sessionStorage.setItem(
          "healthVibrationDeepLink",
          JSON.stringify(payload),
        );
      } catch (e) {
        console.error(e);
      }
      this.$router.push({ path: "/home/health/vibration" });
    },
    bearingTableIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    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}`);
      // setTimeout(() => {
      //   this.automaticDiagnosis();
      // }, 500);
      this.currentPage = val; // 子组件内部更新当前页
      this.$emit("updatePage", this.currentPage); // 通知父组件，把当前页传出去
    },

    // automaticDiagnosis() {
    //   if (this.tableData.length === 0) {
    //     this.$message.warning("当前没有数据，无法进行诊断");
    //     this.loading = false; // 确保关闭 loading 状态
    //     return; // 直接返回，不发请求
    //   }
    //   this.loading = true;
    // },

    reset() {
      this.tableData = [];
      this.xData = [];
      this.yData = [];
      this.statistics = {};
      this.result = {};
      this.trendChartList = [];
      this.selectedFunctionTypeName = "";
      this.selectedMonitorId = "";
      this.bearingStateColors = {
        innerRing: "#80808057",
        outerRing: "#80808057",
        rollingElement: "#80808057",
        cage: "#80808057",
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.gear-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: -10px;
}

.gear-header {
  display: flex;
  align-items: stretch;
  // border: 1px solid #ebeef5;
  border-radius: 12px;
  background: #f5f7fa5e;
  overflow: hidden;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);

  .header-title {
    width: 230px;
    padding: 16px 18px;
    // border-right: 1px solid #ebeef5;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .title {
      margin: 0;
      font-size: 18px;
      font-weight: 700;
      color: #303133;
    }
    .sub-title {
      margin: 6px 0 0;
      font-size: 13px;
      color: #909399;
    }
  }

  .header-stat {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    ::v-deep .header-divider.el-divider--vertical {
      height: 48px; /* 分割线长度 */
      margin: 0 8px 0 0; /* 与图标间距 */
      width: 1px; /* 粗细 */
      background-color: #dcdfe65e; /* 颜色 */
    }
    .stat-item {
      padding: 10px 18px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      // border-right: 1px solid #ebeef5;
      &:last-child {
        border-right: 0;
      }
      .icon-wrap {
        width: 42px;
        height: 42px;
        border-radius: 50%;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22px;
      }
      .stat-item-content {
        display: flex;
        align-items: center;
        gap: 10px;
      }
      .stat-content {
        .label,
        .count,
        .ratio {
          margin: 0;
          line-height: 1.2;
        }
        .label {
          font-size: 14px;
          color: #303133;
          font-weight: 500;
        }
        .count {
          margin-top: 2px;
          font-size: 30px;
          font-weight: 700;
          color: #303133;
        }
        .ratio {
          margin-top: 2px;
          font-size: 12px;
          color: #909399;
        }
      }
      &.is-normal .icon-wrap {
        background: #008080;
      }
      &.is-warning .icon-wrap {
        background: #e6a23c;
      }
      &.is-danger .icon-wrap {
        background: #f56c6c;
      }
    }
  }
}

.gear {
  height: 100%;
  display: flex;
  justify-content: space-between;
  // flex-direction: column;
  gap: 10px;
  .TopBox {
    width: 40%;
  }
  .bottomBox {
    width: 59%;
    height: 360px;
  }
}
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: 150px;
          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: 100%;
    .monitor-panel {
      // border: 1px solid #e4e7ed;
      border-radius: 14px;
      // background: #f5f7fa;
      padding: 14px;
      // min-height: 360px;
      height: 360px;
      overflow-y: auto;
      box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
    }
    .panel-title {
      margin: 0 0 12px;
      font-size: 18px;
      font-weight: 700;
      color: #1f2d3d;
    }
    .monitor-empty {
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 260px;
      background: #fff;
      border-radius: 10px;
    }
    .monitor-list {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
    .monitor-item {
      position: relative;
      display: flex;
      align-items: center;
      gap: 14px;
      border: 1px solid #e4e7ed;
      border-radius: 10px;
      background: #fff;
      padding: 14px 16px;
      cursor: pointer;
      transition: all 0.2s ease;
      &.is-active {
        background: #f0f5f7;
      }
      &.is-active::before {
        content: "";
        position: absolute;
        left: 0;
        top: 10px;
        bottom: 10px;
        width: 4px;
        background: #74727224;
        box-shadow: 0 0 0 2px #24a16600 inset;
        border-radius: 0 4px 4px 0;
      }
    }
    .index-badge {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      color: #fff;
      font-size: 16px;
      font-weight: 700;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      &.is-success {
        background: #008080;
      }
      &.is-warning {
        background: #e6a23c;
      }
      &.is-danger {
        background: #f56c6c;
      }
      &.is-info {
        background: #909399;
      }
    }
    .item-main {
      flex: 1;
      min-width: 0;
      .item-name {
        margin: 0 0 8px;
        font-size: 16px;
        font-weight: 700;
        color: #1f2d3d;
      }
      .item-line {
        margin: 0;
        font-size: 14px;
        line-height: 1.5;
        color: #6b7280;
      }
    }
    .item-right {
      display: flex;
      align-items: center;
      gap: 12px;
      .detail-btn {
        margin-left: 2px;
        font-size: 22px;
        color: #909399;
      }
    }
    .status-pill {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      border-radius: 12px;
      padding: 10px 16px;
      font-size: 16px;
      font-weight: 700;
      line-height: 1;
      .status-dot {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background: currentColor;
      }
      &.is-success {
        color: #21a366;
        background: #e7f6ee;
      }
      &.is-warning {
        color: #d48806;
        background: #fff6e5;
      }
      &.is-danger {
        color: #f04438;
        background: #ffebee;
      }
      &.is-info {
        color: #606266;
        background: #f4f4f5;
      }
    }

    .fenye {
      display: flex;
      justify-content: flex-end;
      margin: 10px 0 0;
      font-size: 12px;
      line-height: 30px;

      span {
        font-weight: 600;
      }
    }
  }
}

.bottomBox {
  display: flex;
  justify-content: space-around;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  .BtLeft {
    // border: 1px solid rgb(231, 231, 231);
    width: 100%;
    padding: 10px 20px;
  }

  .BtRight {
    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;
      }
    }
  }

  .dialog-footer {
    margin-top: 20px;
    text-align: right;
  }
}

.mpoint-charts {
  // display: grid;
  // grid-template-columns: repeat(2, minmax(0, 1fr));
  // gap: 16px;
  display: block;
}

.mpoint-chart-item {
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 8px 10px;
}

.mpoint-chart-title {
  margin: 0 0 6px;
  font-size: 13px;
  color: #303133;
}

.status-legend {
  margin: 4px 0 8px;
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 12px;
  .legend-label {
    color: #606266;
  }
  .legend-item {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    .legend-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: currentColor;
    }
    &.is-normal {
      color: #008080;
    }
    &.is-warning {
      color: #e6a23c;
    }
    &.is-danger {
      color: #f56c6c;
    }
  }
}

/* el-carousel 指示器颜色（Element UI 2.x） */
::v-deep .el-carousel__indicator .el-carousel__button {
  background-color: rgba(144, 147, 153, 0.45); /* 默认灰 */
  opacity: 1; /* Element UI 默认会用 opacity 控制，这里统一用背景色 */
}
::v-deep .el-carousel__indicator.is-active .el-carousel__button {
  background-color: #24a166; /* 激活：主色蓝（可改） */
}
::v-deep .el-carousel__indicator:hover .el-carousel__button {
  background-color: #24a166aa; /* hover */
}
::v-deep .el-carousel__indicators--horizontal {
  bottom: -10px !important;
}
@media (max-width: 1200px) {
  .mpoint-charts {
    grid-template-columns: 1fr;
  }
}

::v-deep .el-table__cell {
  padding: 2px 0;
  font-size: 12px;
}
</style>
