<template>
  <div class="grid-wrapper">
    <!-- 转置按钮 -->
    <el-button 
      type="text" 
      icon="el-icon-refresh-left" 
      size="mini"
      @click="toggleTranspose"
      class="transpose-btn"
    >
      {{ isTransposed ? '恢复行列' : '行列转置' }}
    </el-button>

    <!-- 核心滚动容器：列标尺 + 网格区域共享滚动条 -->
    <div class="grid-scroll-container" ref="scrollContainerRef">
      <!-- 滚动内容容器：列标尺 + 行标尺+网格 -->
      <div class="scroll-content">
        <!-- 列标尺（顶部） -->
        <div class="col-ruler">
          <div class="ruler-empty"></div>
          <div v-for="col in transposedLayerData.maxColumn" :key="`col-${layer}-${col}`" class="ruler-item">
            {{ col }}
          </div>
        </div>

        <!-- 行标尺 + 库位网格 -->
        <div class="row-grid-wrapper">
          <!-- 行标尺（左侧） -->
          <div class="row-ruler">
            <div v-for="row in transposedLayerData.maxRow" :key="`row-${layer}-${row}`" class="ruler-item">
              {{ row }}
            </div>
          </div>

          <!-- 库位网格 -->
          <div class="grid-container" :style="{ gridTemplateColumns: `repeat(${transposedLayerData.maxColumn}, 80px)` }">
            <!-- 库位格子 -->
            <div v-for="warehouse in transposedLayerData.warehouses" :key="warehouse.actualWarehouseId"
              class="warehouse-cell" :class="{ disabled: warehouse.isEnabled === 0 }"
              @click="handleCellClick(warehouse)">
              <div class="cell-code">{{ warehouse.actualWarehouseCode }}</div>
              <div class="cell-name">{{ warehouse.actualWarehouseName || '-' }}</div>
            </div>

            <!-- 空库位占位 -->
            <div class="warehouse-cell empty-cell" v-for="i in transposedLayerData.emptyCount" :key="`empty-${layer}-${i}`">
              <div class="cell-code">-</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 库位详情弹窗 -->
    <el-dialog title="库位详情" :visible.sync="dialogVisible" width="600px" destroy-on-close append-to-body center>
      <el-descriptions :column="2" border size="small" v-if="currentWarehouse">
        <el-descriptions-item label="库位编码">{{ currentWarehouse.actualWarehouseCode }}</el-descriptions-item>
        <el-descriptions-item label="库位名称">{{ currentWarehouse.actualWarehouseName || '无' }}</el-descriptions-item>
        <el-descriptions-item label="所属层级">{{ currentWarehouse.parsedInfo.layer || '未知' }}</el-descriptions-item>
        <!-- 弹窗内行列显示适配转置状态 -->
        <el-descriptions-item label="行号">
          {{ isTransposed ? currentWarehouse.parsedInfo.column : currentWarehouse.parsedInfo.row || '未知' }}
        </el-descriptions-item>
        <el-descriptions-item label="列号">
          {{ isTransposed ? currentWarehouse.parsedInfo.row : currentWarehouse.parsedInfo.column || '未知' }}
        </el-descriptions-item>
        <el-descriptions-item label="一级编码">{{ currentWarehouse.parsedInfo.warehouseFirst || '未知' }}</el-descriptions-item>
        <el-descriptions-item label="二级编码">{{ currentWarehouse.parsedInfo.warehouseSecond || '未知' }}</el-descriptions-item>
        <el-descriptions-item label="启用状态">
          <el-tag :type="currentWarehouse.isEnabled === 1 ? 'success' : 'danger'">
            {{ currentWarehouse.isEnabled === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="库位码">
          <QRCode :content="currentWarehouse.actualWarehouseId" size="60" />
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" span="2">{{ currentWarehouse.createTime || '无' }}</el-descriptions-item>
        <el-descriptions-item label="备注信息" span="2">{{ currentWarehouse.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template slot="footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from '@/components/QRCode/index.vue';

export default {
  name: "WarehouseGrid",
  components: { QRCode },
  props: {
    // 层号
    layer: {
      type: [String, Number],
      required: true
    },
    // 层数据
    layerData: {
      type: Object,
      required: true,
      default: () => ({
        maxRow: 0,
        maxColumn: 0,
        warehouses: [],
        emptyCount: 0
      })
    }
  },
  data() {
    return {
      // 弹窗状态
      dialogVisible: false,
      currentWarehouse: null,
      // 转置状态：false-原始布局 | true-行列转置
      isTransposed: false
    };
  },
  computed: {
    /**
     * 处理转置后的层数据（视图层映射，不修改原数据）
     */
    transposedLayerData() {
      const { maxRow, maxColumn, warehouses } = this.layerData;
      
      // 转置后的基础行列数
      const transMaxRow = this.isTransposed ? maxColumn : maxRow;
      const transMaxColumn = this.isTransposed ? maxRow : maxColumn;

      // 深拷贝库位数据，避免修改原数据
      const transWarehouses = JSON.parse(JSON.stringify(warehouses)).map(item => {
        // 转置时互换行列解析值
        if (this.isTransposed && item.parsedInfo) {
          const { row, column } = item.parsedInfo;
          item.parsedInfo.row = column;
          item.parsedInfo.column = row;
        }
        return item;
      });

      // 转置后重新排序（原：行→列 | 转置：列→行）
      transWarehouses.sort((a, b) => {
        if (a.parsedInfo.row !== b.parsedInfo.row) {
          return a.parsedInfo.row - b.parsedInfo.row;
        }
        return a.parsedInfo.column - b.parsedInfo.column;
      });

      // 转置后重新计算空占位数量
      const totalGrid = transMaxRow * transMaxColumn;
      const emptyCount = Math.max(0, totalGrid - transWarehouses.length);

      return {
        maxRow: transMaxRow,
        maxColumn: transMaxColumn,
        warehouses: transWarehouses,
        emptyCount
      };
    }
  },
  methods: {
    /**
     * 切换转置状态
     */
    toggleTranspose() {
      this.isTransposed = !this.isTransposed;
      // 重置弹窗选中状态（可选）
      this.dialogVisible = false;
      this.currentWarehouse = null;
    },

    /**
     * 点击库位格子展示详情
     */
    handleCellClick(warehouse) {
      this.currentWarehouse = warehouse;
      this.dialogVisible = true;
    }
  }
};
</script>

<style scoped lang="scss">
.grid-wrapper {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
  position: relative; // 为转置按钮提供定位上下文
  min-height: 100px; // 防止空数据时高度为0
}

// 转置按钮（固定位置）
.transpose-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 20; // 高于滚动容器
  color: #409eff;
  height: 30px;
  line-height: 30px;
  padding: 0 8px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 4px;

  &:hover {
    color: #1e88e5;
    background: #e8f4ff;
  }
}

// 核心滚动容器：横向滚动，列标尺+网格共享滚动条
.grid-scroll-container {
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  position: relative;
  padding-bottom: 8px; // 给滚动条留空间
  // 优化滚动条样式
  &::-webkit-scrollbar {
    height: 8px;
  }
  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }
  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
    &:hover {
      background: #a8a8a8;
    }
  }
  // 兼容非webkit浏览器
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

// 滚动内容容器：列标尺 + 行标尺+网格
.scroll-content {
  display: inline-block;
  background: #fff;
}

// 列标尺样式
.col-ruler {
  display: flex;
  height: 30px;
  line-height: 30px;
  background: #eef2f7;
  border-bottom: 1px solid #dcdfe6;

  .ruler-empty {
    width: 30px;
    text-align: center;
    font-weight: 600;
    color: #606266;
    border-right: 1px solid #dcdfe6;
    flex-shrink: 0;
  }

  .ruler-item {
    width: 80px;
    text-align: center;
    font-weight: 600;
    color: #606266;
    border-right: 1px solid #dcdfe6;
    box-sizing: border-box;
    flex-shrink: 0;
  }
}

// 行标尺 + 网格容器
.row-grid-wrapper {
  display: flex;
  width: 100%;
}

// 行标尺样式
.row-ruler {
  width: 30px;
  background: #eef2f7;
  border-right: 1px solid #dcdfe6;
  flex-shrink: 0;

  .ruler-item {
    height: 80px;
    line-height: 80px;
    text-align: center;
    font-weight: 600;
    color: #606266;
    border-bottom: 1px solid #dcdfe6;
    box-sizing: border-box;
  }
}

// 库位网格容器
.grid-container {
  display: grid;
  gap: 0;
  box-sizing: border-box;

  // 库位格子
  .warehouse-cell {
    height: 80px;
    width: 80px;
    border: 1px solid #e6e6e6;
    border-radius: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all 0.2s;
    box-sizing: border-box;
    margin: 0;

    &:hover {
      border-color: #409eff;
      background: #e8f4ff;
      z-index: 1;
    }

    &.disabled {
      background: #f5f5f5;
      color: #909399;
      cursor: not-allowed;

      &:hover {
        border-color: #e6e6e6;
        background: #f5f5f5;
      }
    }

    .cell-code {
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 4px;
    }

    .cell-name {
      font-size: 12px;
      color: #606266;
    }
  }

  // 空占位格子
  .empty-cell {
    background: #fafafa;
    border-style: solid;
    border-color: #e6e6e6;

    .cell-code {
      color: #c0c4cc;
    }
  }
}

// 弹窗样式优化
::v-deep(.el-descriptions) {
  .el-descriptions-item__label {
    font-weight: 500;
    color: #606266;
  }

  .el-descriptions-item__content {
    color: #303133;
  }
}
</style>