<template>
  <div class="tray-container">
    <!-- 标题区域 -->
    <div class="panel-title">
      <div class="title-with-status">
        <div class="title-left">
          <div class="title-text">托盘信息管理</div>
          <div class="title-line"></div>
        </div>
      </div>

      <!-- 搜索区域 -->
      <div class="search-box">
        <el-input
          class="search-input"
          v-model="queryParams.fTrayCode"
          placeholder="请输入托盘编号"
          clearable
          @keyup.enter.native="searchTray"
        >
        </el-input>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="searchTray"
          class="search-button"
        >搜索</el-button>
      </div>
    </div>

    <!-- 表格内容区 -->
    <div class="tray-table-container">
      <!-- 带滚动条的表格容器 -->
      <div class="table-scroll-container">
        <el-table
          ref="trayTable"
          :data="filteredTrays"
          border
          style="width: 100%"
          @row-click="handleRowClick"
          :row-class-name="tableRowClassName"
          class="tray-table"
          :header-cell-style="headerCellStyle"
          :cell-style="cellStyle"
          height="100%"
          :row-key="getRowKey"
        >
          <!-- 固定列：托盘编号 -->
          <el-table-column
            prop="trayId"
            label="托盘编号"
            align="center"
            fixed="left"
            width="150"
          >
            <template slot-scope="scope">
              <div class="tray-id">{{ scope.row.fTrayCode }}</div>
            </template>
          </el-table-column>

          <!-- 固定列：状态 -->
          <el-table-column
            prop="status"
            label="状态"
            align="center"
            fixed="left"
            width="150"
          >
            <template slot-scope="scope">
              <el-tag :type="statusTagType(scope.row.fStatus)" v-if="scope.row.fStatus === '1'" class="status-tag">老化中</el-tag>
              <el-tag :type="statusTagType(scope.row.fStatus)" v-else-if="scope.row.fStatus === '2'" class="status-tag">老化完成</el-tag>
              <el-tag :type="statusTagType(scope.row.fStatus)" v-else-if="scope.row.fStatus === '3'" class="status-tag">标定完成</el-tag>
              <el-tag :type="statusTagType(scope.row.fStatus)" v-else-if="scope.row.fStatus === '4'" class="status-tag">已绑定</el-tag>
              <el-tag :type="statusTagType(scope.row.fStatus)" v-else class="status-tag">空闲</el-tag>
            </template>
          </el-table-column>

          <!-- 可滚动列：老化开始时间 -->
          <el-table-column prop="fAgingStartTime" label="老化开始时间" align="center" width="200">
            <template slot-scope="scope">
              <div class="device-code">{{ scope.row.fAgingStartTime ? formatDate(scope.row.fAgingStartTime) : '-' }}</div>
            </template>
          </el-table-column>

          <!-- 可滚动列：预计老化结束时间 -->
          <el-table-column prop="fAgingEndTime" label="预计老化结束时间" align="center" width="200">
            <template slot-scope="scope">
              <div class="device-code">{{ scope.row.estimatedEndTime ? formatDate(scope.row.estimatedEndTime) : '-' }}</div>
            </template>
          </el-table-column>
          <!-- 可滚动列：主板数量 -->
          <el-table-column prop="boardCount" label="主板数量" align="center" :width="boardCountWidth">
            <template slot-scope="scope">
              <div class="board-count">
                <span class="count-number">{{ (scope.row.boardCount == null || scope.row.boardCount === 0) ? '0' : scope.row.boardCount }}</span>
                <span class="count-label">块</span>
              </div>
            </template>
          </el-table-column>

          <!-- 可滚动列：位置 -->
          <el-table-column prop="location" label="位置" align="center" :width="locationWidth">
            <template slot-scope="scope">
              <div class="location-text">{{ scope.row.fStoreyCode }}</div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="total"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { listTray } from "@/api/tray/tray"
import {formatDate} from "@/utils";
import {getAgingStage4Time} from "@/api/system/config";

export default {
  name: "TrayInformation",
  data() {
    return {
      searchKeyword: '',
      trays: [],

      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fTrayCode: undefined,
      },
      // 动态列宽
      boardCountWidth: '150',
      locationWidth: '150',
      // // 把预计老化结束时间保存到数据库中，因为可能会不同的老化时间
      // agingStage4Time: 0,
    };
  },
  created() {
    this.fetchTrays();
  },
  mounted() {
    // 监听窗口大小变化，调整表格布局
    window.addEventListener('resize', this.handleResize);
    // 初始化时也计算一次
    this.$nextTick(() => {
      this.adjustTableLayout();
    });
    //// 把预计老化结束时间保存到数据库中，因为可能会不同的老化时间
    // this.initAgingStage4Time();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  computed: {
    // 表格头部样式
    headerCellStyle() {
      return {
        'background': 'linear-gradient(to bottom, rgba(10, 35, 80, 0.9), rgba(8, 28, 65, 0.9))',
        'color': '#a0d0ff',
        'font-size': '16px',
        'font-weight': 'bold',
        'border-bottom': '1px solid rgba(64, 158, 255, 0.5)',
        'height': '60px',
        'padding': '0 15px',
      }
    },
    // 表格单元格样式
    cellStyle() {
      return {
        'border-bottom': '1px solid rgba(64, 158, 255, 0.2)',
        'padding': '16px 15px',
        'font-size': '15px',
        'transition': 'all 0.3s ease'
      }
    },
    // 计算过滤后的托盘数据
    filteredTrays() {
      let filtered = this.trays;
      if (this.searchKeyword) {
        filtered = filtered.filter(tray =>
          tray.fTrayCode && tray.fTrayCode.includes(this.searchKeyword)
        );
      }
      return filtered;
    },
  },
  methods: {
    /** 日期格式化（兼容字符串和Date对象） */
    formatDate(date) {
      return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    },

    // 获取行唯一键
    getRowKey(row) {
      return row.fTrayCode || row.trayId;
    },
    initAgingStage4Time() {
      getAgingStage4Time().then(response => {
        this.agingStage4Time = response.data.configValue;
      })
    },

    // 获取托盘数据
// 获取托盘数据
    fetchTrays() {
      listTray(this.queryParams).then(response => {
        // // 把预计老化结束时间保存到数据库中，因为可能会不同的老化时间
        // this.trays = response.rows.map(item => {
        //   // 如果是运行中状态且有老化开始时间，计算预计老化结束时间
        //   if (item.fStatus === '1' && item.fAgingStartTime) {
        //     try {
        //       // 将开始时间转换为Date对象
        //       const startTime = new Date(item.fAgingStartTime);
        //       // 加上配置的分钟数（agingStage3Time以分钟为单位）
        //       const endTime = new Date(startTime.getTime() + this.agingStage4Time * 60 * 1000);
        //       // 添加到item对象中
        //       item.fAgingEndTime = endTime;
        //     } catch (e) {
        //       console.error('计算预计老化结束时间失败:', e);
        //       item.fAgingEndTime = null;
        //     }
        //   } else {
        //     item.fAgingEndTime = null;
        //     item.fAgingStartTime = null;
        //   }
        //   return item;
        // });
        this.trays = response.rows;
        this.total = response.total;
        this.loading = false;
        // 数据加载完成后调整表格布局
        this.$nextTick(() => {
          this.adjustTableLayout();
        });
      });
    },
    // 搜索托盘
    searchTray() {
      this.queryParams.pageNum = 1;
      this.fetchTrays();
    },

    // 处理行点击
    handleRowClick(row) {
      this.$emit('cabinet-click', row, 4);
    },

    // 设置行样式
    tableRowClassName() {
      return 'clickable-row';
    },

    // 状态标签类型
    statusTagType(status) {
      const statusMap = {
        '0': 'info',       // 空闲 - 灰色
        '1': 'success',    // 运行 - 绿色
        '2': 'warning',    // 老化完成 - 橙色（较浅）
        '3': 'danger',     // 标检完成 - 红色（更紧急）
        '4': 'primary',    // 已绑定 - 蓝色
      };
      return statusMap[status] || 'info';
    },

    // 分页处理
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      this.fetchTrays();
    },

    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.fetchTrays();
    },

    // 窗口大小变化处理
    handleResize() {
      this.adjustTableLayout();
    },

    // 调整表格布局
    adjustTableLayout() {
      // 确保表格填满容器宽度，避免大屏幕留白
      const tableContainer = this.$el.querySelector('.tray-table-container');
      if (tableContainer) {
        const containerWidth = tableContainer.clientWidth;

        // 计算所有固定宽度的列的总宽度
        const fixedColsWidth = 150 + 170; // 固定列宽度（托盘编号150 + 状态120）
        const timeColsWidth = 200 + 200; // 时间列宽度（老化开始时间200 + 预计老化结束时间200）
        const fixedTotalWidth = fixedColsWidth + timeColsWidth;

        // 计算剩余可用宽度
        const remainingWidth = containerWidth - fixedTotalWidth;

        // 如果剩余宽度大于0，平均分配给主板数量和位置列
        if (remainingWidth > 300) { // 确保有最小宽度
          const averageWidth = Math.floor(remainingWidth / 2);
          this.boardCountWidth = averageWidth.toString();
          this.locationWidth = averageWidth.toString();
        } else {
          // 如果宽度不足，使用最小宽度
          this.boardCountWidth = '150';
          this.locationWidth = '150';
        }

        // 触发表格重新布局
        if (this.$refs.trayTable) {
          this.$refs.trayTable.doLayout();
        }
      }
    },
  }
}
</script>

<style scoped>
/* 主容器样式 */
.tray-container {
  width: 100%;
  height: 100%;
  min-height: 100%;
  background: rgba(10, 20, 40, 0.85);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid rgba(64, 158, 255, 0.3);
  box-shadow: 0 0 20px rgba(0, 50, 120, 0.3);
  box-sizing: border-box;
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;
}

/* 标题区域样式 */
.panel-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(64, 158, 255, 0.3);
  width: 100%;
}

.title-with-status {
  display: flex;
  align-items: center;
  gap: 15px;
}

.title-left {
  display: flex;
  flex-direction: column;
}

.title-text {
  font-size: 22px;
  font-weight: bold;
  color: #ffffff;
  letter-spacing: 1px;
  text-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
}

.title-line {
  height: 3px;
  width: 100px;
  background: linear-gradient(to right, #409EFF, transparent);
  margin-top: 8px;
  border-radius: 2px;
}

/* 搜索区域样式 */
.search-box {
  display: flex;
  gap: 10px;
  width: auto;
}

.search-input {
  min-width: 200px;
  width: 300px;
}

.search-input >>> .el-input__inner {
  background: rgba(10, 30, 70, 0.6);
  border: 1px solid #409EFF;
  color: #ffffff;
  height: 40px;
  border-radius: 4px;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.3) inset;
}

.search-input >>> .el-input__inner::placeholder {
  color: rgba(200, 200, 255, 0.5);
}

.search-button {
  background: linear-gradient(to right, #409EFF, #64c8ff);
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  transition: all 0.3s;
  height: 40px;
}

.search-button:hover {
  background: linear-gradient(to right, #64c8ff, #409EFF);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.4);
}

.search-button i {
  margin-right: 5px;
}

/* 表格容器样式 */
.tray-table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  border-radius: 10px;
  overflow: hidden;
  border: 1px solid rgba(64, 158, 255, 0.3);
  box-shadow: 0 0 20px rgba(0, 153, 255, 0.15);
  margin-top: 10px;
  min-width: 0; /* 关键：防止flex容器溢出 */
}

/* 表格滚动容器 - 关键修改：支持水平滚动 */
.table-scroll-container {
  flex: 1;
  overflow: auto; /* 改为auto，同时支持水平和垂直滚动 */
  position: relative;
  width: 100%;
}

/* 自定义滚动条样式 */
.table-scroll-container::-webkit-scrollbar {
  width: 10px; /* 垂直滚动条宽度 */
  height: 10px; /* 水平滚动条高度 */
}

.table-scroll-container::-webkit-scrollbar-track {
  background: rgba(10, 35, 80, 0.5);
  border-radius: 4px;
}

.table-scroll-container::-webkit-scrollbar-thumb {
  background: rgba(64, 158, 255, 0.5);
  border-radius: 4px;
  border: 1px solid rgba(64, 158, 255, 0.2);
}

.table-scroll-container::-webkit-scrollbar-thumb:hover {
  background: rgba(64, 158, 255, 0.8);
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
}

.table-scroll-container::-webkit-scrollbar-corner {
  background: rgba(10, 35, 80, 0.5);
}

/* 表格样式 - 关键修改：确保表格填满容器 */
.tray-table >>> .el-table {
  background: transparent;
  color: #e0f0ff;
  border-radius: 10px 10px 0 0;
  overflow: hidden;
  width: 100% !important; /* 确保表格宽度100% */
  min-width: auto !important; /* 移除最小宽度限制 */
  table-layout: fixed !important; /* 使用固定布局，让列宽平均分配 */
}

/* 固定列样式 */
.tray-table >>> .el-table__fixed,
.tray-table >>> .el-table__fixed-right {
  box-shadow: 0 0 10px rgba(0, 100, 255, 0.2);
  z-index: 2;
}

.tray-table >>> .el-table__fixed::before,
.tray-table >>> .el-table__fixed-right::before {
  background-color: transparent;
}

.tray-table >>> .el-table th.is-fixed-left,
.tray-table >>> .el-table th.is-fixed-right {
  background: linear-gradient(to bottom, rgba(10, 35, 80, 0.95), rgba(8, 28, 65, 0.95));
}

.tray-table >>> .el-table td.is-fixed-left,
.tray-table >>> .el-table td.is-fixed-right {
  background: rgba(8, 28, 65, 0.7);
}

/* 表头样式 */
.tray-table >>> .el-table th {
  background: linear-gradient(to bottom, rgba(10, 35, 80, 0.9), rgba(8, 28, 65, 0.9));
  color: #a0d0ff;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid rgba(64, 158, 255, 0.5);
  height: 60px;
  white-space: nowrap; /* 防止表头文字换行 */
  min-width: 0; /* 允许表头列收缩 */
}

.tray-table >>> .el-table tr {
  background: rgba(8, 28, 65, 0.5);
  transition: all 0.3s ease;
}

.tray-table >>> .el-table tr:hover {
  background: rgba(15, 45, 90, 0.7) !important;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 100, 255, 0.2);
}

.tray-table >>> .el-table td {
  border-bottom: 1px solid rgba(64, 158, 255, 0.2);
  padding: 16px 15px;
  font-size: 15px;
  white-space: nowrap; /* 防止单元格内容换行 */
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: 0; /* 允许单元格内容自适应 */
}

/* 行点击样式 */
.clickable-row {
  cursor: pointer;
}

/* 表格内容样式 */
.tray-id {
  font-weight: bold;
  color: #6dc6ff;
}

.status-tag {
  font-weight: bold;
  border-radius: 12px;
  padding: 0 12px;
  height: 28px;
  line-height: 28px;
  min-width: 80px;
  text-align: center;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
}

.board-count {
  display: flex;
  align-items: center;
  justify-content: center;
}

.count-number {
  font-size: 18px;
  font-weight: bold;
  color: #ffcf5c;
  margin-right: 5px;
  text-shadow: 0 0 8px rgba(255, 207, 92, 0.3);
}

.count-label {
  color: #a0d0ff;
}

.location-text {
  color: #a0d0ff;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

/* 分页样式 */
.pagination-container {
  background: rgba(10, 35, 80, 0.7);
  padding: 15px 20px;
  border-top: 1px solid rgba(64, 158, 255, 0.3);
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-shrink: 0; /* 防止分页区域被压缩 */
}

.pagination-container >>> .el-pagination {
  color: #a0d0ff;
}

.pagination-container >>> .el-pagination__total {
  color: #a0d0ff;
  margin-right: 15px;
}

.pagination-container >>> .el-pagination button {
  background: transparent;
  color: #a0d0ff;
  border: 1px solid rgba(64, 158, 255, 0.3);
  border-radius: 6px;
  min-width: 32px;
  height: 32px;
  margin: 0 3px;
  transition: all 0.3s ease;
}

.pagination-container >>> .el-pagination button:hover {
  background: rgba(64, 158, 255, 0.2);
  color: #6dc6ff;
  border-color: rgba(64, 158, 255, 0.5);
}

.pagination-container >>> .el-pager li {
  background: transparent;
  color: #a0d0ff;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  margin: 0 3px;
  border-radius: 6px;
  border: 1px solid rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.pagination-container >>> .el-pager li:hover {
  color: #6dc6ff;
  background: rgba(64, 158, 255, 0.1);
  border-color: rgba(64, 158, 255, 0.5);
}

.pagination-container >>> .el-pager li.active {
  background: linear-gradient(135deg, #409EFF 0%, #1a73e8 100%);
  color: white;
  border: none;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
}

.pagination-container >>> .el-pagination__sizes {
  margin-right: 15px;
}

.pagination-container >>> .el-pagination__sizes .el-input .el-input__inner {
  background: rgba(10, 30, 70, 0.6);
  border: 1px solid rgba(64, 158, 255, 0.3);
  color: #e0f0ff;
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .search-input {
    width: 250px;
  }
}

@media (max-width: 800px) {
  .panel-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .search-box {
    width: 100%;
    justify-content: flex-start;
  }

  .search-input {
    width: 100%;
    min-width: auto;
  }

  /* 表格列自适应 */
  .tray-table >>> .el-table th,
  .tray-table >>> .el-table td {
    padding: 12px 8px;
    font-size: 14px;
  }
}

@media (max-width: 500px) {
  .title-text {
    font-size: 18px;
  }

  .title-line {
    width: 80px;
  }

  .pagination-container {
    padding: 10px;
  }

  .pagination-container >>> .el-pagination {
    font-size: 12px;
  }

  .pagination-container >>> .el-pagination__total {
    display: none;
  }

  .tray-table >>> .el-table th,
  .tray-table >>> .el-table td {
    padding: 8px 4px;
    font-size: 13px;
  }

  .status-tag {
    padding: 0 8px;
    min-width: 60px;
    font-size: 12px;
  }
}

/* 大屏幕优化：填满容器，避免留白 */
@media (min-width: 1400px) {
  .tray-table-container {
    min-width: 100%;
  }

  .table-scroll-container {
    overflow-x: hidden; /* 大屏幕上如果宽度足够，隐藏水平滚动条 */
  }

  .tray-table >>> .el-table {
    table-layout: fixed !important; /* 确保使用固定布局 */
  }
}
</style>
