<template>
  <div class="multi-layer-grid" @click="closeContextMenu" @keydown.esc="closeContextMenu">
    <!-- 顶部列标尺 -->
    <div class="col-ruler" :style="{ '--cell-width': `${cellWidth}px` }">
      <div class="ruler-empty"></div>
      <div v-for="col in sortedColumnKeys" :key="`col-${col}`" class="ruler-item">
        {{ col }}
      </div>
    </div>

    <!-- 左侧行标尺 + 库位网格 -->
    <div class="row-grid-wrapper">
      <!-- 左侧行标尺（高度固定） -->
      <div class="row-ruler" :style="{ '--total-height': `${rulerTotalHeight}px` }">
        <div v-for="row in rulerMaxRow" :key="`row-${row}`" class="ruler-item">
          {{ row }}
        </div>
      </div>

      <!-- 网格容器（列→左右容器→格子） -->
      <div class="grid-container" :style="{
        '--half-cell-width': `${halfCellWidth}px`,
        '--cell-width': `${cellWidth}px`,
        '--column-count': sortedColumnKeys.length * 2,
        '--total-height': `${rulerTotalHeight}px`
      }">
        <!-- 逐列渲染：每列对应左右两个容器 -->
        <template v-for="column in sortedColumnKeys">
          <!-- 左容器：承载当前列的layer1库位 -->
          <div 
            class="column-container layer-1-container"
            :style="{
              gridRow: '1 / -1',
              gridColumn: `${(column - 1) * 2 + 1} / ${(column - 1) * 2 + 2}`,
              '--item-height': `${getWarehouseCellHeight(column)}px`
            }"
          >
            <!-- 左容器内渲染layer1的单个格子（无偏移） -->
            <div 
              v-for="warehouse in getColumnLayerWarehouses(column, 1)" 
              :key="`warehouse-1-${warehouse.actualWarehouseId}`"
              class="warehouse-cell layer-1" 
              :class="{ disabled: warehouse.isEnabled === 0 }" 
              @click="handleCellClick(warehouse)"
              @contextmenu.prevent="(e) => openContextMenu(e, warehouse)"
            >
              <div class="cell-name">
                <div class="cell-line1">{{ warehouse.actualWarehouseName || '-' }}</div>
                <div class="cell-line2">{{ warehouse.currentCoilNo || '-' }}</div>
              </div>
            </div>
          </div>

          <!-- 右容器：承载当前列的layer2库位（核心修改：新增高度计算） -->
          <div 
            class="column-container layer-2-container"
            :style="{
              gridRow: '1 / -1',
              gridColumn: `${(column - 1) * 2 + 2} / ${(column - 1) * 2 + 3}`,
              '--item-height': `${getWarehouseCellHeight(column)}px`,
              '--offset-value': `${getWarehouseCellHeight(column) * 0.5}px`,
              // 新增：第二层容器高度 = 格子总高度 + 偏移量（半个格子）
              height: `${(getColumnLayerWarehouses(column, 2).length * getWarehouseCellHeight(column))}px`
            }"
          >
            <!-- 右容器内渲染layer2的单个格子（向下偏移半个高度） -->
            <div 
              v-for="warehouse in getColumnLayerWarehouses(column, 2)" 
              :key="`warehouse-2-${warehouse.actualWarehouseId}`"
              class="warehouse-cell layer-2" 
              :class="{ disabled: warehouse.isEnabled === 0 }" 
              :style="{
                transform: `translateY(var(--offset-value))`
              }"
              @click="handleCellClick(warehouse)"
              @contextmenu.prevent="(e) => openContextMenu(e, warehouse)"
            >
              <div class="cell-name">
                <div class="cell-line1">{{ warehouse.actualWarehouseName || '-' }}</div>
                <div class="cell-line2">{{ warehouse.currentCoilNo || '-' }}</div>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- 自定义右键菜单 -->
    <div 
      v-if="contextMenuVisible"
      class="custom-contextmenu"
      :style="{
        top: `${contextMenuTop}px`,
        left: `${contextMenuLeft}px`,
        zIndex: 9999
      }"
      @click.stop
    >
      <ul>
        <li @click="handleContextMenuClick('view')">查看详情</li>
        <li class="menu-divider"></li>
        <li 
          @click="handleContextMenuClick('delete')"
          :class="{ disabled: currentContextWarehouse.isEnabled === 0 }"
        >
          删除库位
        </li>
        <li class="menu-divider"></li>
        <li @click="handleContextMenuClick('split')" v-if="currentContextWarehouse.splitStatus == 0">拆分整列</li>
        <li @click="handleContextMenuClick('merge')" v-if="currentContextWarehouse.splitStatus == 1">合并整列</li>
      </ul>
    </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.currentCoilNo || '无' }}</el-descriptions-item>
        <el-descriptions-item label="所属层级">{{ currentWarehouse.parsedInfo.layer || '未知' }}</el-descriptions-item>
        <el-descriptions-item label="行号">{{ currentWarehouse.parsedInfo.row || '未知' }}</el-descriptions-item>
        <el-descriptions-item label="列号">{{ 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 ? '未占用' : currentWarehouse.currentCoilNo }}
          </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.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';
import { Message } from 'element-ui';

export default {
  name: "SteelCoilWarehouse",
  components: {
    QRCode
  },
  props: {
    columns: {
      type: Object,
      required: true,
      default: () => ({})
    }
  },
  data() {
    return {
      dialogVisible: false,
      currentWarehouse: null,
      containerWidth: 0,
      resizeTimer: null,
      // 右键菜单
      contextMenuVisible: false,
      contextMenuTop: 0,
      contextMenuLeft: 0,
      currentContextWarehouse: null,
      // 标尺配置
      rulerRowHeight: 80,
      rulerMaxRow: 0
    };
  },
  computed: {
    // 排序后的列号（数字升序）
    sortedColumnKeys() {
      return Object.keys(this.columns)
        .map(key => Number(key))
        .sort((a, b) => a - b);
    },
    // 标尺总高度
    rulerTotalHeight() {
      return this.rulerMaxRow * this.rulerRowHeight;
    },
    // 列宽度（原始列）
    cellWidth() {
      if (!this.containerWidth || this.sortedColumnKeys.length === 0) return 60;
      const availableWidth = Math.max(0, this.containerWidth - 30);
      return availableWidth / this.sortedColumnKeys.length;
    },
    // 半列宽度（小列/容器宽度）
    halfCellWidth() {
      return this.cellWidth / 2;
    }
  },
  watch: {
    // 初始化标尺最大行数（仅一次）
    columns: {
      immediate: true,
      handler(newVal) {
        if (this.rulerMaxRow === 0 && Object.keys(newVal).length > 0) {
          const allMaxRows = Object.values(newVal).map(col => col.maxRow);
          this.rulerMaxRow = allMaxRows.length > 0 ? Math.max(...allMaxRows) : 0;
        }
        this.calcContainerWidth();
      }
    }
  },
  mounted() {
    this.calcContainerWidth();
    window.addEventListener('resize', this.handleResize);
    document.addEventListener('click', this.closeContextMenu);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
    document.removeEventListener('click', this.closeContextMenu);
    clearTimeout(this.resizeTimer);
  },
  methods: {
    // 获取指定列、指定层的库位（按行号排序）
    getColumnLayerWarehouses(column, layer) {
      const columnData = this.columns[column];
      if (!columnData) return [];
      const layerKey = `layer${layer}`;
      return columnData[layerKey].sort((a, b) => a.parsedInfo.row - b.parsedInfo.row);
    },
    // 获取指定列的总行数（layer1 + layer2）
    getColTotalRows(column) {
      const columnData = this.columns[column];
      if (!columnData) return 0;
      return columnData.layer1.length;
    },
    // 判断列是否超限
    isColOverflow(column) {
      const totalRows = this.getColTotalRows(column);
      return totalRows > this.rulerMaxRow;
    },
    // 计算列内格子高度
    getWarehouseCellHeight(column) {
      const totalRows = this.getColTotalRows(column);
      if (totalRows === 0) return this.rulerRowHeight;
      return this.isColOverflow(column) 
        ? this.rulerTotalHeight / totalRows 
        : this.rulerRowHeight;
    },
    // 获取整列库位ID
    getInterlacedWarehouseIds(warehouse) {
      if (!warehouse?.parsedInfo) return [];
      const { column, row } = warehouse.parsedInfo;
      const columnData = this.columns[column];
      if (!columnData) return [];
      
      const ids = [];
      const layer1Warehouse = columnData.layer1.find(w => w.parsedInfo.row === row);
      const layer2Warehouse = columnData.layer2.find(w => w.parsedInfo.row === row);
      if (layer1Warehouse) ids.push(layer1Warehouse.actualWarehouseId);
      if (layer2Warehouse) ids.push(layer2Warehouse.actualWarehouseId);
      return ids;
    },
    // 容器宽度计算
    calcContainerWidth() {
      this.containerWidth = this.$el.parentElement?.clientWidth || this.$el.clientWidth || 0;
    },
    handleResize() {
      clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout(() => {
        this.calcContainerWidth();
      }, 100);
    },
    // 单个格子点击
    handleCellClick(warehouse) {
      this.currentWarehouse = warehouse;
      this.dialogVisible = true;
    },
    // 单个格子右键
    openContextMenu(e, warehouse) {
      e.stopPropagation();
      this.currentContextWarehouse = warehouse;
      this.contextMenuTop = e.clientY;
      this.contextMenuLeft = e.clientX;
      this.contextMenuVisible = true;
    },
    closeContextMenu() {
      this.contextMenuVisible = false;
      this.currentContextWarehouse = null;
    },
    // 右键菜单处理
    handleContextMenuClick(type) {
      this.contextMenuVisible = false;
      if (!this.currentContextWarehouse) return;
      
      switch (type) {
        case 'view':
          this.handleCellClick(this.currentContextWarehouse);
          break;
        case 'delete':
          this.handleDeleteWarehouse(this.currentContextWarehouse);
          break;
        case 'split':
          this.handleSplitWarehouse();
          break;
        case 'merge':
          this.handleMergeWarehouse();
          break;
      }
    },
    // 分割库位
    handleSplitWarehouse() {
      if (!this.currentContextWarehouse) {
        this.$message.warning('请先选择要分割的库位');
        return;
      }
      if (this.currentContextWarehouse.isEnabled === 0) {
        this.$message.warning('已占用库位无法分割');
        return;
      }
      this.$emit('split-warehouse', this.currentContextWarehouse);
    },
    // 合并库位
    handleMergeWarehouse() {
      if (!this.currentContextWarehouse) {
        this.$message.warning('请先选择要合并的库位');
        return;
      }
      if (this.currentContextWarehouse.isEnabled === 0) {
        this.$message.warning('已占用库位无法合并');
        return;
      }
      this.$emit('merge-warehouse', this.currentContextWarehouse);
    },
    // 删除库位
    handleDeleteWarehouse(warehouse) {
      if (warehouse.isEnabled === 0) {
        Message.warning('禁用状态的库位无法删除');
        return;
      }
      this.$emit('delete-warehouse', warehouse);
    }
  }
};
</script>

<style scoped lang="scss">
/* 外层容器 */
.multi-layer-grid {
  width: 100% !important;
  height: 100%;
  box-sizing: border-box;
  margin: 0 !important;
  padding: 0 !important;
  overflow: hidden !important;
}

/* 列标尺 */
.col-ruler {
  display: flex;
  height: 30px;
  line-height: 30px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  width: 100% !important;
  box-sizing: border-box;
  overflow: hidden !important;

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

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

/* 行标尺 + 网格外层 */
.row-grid-wrapper {
  display: flex;
  width: 100% !important;
  height: calc(100% - 30px);
  box-sizing: border-box;
  overflow: hidden !important;
}

/* 左侧行标尺 */
.row-ruler {
  width: 30px;
  background: #f5f7fa;
  border-right: 1px solid #e4e7ed;
  flex-shrink: 0;
  overflow: hidden !important;
  height: var(--total-height);

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

/* 网格容器 */
.grid-container {
  display: grid;
  width: 100% !important;
  grid-template-columns: repeat(var(--column-count), minmax(0, var(--half-cell-width)));
  grid-auto-rows: var(--total-height); /* 每行高度=标尺总高度 */
  gap: 0px;
  box-sizing: border-box;
  margin: 0 !important;
  padding: 0 !important;
  height: var(--total-height);
  overflow: hidden !important;
  -ms-overflow-style: none;
  scrollbar-width: none;

  &::-webkit-scrollbar {
    display: none !important;
    width: 0 !important;
    height: 0 !important;
  }
}

/* 列容器（左右小列的外层容器）- 核心修改：移除底部padding，区分两层容器高度 */
.column-container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  padding: 1px;
  box-sizing: border-box;
  border: 1px solid #e4e7ed;
  border-radius: 4px;

  /* 移除：原填补空隙的底部padding */
  /* padding-bottom: calc(var(--offset-value, 0px) + 2px); */

  /* 左容器（layer1）基础样式：强制100%高度 */
  &.layer-1-container {
    background-color: #fff3e020;
    height: 100%;
  }

  /* 右容器（layer2）基础样式：自动高度，覆盖100% */
  &.layer-2-container {
    background-color: #e8f5e920;
    height: 100%;
  }
}

/* 单个库位格子（容器内的子元素） */
.warehouse-cell {
  height: var(--item-height); /* 动态高度：超限列缩小 */
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
  box-sizing: border-box;
  position: relative;
  z-index: 1;
  overflow: hidden;
  margin: 1px 0;
  /* 确保transform偏移不影响点击区域 */
  transform-origin: top center;

  /* 第一层格子样式 */
  &.layer-1:not(.disabled) {
    background: #fff3e0;
    color: #e65100;
  }

  /* 第二层格子样式 */
  &.layer-2:not(.disabled) {
    background: #e8f5e9;
    color: #2e7d32;
    /* 偏移后增加z-index，避免被遮挡 */
    z-index: 1;
  }

  /* 禁用状态 */
  &.disabled {
    background: #fafafa;
    color: #909399;
    cursor: not-allowed;
    opacity: 0.8;

    &:hover {
      border-color: #e4e7ed;
      background: #fafafa;
      z-index: 1;
    }
  }

  /* 单个格子独立hover */
  &:not(.disabled):hover {
    border-color: #90caf9;
    background: #f0f8ff;
    z-index: 2;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }

  /* 格子文字 */
  .cell-name {
    width: 100%;
    height: 90%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    padding: 0 4px;
    box-sizing: border-box;

    .cell-line1 {
      font-size: 12px;
      font-weight: 600;
      line-height: 1.2;
      margin-bottom: 2px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 100%;
    }

    .cell-line2 {
      font-size: 11px;
      line-height: 1.2;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 100%;
    }

    .disabled & .cell-line1,
    .disabled & .cell-line2 {
      color: #909399 !important;
    }

    .layer-1:not(.disabled) & .cell-line1,
    .layer-1:not(.disabled) & .cell-line2 {
      color: #e65100;
    }

    .layer-2:not(.disabled) & .cell-line1,
    .layer-2:not(.disabled) & .cell-line2 {
      color: #2e7d32;
    }
  }
}

/* 右键菜单 */
.custom-contextmenu {
  position: fixed;
  width: 120px;
  background: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
  padding: 5px 0;
  margin: 0;
  list-style: none;
  z-index: 9999;

  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li {
    padding: 6px 15px;
    cursor: pointer;
    font-size: 14px;
    color: #606266;
    transition: background-color 0.2s;

    &:hover {
      background-color: #f5f7fa;
    }

    &.disabled {
      color: #c0c4cc;
      cursor: not-allowed;

      &:hover {
        background-color: #ffffff;
      }
    }
  }

  .menu-divider {
    height: 1px;
    margin: 4px 0;
    background-color: #ebeef5;
    padding: 0;
    cursor: default;

    &:hover {
      background-color: #ebeef5;
    }
  }
}
</style>