<template>
  <div class="iot-status-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" class="search-form">
      <el-form-item>
        <el-input
          v-model="trayCode"
          placeholder="请输入托盘号"
          clearable
          size="medium"
          @keyup.enter.native="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 加载状态 -->
    <div v-loading="loading" class="result-area">
      <!-- 无数据提示 -->
      <el-empty v-if="!loading && matrixData.length === 0" description="暂无数据，请搜索托盘号" />

      <!-- 矩阵网格 8行 x 9列 -->
      <div v-else class="matrix-grid">
        <div
          v-for="(row, rowIndex) in matrixData"
          :key="'row-' + rowIndex"
          class="matrix-row"
        >
          <div
            v-for="(cell, colIndex) in row"
            :key="'col-' + colIndex"
            class="matrix-cell"
          >
            <!-- 有设备数据显示圆点 -->
            <el-tooltip
              v-if="cell"
              placement="top"
              :content="tooltipContent(cell)"
              effect="dark"
            >
              <div
                class="dot"
                :class="{
                  'dot-green': isNormal(cell),
                  'dot-red': !isNormal(cell)
                }"
              ></div>
            </el-tooltip>
            <!-- 无设备数据展示空位（灰色小圆） -->
            <div v-else class="dot dot-empty"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { realTimeObtainIotStatusByTrayCode } from '@/api/palletDeviceBinding/binding'

export default {
  name: 'SearchIotStatus',
  data() {
    return {
      trayCode: '',
      loading: false,
      deviceList: [], // 接口返回的原始数组
      matrixData: [] // 8行 x 9列的二维数组
    }
  },
  methods: {
    /** 搜索 */
    handleSearch() {
      if (!this.trayCode.trim()) {
        this.$message.warning('请输入托盘号')
        return
      }
      this.loading = true
      realTimeObtainIotStatusByTrayCode(this.trayCode.trim())
        .then(res => {
          this.deviceList = res.data || []
          if (this.deviceList.length === 0) {
            this.$message.info('未查询到设备信息')
          }
          this.buildMatrix()
        })
        .catch(err => {
          this.$message.error('查询失败：' + (err.message || '未知错误'))
          this.deviceList = []
          this.matrixData = []
        })
        .finally(() => {
          this.loading = false
        })
    },

    /** 根据 deviceList 构建 8行 x 9列 的矩阵 */
    buildMatrix() {
      // 初始化 8行 x 9列，全部为 null
      const rows = 8
      const cols = 9
      const matrix = Array.from({ length: rows }, () => Array(cols).fill(null))

      // 填充数据：row 和 col 从 1 开始，映射到索引 0 开始
      this.deviceList.forEach(item => {
        const rowIdx = (item.row || 0) - 1
        const colIdx = (item.col || 0) - 1
        // 仅当行列在有效范围内才填充
        if (rowIdx >= 0 && rowIdx < rows && colIdx >= 0 && colIdx < cols) {
          matrix[rowIdx][colIdx] = item
        }
      })

      this.matrixData = matrix
    },

    /** 判断该设备是否正常（网络和IOT均为正常） */
    isNormal(cell) {
      if (!cell) return false
      const networkOk = cell.networkStatus === 1
      const iotOk = cell.iotStatus === 1
      return networkOk && iotOk
    },

    /** 生成悬停提示内容 */
    tooltipContent(cell) {
      if (!cell) return ''
      const rows = [
        `行：${cell.row ?? '-'}`,
        `列：${cell.col ?? '-'}`,
        `设备编号：${cell.motherboardCode || '-'}`,
        `NB码：${cell.nbCode || '-'}`,
        `网络状态：${this.formatNetworkStatus(cell.networkStatus)}`,
        `IOT状态：${this.formatIotStatus(cell.iotStatus)}`
      ]
      return rows.join('\n')
    },

    /** 格式化网络状态显示文本（用于tooltip） */
    formatNetworkStatus(status) {
      if (status === null || status === undefined) return '空'
      return status === 1 ? '正常' : '异常'
    },

    /** 格式化IOT状态显示文本（用于tooltip） */
    formatIotStatus(status) {
      if (status === null || status === undefined) return '空'
      const map = {
        0: '异常',
        1: '正常',
        2: 'Nb码为空',
        3: '网络状态异常'
      }
      return map[status] || '未知'
    }
  }
}
</script>

<style lang="scss" scoped>
.iot-status-container {
  padding: 20px;

  .search-form {
    margin-bottom: 20px;
    text-align: center;
  }

  .result-area {
    min-height: 200px;
  }

  .matrix-grid {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    margin-top: 10px;
  }

  .matrix-row {
    display: flex;
    gap: 8px;
  }

  .matrix-cell {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .dot {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    border: 2px solid #dcdfe6;
    background-color: #f5f7fa;
    transition: all 0.2s;
    cursor: default;

    &.dot-green {
      background-color: #67c23a;
      border-color: #67c23a;
      box-shadow: 0 2px 6px rgba(103, 194, 58, 0.3);
    }

    &.dot-red {
      background-color: #f56c6c;
      border-color: #f56c6c;
      box-shadow: 0 2px 6px rgba(245, 108, 108, 0.3);
    }

    &.dot-empty {
      background-color: #e4e7ed;
      border-color: #c0c4cc;
      opacity: 0.4;
    }

    &:hover {
      transform: scale(1.1);
    }
  }
}
</style>
