<!-- 还料离开 - 智能仓储风格 -->
<template>
  <div class="stock-requisition-page">
    <!-- 背景层 -->
    <div class="bg-layer" :style="{ backgroundImage: `url(${bgImg})` }" />

    <!-- 顶部标题区域 -->
    <div class="header-section">
      <button class="logout-btn" @click="goHome">
        <i class="fas fa-home" />
        <span>主页</span>
      </button>
      <h1 class="page-title">入库离开</h1>
      <!-- 右侧操作按钮 -->
      <div class="header-actions">
        <button class="action-btn refresh-btn" @click="verify">
          <i class="fas fa-sync-alt" />
          <span>重新校验</span>
        </button>
      </div>
    </div>

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 统计信息 -->
      <div v-if="materialList.length > 0" class="stats-section">
        <span class="stats-text">您共有 {{ materialList.length }} 个物料入库，请确认物料已经放置到对应的货位，确认无误以后，再点击【入库离开】按钮。</span>
      </div>

      <!-- 卡片网格区域 -->
      <div class="card-grid-wrapper">
        <!-- 空状态 -->
        <div v-if="materialList.length === 0 && !loading" class="empty-state">
          <i class="fas fa-inbox empty-icon" />
          <p>暂无数据</p>
        </div>

        <!-- 卡片网格 -->
        <div v-else class="card-grid">
          <div
            v-for="(item, index) in materialList"
            :key="item.id || index"
            class="inventory-card"
            :class="getCardClass(item)"
          >
            <!-- 卡片序号 -->
            <div class="card-index" :class="getCardClass(item)">{{ index + 1 }}</div>

            <!-- 图片区域 -->
            <div class="card-image">
              <div class="image-placeholder" :class="getCardClass(item)">
                <i :class="getInventoryIcon(item.inventoryType)" />
              </div>
            </div>

            <!-- 信息区域 -->
            <div class="card-info">
              <div class="info-row">
                <span class="info-label">类型:</span>
                <span class="info-value">{{ item.inventoryType || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">名称:</span>
                <span class="info-value">{{ item.inventoryName || '-' }}</span>
              </div>
              <div class="info-row location-row">
                <i class="fas fa-map-marker-alt location-icon" />
                <span class="info-value">{{ item.positionName || '-' }}</span>
              </div>
            </div>

            <!-- 状态区域（固定高度） -->
            <div class="card-status-section">
              <div class="status-badge" :class="getCardClass(item)">
                <i class="fas fa-exclamation-circle" />
                {{ item.remarks || '-' }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部操作按钮 -->
    <div class="bottom-actions">
      <button class="submit-btn" :disabled="notInStockCount" @click="handleComplete">
        入库离开
      </button>
    </div>

    <!-- Loading -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-dots">
        <div class="dot" />
        <div class="dot" />
        <div class="dot" />
      </div>
      <span class="loading-text">加载中...</span>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { showNotify } from 'vant';
import { ref, onMounted, computed, onUnmounted } from 'vue';
import { queryCFStockInByUser, backfillCFStockInTime, cfStockInLeave } from '../api/stockIn.js';
import { areArraysEqual } from '../common/utils.js';
import { gateController } from '../hardware/GateOperate.js';

// 图片资源
import bgImg from '../assets/images/bj.png';

const router = useRouter();

// 返回主页
const goHome = () => {
    router.push('/home');
};

// 表格加载状态
const loading = ref(false);

const isCanLeave = ref(false);

// 物料列表数据
const materialList = ref([]);

const userMaterialList = ref([]);

// 人员对应的物料列表
const inList = ref([]);

// 校验列表
const validateList = ref([]);
const epcs = ref([]);
// 临时数组用于累积EPC数据
const tempEpcs = ref([]);

// 是否可以还料离开
const notInStockCount = computed(() => {
    if (isCanLeave.value === true) {
        return false;
    }
    // if (inList.value.length === 0) {
    //     return false;
    // }
    return true;
});

// 根据 isValid 返回卡片样式类
const getCardClass = card => {
    if (card.isValid === true) {
        return 'not-in-stock-card';
    } else if (card.isValid === false) {
        return 'in-stock-card';
    }
    return '';
};

// 获取设备类型图标
const getInventoryIcon = type => {
    const iconMap = {
        '工装': 'fas fa-cube',
        '设备': 'fas fa-cogs',
        '成品': 'fas fa-box',
    };
    return iconMap[type] || 'fas fa-cube';
};

// 还料离开
const handleComplete = async () => {
    const params = inList.value.map(item => {
        return item.stockInId;

    });

    console.log('提交参数:', params);
    await generateCFStockIn(params);
};

// 校验
const verify = () => {
    inList.value = [];
    validateList.value = [];
    materialList.value = [];
    getCFStockInByUser();
};

// 查询用户对应工装设备信息
const getCFStockInByUser = async () => {
    const info = localStorage.getItem('#LoginInfo');
    const userId = JSON.parse(info).userId;
    try {
        const res = await queryCFStockInByUser(userId);

        if (res.errorCode === 0) {
            if (res.datas && res.datas.length > 0) {
                materialList.value = res.datas;
                inList.value = res.datas;
                userMaterialList.value = res.datas;
                getInnerList();
            } else {
                materialList.value = [];
                userMaterialList.value = [];
                inList.value = [];
            }
        } else {
            showNotify({ type: 'danger', message: res.errorMessage,zIndex: 99999999 });
            getInnerList();
        }
    } catch (error) {
        console.error('获取物料列表API调用失败:', error);
        showNotify({ type: 'danger', message: '获取物料列表API调用失败' });
    }
};

// 获取物料列表(内侧校验)
const getInnerList = async () => {
    console.log('epcs:', epcs.value);
    // loading.value = true;
    const params = {
        epcList: epcs.value,
    };
    try {
        const res = await cfStockInLeave(params);

        if (res.errorCode === 0) {
            materialList.value = [...userMaterialList.value];
            isCanLeave.value = true;
            showNotify({ type: 'success', message: '校验成功，请先点击【还料离开】按钮，待闸机开门后离开',duration: 6000  });
        } else {
            if (res.errorMessage === '识别到工装设备') {
                isCanLeave.value = false;
                res.datas.forEach(item => {
                    item.isValid = true;
                });
                materialList.value = [...userMaterialList.value, ...res.datas];
                validateList.value = res.datas;
                showNotify({ type: 'danger', message: '检测到您已携带工装设备，请将工装设备全部还料后，再次点击【重新校验】按钮，待校验通过后,请在闸机开门后离开', duration: 6000 });
            } else {
                showNotify({ type: 'danger', message: res.errorMessage });
            }
        }
    } catch (error) {
        console.error('获取物料列表API调用失败:', error);
        showNotify({ type: 'danger', message: '获取物料列表API调用失败' });
    } finally {
        loading.value = false;
    }
};
// 还料离开(回填归还入库单入库时间)
const generateCFStockIn = async params => {
    loading.value = true;
    try {
        const res = await backfillCFStockInTime(params);

        if (res.errorCode === 0) {
            // 调用开门操作
            gateController('SHOTOPEN');
            showNotify({ type: 'success', message: '还料离开已完成！' });
            router.push('/home');
        } else {
            showNotify({ type: 'danger', message: res.errorMessage });
        }

    } catch (error) {
        console.error('生成CF离开单API调用失败:', error);
        showNotify({ type: 'danger', message: '生成CF离开单API调用失败' });
    } finally {
        loading.value = false;
    }
};


let timer = null; // 用于保存当前定时器引用

const addEpc = data => {
    const newEpcs = data.map(item => item.epc);
    
    // 将新的EPC数据添加到临时数组中，使用Set进行去重
    const uniqueEpcs = new Set([...tempEpcs.value, ...newEpcs]);
    tempEpcs.value = [...uniqueEpcs];
};

onMounted(() => {
    getCFStockInByUser();
    plugin.gateConfig.sendEpc = function(data){
        if (typeof(GATE_CONFIG) == 'undefined') {
            console.log('设备不支持读写器功能。');
        } else {
            addEpc(data);
        }
    };

    // 创建全局唯一定时器，每2秒执行一次
    timer = setInterval(() => {
        // 将临时数组的数据赋值给epcs
        epcs.value = [...tempEpcs.value];
        // 执行获取列表
        getInnerList();
        // 清空临时数组
        tempEpcs.value = [];
    }, 3000);
});

onUnmounted(() => {
    plugin.gateConfig.sendEpc = null;
    // 清除定时器
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
});
</script>

<style scoped>
/* ========== 基础样式 ========== */
.stock-requisition-page {
  width: 100%;
  height: 100vh;
  max-height: 100vh;
  position: relative;
  font-family: 'Microsoft YaHei', sans-serif;
  color: #fff;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 背景层 */
.bg-layer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #041c3d;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  z-index: 0;
}

/* ========== 主内容区域 ========== */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0 30px;
  position: relative;
  z-index: 10;
  min-height: 0;
  overflow: hidden;
}

/* 统计信息 */
.stats-section {
  background: rgba(9, 61, 140, 0.5);
  border: 1px solid #049FD8;
  border-radius: 12px;
  padding: 15px 20px;
  margin-bottom: 15px;
  flex-shrink: 0;
}

.stats-text {
  color: #7ec8ff;
  font-size: 16px;
}

/* ========== 卡片网格区域 ========== */
.card-grid-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow-y: auto;
  overflow-x: hidden;
  padding-bottom: 10px;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.card-grid-wrapper::-webkit-scrollbar {
  display: none;
}

/* 空状态 */
.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #7ec8ff;
  padding: 60px 0;
}

.empty-icon {
  font-size: 80px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-state p {
  font-size: 18px;
  margin: 0;
}

/* 卡片网格 - 4列布局 */
.card-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

/* ========== 设备卡片样式 ========== */
.inventory-card {
  background: rgba(5, 30, 60, 0.8);
  border: 2px solid #0d4a8a;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
}

.inventory-card:hover {
  border-color: #1e90ff;
  box-shadow: 0 0 20px rgba(30, 144, 255, 0.3);
  transform: translateY(-3px);
}

/* 校验失败卡片 - 红色警告 */
.inventory-card.not-in-stock-card {
  border-color: #ef4444;
}

/* 校验通过卡片 - 绿色 */
.inventory-card.in-stock-card {
  border-color: #10b981;
}

/* 卡片序号 - 左上角 */
.card-index {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #1e90ff 0%, #00bfff 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  z-index: 2;
  box-shadow: 0 2px 8px rgba(0, 191, 255, 0.4);
}

.card-index.not-in-stock-card {
  background: linear-gradient(135deg, #ef4444 0%, #f87171 100%);
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.4);
}

.card-index.in-stock-card {
  background: linear-gradient(135deg, #10b981 0%, #34d399 100%);
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.4);
}

/* 图片区域 */
.card-image {
  width: 100%;
  aspect-ratio: 3 / 4;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  margin: 15px;
  margin-bottom: 10px;
  border-radius: 8px;
  width: calc(100% - 30px);
}

.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f0f4f8 0%, #e8ecf0 100%);
  color: #94a3b8;
  font-size: 48px;
}

.image-placeholder.not-in-stock-card {
  background: linear-gradient(135deg, #ef4444 0%, #f87171 100%);
  color: #fff;
}

.image-placeholder.in-stock-card {
  background: linear-gradient(135deg, #10b981 0%, #34d399 100%);
  color: #fff;
}

/* 信息区域 */
.card-info {
  padding: 10px 15px 15px;
}

.info-row {
  display: flex;
  align-items: baseline;
  margin-bottom: 6px;
  font-size: 14px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  color: #7ec8ff;
  white-space: nowrap;
  margin-right: 5px;
}

.info-value {
  color: #fff;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 位置行样式 */
.location-row {
  display: flex;
  align-items: center;
  margin-top: 4px;
  padding-top: 4px;
  border-top: 1px solid rgba(30, 144, 255, 0.2);
}

.location-icon {
  color: #00bfff;
  font-size: 12px;
  margin-right: 6px;
}

/* ========== 状态区域（固定高度） ========== */
.card-status-section {
  padding: 12px 15px;
  border-top: 1px solid rgba(30, 144, 255, 0.3);
  background: rgba(9, 61, 140, 0.3);
  min-height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 状态标签 */
.status-badge {
  padding: 8px 20px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
}

.status-badge.not-in-stock-card {
  background: rgba(239, 68, 68, 0.3);
  border: 1px solid #ef4444;
  color: #fca5a5;
}

.status-badge.in-stock-card {
  background: rgba(16, 185, 129, 0.3);
  border: 1px solid #10b981;
  color: #6ee7b7;
}

/* ========== 底部操作按钮 ========== */
.bottom-actions {
  width: 100%;
  padding: 15px 30px;
  box-sizing: border-box;
  background: rgba(4, 28, 61, 0.95);
  z-index: 20;
  flex-shrink: 0;
}

.submit-btn {
  width: 100%;
  padding: 18px 0;
  background: #4a99e2;
  border: none;
  border-radius: 12px;
  font-size: 24px;
  font-weight: bold;
  color: #fff;
  cursor: pointer;
  transition: all 0.3s;
  letter-spacing: 8px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.submit-btn:hover:not(:disabled) {
  box-shadow: 0 0 30px rgba(16, 185, 129, 0.6);
  transform: translateY(-2px);
}

.submit-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: linear-gradient(90deg, #6b7280 0%, #9ca3af 100%);
}

/* ========== 响应式 - 横屏 ========== */
@media screen and (orientation: landscape) {
  .header-section {
    padding: 10px 20px;
  }

  .page-title {
    font-size: 22px;
  }

  .logout-btn {
    padding: 6px 14px;
    font-size: 13px;
    left: 20px;
  }

  .logout-btn i {
    font-size: 14px;
  }

  .header-actions {
    right: 20px;
  }

  .action-btn {
    padding: 6px 14px;
    font-size: 13px;
  }

  .action-btn i {
    font-size: 14px;
  }

  .main-content {
    padding: 0 20px;
  }

  .stats-section {
    padding: 10px 15px;
    margin-bottom: 10px;
  }

  .stats-text {
    font-size: 14px;
  }

  /* 卡片网格响应式 */
  .card-grid {
    grid-template-columns: repeat(6, 1fr);
    gap: 15px;
  }

  .card-index {
    width: 24px;
    height: 24px;
    font-size: 11px;
    top: 6px;
    left: 6px;
  }

  .card-image {
    margin: 10px;
    margin-bottom: 8px;
    width: calc(100% - 20px);
  }

  .image-placeholder {
    font-size: 36px;
  }

  .card-info {
    padding: 6px 10px 8px;
  }

  .info-row {
    font-size: 11px;
    margin-bottom: 3px;
  }

  .location-icon {
    font-size: 10px;
  }

  .card-status-section {
    padding: 8px 10px;
    min-height: 40px;
  }

  .status-badge {
    padding: 5px 12px;
    font-size: 11px;
    gap: 4px;
  }

  .bottom-actions {
    padding: 10px 20px;
  }

  .submit-btn {
    padding: 12px 0;
    font-size: 18px;
    letter-spacing: 6px;
    border-radius: 8px;
  }
}
</style>
