<template>
  <div class="screen-container">
    <!-- 外层容器 - 添加边框 -->
    <div class="aging-layer-container">
      <!-- 头部标题区域 -->
      <div class="tray-header">
        <div class="tray-title">
          <div class="title-text">{{ modbusDeviceData.fEquipmentCode }}号柜</div>
          <div class="title-line"></div>
        </div>
      </div>

      <!-- 整体内容容器 -->
      <div class="content-container">
        <!-- 返回按钮 -->
        <div class="back-button" @click="goBack">
          <i class="el-icon-back"></i> 返回老化柜看板
        </div>

        <!-- 柜体容器 -->
        <div class="cabinet-body">
          <div class="cabinet-and-lines">
            <!-- 柜体 -->
            <div class="cabinet" ref="cabinetContainer">
              <div
                v-for="(layer, index) in layers"
                :key="layer.id"
                class="layer"
                :style="getLayerStyle(index)"
                :class="[
                  'layer-depth',
                  `layer-${index}`,
                  {
                    'status-running': layer.fStatus === '1',
                    'status-fault': layer.fStatus === '2',
                    'status-idle': layer.fStatus === '0',
                    'status-power_outage': layer.fStatus === '3'
                  }
                ]"
                @click="selectLayer(index)"
              >
                <div class="layer-content">
                  <div class="layer-name">{{ layer.name }}</div>
                  <div class="layer-status">{{ getStatusText(layer.fStatus) }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧内容区域 -->
        <div class="right-content">
          <div class="panel-title">托盘信息</div>
          <div class="placeholder">
            <div class="tray-container">
              <!-- 托盘信息展示区域 -->
              <div class="tray-header-inner">
                <span class="tray-label">托盘</span>
                <span class="tray-id">{{ trayInfo.fTrayCode }}</span>
              </div>

              <div class="tray-info">
                <div class="info-row">
                  <div class="info-label">所在柜体：</div>
                  <div class="info-value">{{ modbusDeviceData.fEquipmentCode }}号柜 - {{ trayInfo.layer ? trayInfo.layer.split("-")[1] : '--' }}层</div>
                </div>
                <div class="info-row">
                  <div class="info-label">当前状态：</div>
                  <div class="info-value" :class="trayInfo.statusClass || 'status-idle'">
                    {{ trayInfo.status || '--' }}
                  </div>
                </div>

                <div class="info-row">
                  <div class="info-label">老化开始时间：</div>
                  <div class="info-value">{{ formatDateTime(trayInfo.fAgingStartTime) || '--' }}</div>
                </div>
                <div class="info-row">
                  <div class="info-label">老化时长：</div>
                  <div class="info-value aging-time">{{ agingTimeDisplay }}</div>
                </div>
              </div>

              <!-- 操作按钮区域 -->
              <div class="tray-actions">
                <button class="btn-action btn-load" @click="loadTray" v-if="trayInfo.status === '1'">
                  <i class="icon-load"></i>下料
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { queryByDepartmentId } from "@/api/storey/storey";
import { testPowerOutage } from "@/api/testScheduledTasks/testTasks";
import { insertBlankingRobotArmCommand } from "@/api/robotArm/robotArmCommand";
export default {
  name: "AgingLayer",
  props: {
    modbusDeviceData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      layers: [],
      trayInfo: {},
      agingTimer: null,
      agingStartTime: null,
      agingTimeDisplay: "00:00:00"
    };
  },
  watch: {
    modbusDeviceData: {
      immediate: true,
      handler(newVal) {
        if (newVal && newVal.id) {
          this.loadCabinetData(newVal.id);
        }
      }
    },
    trayInfo: {
      deep: true,
      handler(newVal) {
        if (newVal.fAgingStartTime) {
          this.startAgingTimer(newVal.fAgingStartTime);
        } else {
          this.stopAgingTimer();
          this.agingTimeDisplay = "00:00:00";
        }
      }
    }
  },
  mounted() {
    if (this.modbusDeviceData && this.modbusDeviceData.fEquipmentId) {
      this.loadCabinetData(this.modbusDeviceData.fEquipmentId);
    }
  },
  beforeDestroy() {
    this.stopAgingTimer();
  },
  methods: {
    // 格式化日期时间
    formatDateTime(dateString) {
      if (!dateString) return "--";
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },

    // 启动老化计时器
    startAgingTimer(startTime) {
      this.stopAgingTimer();
      this.agingStartTime = new Date(startTime);

      // 立即更新一次
      this.updateAgingTime();

      // 每秒更新一次
      this.agingTimer = setInterval(() => {
        this.updateAgingTime();
      }, 1000);
    },

    // 更新老化时间显示
    updateAgingTime() {
      if (!this.agingStartTime) return;

      const now = new Date();
      const diff = Math.floor((now - this.agingStartTime) / 1000); // 秒数

      const hours = Math.floor(diff / 3600);
      const minutes = Math.floor((diff % 3600) / 60);
      const seconds = diff % 60;

      this.agingTimeDisplay = `${this.padZero(hours)}:${this.padZero(minutes)}:${this.padZero(seconds)}`;
    },

    // 停止老化计时器
    stopAgingTimer() {
      if (this.agingTimer) {
        clearInterval(this.agingTimer);
        this.agingTimer = null;
      }
    },

    // 数字补零
    padZero(num) {
      return num.toString().padStart(2, '0');
    },

    // 加载柜子详情数据
    loadCabinetData(id) {
      queryByDepartmentId(id).then(res => {
        if (res.code === 200 && res.data.length > 0) {
          this.layers = res.data.map((item, i) => ({
            ...item,
            name: item.fStoreyCode,
            id: item.fStoreyId,
            layer: item.fStoreyCode,
            productModel: `PQC-${1000 + i}`,
            status: this.getStatusText(item.fStatus),
            statusClass: this.getStatusClass(item.fStatus),
            fAgingStartTime: item.fAgingStartTime
          }));

          // 默认选中第一层
          if (this.layers.length > 0) {
            this.selectLayer(0);
          }
        } else {
          this.$message.error("加载层数据失败");
          console.error("加载数据失败:", res.message);
        }
      }).catch(error => {
        this.$message.error("加载数据异常");
        console.error("加载数据异常:", error);
      });
    },

    // 返回老化柜看板
    goBack() {
      this.$emit('go-back',0);
    },

    // 选择层
    selectLayer(index) {
      this.trayInfo = { ...this.layers[index] };
    },

    // 操作按钮方法
    loadTray() {
      this.$message.success("下料操作已执行");

      const robotArmCommand = {
        trayCode: this.trayInfo.fTrayCode,
        storeyCode: this.trayInfo.storeyCode,
        type: '1'
      };
      insertBlankingRobotArmCommand(robotArmCommand).then(res => {
        if(res.code === 200) {
          this.msgSuccess("添加成功");
          this.showAddDialog = false;
        } else {
          this.msgSuccess("添加失败");
        }
      })
    },

    powerOn() {
      this.$message.success("上电操作已执行");
      testPowerOutage().then(response => {
        if(response.code === 200) {
          this.$message.success("断电操作已执行");
        }
      })
    },

    // 获取状态类名
    getStatusClass(status) {
      switch (status) {
        case '0': return 'status-idle';
        case '1': return 'status-running';
        case '2': return 'status-fault';
        case '3': return 'status-power_outage';
        default: return 'status-idle';
      }
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case '0': return '空闲';
        case '1': return '运行中';
        case '2': return '故障';
        case '3': return '断电';
        default: return '未知状态';
      }
    },

    // 获取层样式
    getLayerStyle(index) {
      const verticalSpacing = 70;
      return {
        top: `${index * verticalSpacing}px`,
        width: '180px',
        height: '60px',
        zIndex: index,
      };
    }
  }
};
</script>

<style scoped>
/* 外层容器样式 - 统一边框风格 */
.aging-layer-container {
  width: 100%;
  padding: 20px;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
  background: rgba(4, 18, 57, 0.7);
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 153, 255, 0.2);
  border: 1px solid rgba(64, 158, 255, 0.3);
}

/* 头部标题样式 - 与托盘信息管理界面一致 */
.tray-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(64, 158, 255, 0.3);
}

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

/* 层状态样式 - 运行中 */
.status-running {
  /* 运行中状态 - 绿色 #67c23a */
  color: #67c23a;
  border: 1px solid rgba(103, 194, 58, 0.8);
  box-shadow:
    0 4px 12px rgba(0, 0, 0, 0.6),
    inset 0 0 8px rgba(103, 194, 58, 0.5);
}

.status-running.layer-depth {
  border-width: 1px 3px 3px 1px;
  border-color:
    rgba(103, 194, 58, 0.4)
    rgba(103, 194, 58, 0.8)
    rgba(103, 194, 58, 0.8)
    rgba(103, 194, 58, 0.4);
}

.status-running:hover {
  background: linear-gradient(to bottom, rgba(103, 194, 58, 0.2), rgba(0,0,0,0.3));
  box-shadow:
    0 4px 15px rgba(103, 194, 58, 0.4),
    inset 0 0 10px rgba(103, 194, 58, 0.4);
}

/* 层状态样式 - 故障 */
.status-fault {
  /* 故障状态 - 红色 #f56c6c */
  color: #f56c6c;
  border: 1px solid rgba(245, 108, 108, 0.8);
  box-shadow:
    0 4px 12px rgba(0, 0, 0, 0.6),
    inset 0 0 8px rgba(245, 108, 108, 0.5);
}

.status-fault.layer-depth {
  border-width: 1px 3px 3px 1px;
  border-color:
    rgba(245, 108, 108, 0.4)
    rgba(245, 108, 108, 0.8)
    rgba(245, 108, 108, 0.8)
    rgba(245, 108, 108, 0.4);
}

.status-fault:hover {
  background: linear-gradient(to bottom, rgba(245, 108, 108, 0.2), rgba(0,0,0,0.3));
  box-shadow:
    0 4px 15px rgba(245, 108, 108, 0.4),
    inset 0 0 10px rgba(245, 108, 108, 0.4);
}

/* 层状态样式 - 空闲 */
.status-idle {
  /* 空闲状态 - 浅灰 #f0f0f0 */
  color: #f0f0f0;
  border: 1px solid rgba(240, 240, 240, 0.8);
  box-shadow:
    0 4px 12px rgba(0, 0, 0, 0.6),
    inset 0 0 8px rgba(240, 240, 240, 0.5);
}

.status-idle.layer-depth {
  border-width: 1px 3px 3px 1px;
  border-color:
    rgba(240, 240, 240, 0.4)
    rgba(240, 240, 240, 0.8)
    rgba(240, 240, 240, 0.8)
    rgba(240, 240, 240, 0.4);
}

.status-idle:hover {
  background: linear-gradient(to bottom, rgba(240, 240, 240, 0.2), rgba(0,0,0,0.3));
  box-shadow:
    0 4px 15px rgba(240, 240, 240, 0.4),
    inset 0 0 10px rgba(240, 240, 240, 0.4);
}

/* 层状态样式 - 断电 */
.status-power_outage {
  color: #9e9e9e;
  border: 1px solid rgba(158, 158, 158, 0.8);
  box-shadow:
    0 4px 12px rgba(0, 0, 0, 0.6),
    inset 0 0 8px rgba(158, 158, 158, 0.5);
}

.status-power_outage.layer-depth {
  border-width: 1px 3px 3px 1px;
  border-color:
    rgba(158, 158, 158, 0.4)
    rgba(158, 158, 158, 0.8)
    rgba(158, 158, 158, 0.8)
    rgba(158, 158, 158, 0.4);
}

.status-power_outage:hover {
  background: linear-gradient(to bottom, rgba(158, 158, 158, 0.2), rgba(0,0,0,0.3));
  box-shadow:
    0 4px 15px rgba(158, 158, 158, 0.4),
    inset 0 0 10px rgba(158, 158, 158, 0.4);
}

/* 层内容样式 */
.layer-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.layer-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 4px;
  text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
}

.layer-status {
  font-size: 12px;
  opacity: 0.9;
  text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
}

/* 老化时间样式 */
.aging-time {
  font-family: 'Courier New', monospace;
  font-size: 16px;
  letter-spacing: 1px;
  color: #64ffaa;
}

/* 其他样式保持不变（原有样式） */
.screen-container {
  color: white;
  font-family: 'Arial', sans-serif;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background: radial-gradient(circle at center, #041740 0%, #030b2a 70%);
}

.content-container {
  position: relative; /* 使返回按钮相对于此容器定位 */
  display: flex;
  width: 100%;
  max-width: 1600px;
  justify-content: space-between;
  align-items: flex-start;
}

.cabinet-body {
  display: flex;
  align-items: flex-start;
  height: auto;
  position: relative;
}

.cabinet-and-lines {
  position: relative;
}

.cabinet {
  position: relative;
  width: 180px;
  height: 700px;
}

.layer {
  position: absolute;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.layer:hover {
  transform: translateY(-2px);
}

.right-content {
  flex: 1;
  margin-left: 80px;
  min-height: 700px;
  display: flex;
  flex-direction: column;
  background: rgba(0, 30, 80, 0.2);
  border-radius: 12px;
  border: 1px solid rgba(100, 180, 255, 0.3);
  padding: 20px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 0 20px rgba(0, 50, 120, 0.3);
}

.panel-title {
  font-size: 20px;
  color: #64c8ff;
  font-weight: bold;
  text-shadow: 0 0 5px rgba(100, 200, 255, 0.5);
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(100, 180, 255, 0.4);
}

.placeholder {
  padding: 20px;
  background: rgba(0, 30, 80, 0.3);
  border: 1px solid rgba(100, 180, 255, 0.4);
  border-radius: 10px;
  font-size: 18px;
  text-align: left;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tray-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

/* 区分内部托盘标题和外部容器标题 */
.tray-header-inner {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background: rgba(0, 40, 90, 0.4);
  border-radius: 8px;
  border: 1px solid rgba(100, 180, 255, 0.5);
  margin-bottom: 20px;
}

.tray-label {
  font-size: 20px;
  font-weight: bold;
  color: #64c8ff;
  text-shadow: 0 0 8px rgba(100, 200, 255, 0.6);
}

.tray-id {
  font-size: 22px;
  font-weight: bold;
  background: linear-gradient(to right, #64c8ff, #3a7bd5);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 0 10px rgba(100, 200, 255, 0.4);
}

.tray-info {
  flex: 1;
  padding: 15px;
  background: rgba(0, 30, 70, 0.3);
  border-radius: 8px;
  border: 1px solid rgba(100, 180, 255, 0.4);
}

.info-row {
  display: flex;
  margin: 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px dashed rgba(100, 180, 255, 0.2);
}

.info-label {
  width: 130px;
  color: #64c8ff;
  font-weight: bold;
}

.info-value {
  flex: 1;
  color: #fff;
}

/* 右侧状态文本样式 */
.status-idle {
  color: #f0f0f0;
  font-weight: bold;
}

.status-running {
  color: #67c23a;
  font-weight: bold;
}

.status-fault {
  color: #f56c6c;
  font-weight: bold;
}

.status-power_outage {
  color: #9e9e9e;
  font-weight: bold;
}

.tray-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  gap: 15px;
}

.btn-action {
  padding: 12px 25px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-action:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.btn-load {
  background: linear-gradient(to right, #3a7bd5, #00d2ff);
  color: white;
}

.btn-power {
  background: linear-gradient(to right, #11998e, #38ef7d);
  color: white;
}

.icon-load, .icon-power {
  display: inline-block;
  width: 20px;
  height: 20px;
  background-size: contain;
  background-repeat: no-repeat;
}

.icon-load {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z'/%3E%3C/svg%3E");
}

.icon-power {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M16 9v4.66l-3.5 3.51V19h-1v-1.83L8 13.65V9h8m0-6h-2v4h-4V3H8v4h-.01C6.9 6.99 6 7.89 6 8.98v5.52L9.5 18v3h5v-3l3.5-3.5V9c0-1.1-.9-2-2-2V3z'/%3E%3C/svg%3E");
}

.glow-effect {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at center, rgba(100, 200, 255, 0.1) 0%, transparent 70%);
  pointer-events: none;
  z-index: -1;
}

.back-button {
  position: absolute;
  top: -90px; /* 调整顶部距离 */
  right: 15px; /* 调整右侧距离 */
  cursor: pointer;
  padding: 8px 15px;
  background: rgba(0, 30, 80, 0.3);
  border-radius: 6px;
  border: 1px solid rgba(100, 180, 255, 0.6);
  color: #409EFF;
  display: inline-flex;
  align-items: center;
  transition: all 0.3s;
  font-size: 14px;
  z-index: 100; /* 确保在其他内容上方 */
}

.back-button:hover {
  color: #66b1ff;
  transform: translateX(-5px);
}
</style>
