<!-- 还料入库 -->
<template>
  <div class="page-container">
    <!-- 顶部信息栏 -->
    <PageHeader title="还料入库" />

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 页面标题 -->
      <div class="page-header-row">
        <van-button type="primary" @click="verify">
          <i class="fas fa-sync-alt mr-1" /> 重新校验
        </van-button>
      </div>

      <!-- 卡片容器 -->
      <div class="card-container">
        <!-- 卡片列表区域 -->
        <div class="card-list-wrapper">
          <van-empty v-if="materialList.length === 0" description="暂无数据" />

          <!-- 卡片列表 -->
          <div v-else class="card-list">
            <div
              v-for="(item, index) in materialList" :key="item.id || index" :class="getCardClass(item.remarks)"
              class="inventory-card"
            >
              <div class="card-header">
                <div class="card-header-left">
                  <div class="custom-avatar">
                    <!-- :style="{ backgroundColor: getStatusColor(item.remarks) }" -->
                    <i :class="getInventoryIcon(item.inventoryType)" />
                  </div>
                  <div class="ml-4 card-title-info">
                    <div class="card-name">{{ item.inventoryName }}</div>
                    <div class="card-subtitle">编号: {{ item.inventoryNo }}</div>
                  </div>
                </div>
                <div class="card-header-right">
                  <div class="card-location">
                    <i class="fas fa-map-marker-alt mr-2" />
                    <span>{{ item.positionName || '-' }}</span>
                    <span class="mx-2">/</span>
                    <span>{{ item.remarks || '-' }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页区域（固定底部） -->
        <div v-if="materialList.length > 0" class="pagination-wrapper">
          <span class="text-gray-600">共 {{ materialList.length }} 条数据</span>
        </div>
      </div>
    </main>
    <!-- 底部完成按钮 -->
    <div class="bottom-actions">
      <van-button
        type="primary" size="large" :disabled="notInStockCount === 0" class="submit-btn"
        @click="handleComplete"
      >
        <i class="fas fa-check-circle mr-2" />
        还料入库
      </van-button>
    </div>
  </div>
  <Loading v-if="loading" />
</template>

<script setup>
import { useRouter } from 'vue-router';
import { showNotify } from 'vant';
import PageHeader from '../common/PageHeader.vue';
import { ref, reactive, onMounted, computed } from 'vue';
import { cfStockIn, createStockIn, cfStockInLeave } from '../api/stockIn.js';

const router = useRouter();

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

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

// 分页配置
const pagination = reactive({
    start: 1,
    lang: 10,
    total: 0,
});

// 计算不在库的数量
const notInStockCount = computed(() => {
    return materialList.value.filter(item => item.remarks === '不在库').length;
});

// 根据 remarks 返回卡片样式类
const getCardClass = remarks => {
    if (remarks === '不在库') {
        return 'not-in-stock-card';
    } else if (remarks === '在库') {
        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 getStatusColor = remarks => {
//     if (remarks === '不在库') {
//         return '#3b82f6'; // 蓝色 - 需要入库
//     } else if (remarks === '在库') {
//         return '#10b981'; // 绿色 - 已在库
//     }
//     return '#6b7280'; // 灰色 - 默认
// };

// 还料入库
const handleComplete = async () => {
    // 只处理不在库的数据
    const notInStockItems = materialList.value.filter(item => item.remarks === '不在库');

    if (notInStockItems.length === 0) {
        showNotify({ type: 'warning', message: '没有需要入库的物料！' });
        return;
    }

    const params = [];
    notInStockItems.forEach(item => {
        if (item.remarks === '不在库') {
            params.push({
                inventoryId: item.inventoryId,
            });
        }
    });

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

// 校验
const verify = () => {
    getList();
};

// 获取物料列表(外侧校验)
const getList = async () => {
    loading.value = true;
    try {

        const res = await cfStockIn();

        if (res.errorCode === 0) {
            if (res.datas && res.datas.length > 0) {
                materialList.value = res.datas;
                pagination.total = materialList.value.length;
            } else {
                materialList.value = [];
            }
        } else {
            showNotify({ type: 'warning', message: res.errorMessage });
        }
    } catch (error) {
        console.error('获取物料列表API调用失败:', error);
        showNotify({ type: 'danger', message: '获取物料列表API调用失败' });
    } finally {
        loading.value = false;
    }
};
// 获取物料列表(内侧校验)
const getInnerList = async () => {
    loading.value = true;
    try {
        const res = await cfStockInLeave();

        if (res.errorCode === 0) {
            if (res.datas && res.datas.length > 0) {
                materialList.value = res.datas;
                pagination.total = materialList.value.length;
                showNotify({ type: 'warning', message: '检测到您已携带工装设备，请将工装设备全部还料后，再次点击【重新校验】按钮，待校验通过后,请在闸机开门后离开', duration: 8000 });
            } else {
                showNotify({ type: 'success', message: '校验成功，请在闸机开门后离开' });
            }
        } else {
            showNotify({ type: 'warning', message: res.errorMessage });
        }
    } catch (error) {
        console.error('获取物料列表API调用失败:', error);
        showNotify({ type: 'danger', message: '获取物料列表API调用失败' });
    } finally {
        loading.value = false;
    }
};
// 生成CF入库单
const generateCFStockIn = async params => {
    loading.value = true;
    try {
        const res = await createStockIn(params);

        if (res.errorCode === 0) {
            showNotify({ type: 'success', message: '入库申请已完成，还料任务已创建！' });
            router.push('/home');
        } else {
            showNotify({ type: 'warning', message: res.errorMessage });
        }

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

onMounted(() => {
    getList();
});
</script>

<style scoped>
/* 页面容器 - 固定高度布局 */
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f9fafb;
  overflow: hidden;
}

/* 主内容区 - 可滚动 */
.main-content {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
}

/* 操作按钮行 */
.page-header-row {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 1rem;
}

/* 卡片容器 */
.card-container {
  flex: 1;
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

/* 卡片列表包装器（可滚动区域） */
.card-list-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  min-height: 0;
}

/* 卡片列表（单列布局） */
.card-list {
  display: flex;
  flex-direction: column;
}

.card-list>* {
  margin-bottom: 1rem;
}

.card-list>*:last-child {
  margin-bottom: 0;
}

/* 分页包装器（固定底部） */
.pagination-wrapper {
  padding: 0.5rem 1.5rem;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
  background-color: #fafafa;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* 底部操作按钮 */
.bottom-actions {
  position: sticky;
  bottom: 0;
  padding: 0 1rem 1rem 1rem;
  background-color: #f9fafb;
  display: flex;
  justify-content: flex-end;
  z-index: 10;
}

/* 库存卡片样式 */
.inventory-card {
  padding: 1rem 1.5rem;
  transition: all 0.25s ease;
  border: 2px solid #e5e7eb;
  background-color: #ffffff;
  border-radius: 0.5rem;
  cursor: pointer;
}

.inventory-card:hover {
  border-color: #93c5fd;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.1);
}

/* 不在库卡片 */
.not-in-stock-card {
  background-color: #eff6ff !important;
  border-color: #93c5fd !important;
}

/* 在库卡片 */
.in-stock-card {
  background-color: #f5f5f5 !important;
  border-color: #d1d5db !important;
}

/* 卡片标题区域 */
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.card-header>* {
  margin-right: 1rem;
}

.card-header>*:last-child {
  margin-right: 0;
}

.card-header-left {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.card-header-right {
  display: flex;
  align-items: center;
}

.card-header-right>* {
  margin-left: 0.75rem;
}

.card-header-right>*:first-child {
  margin-left: 0;
}

/* 卡片标题信息 */
.card-title-info {
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.card-title-info>* {
  margin-bottom: 0.25rem;
}

.card-title-info>*:last-child {
  margin-bottom: 0;
}

.card-name {
  font-size: 1.125rem;
  font-weight: 600;
  color: #111827;
  line-height: 1.5;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-subtitle {
  font-size: 0.875rem;
  color: #6b7280;
  line-height: 1.4;
}

/* 卡片位置信息 */
.card-location {
  display: flex;
  align-items: center;
  padding: 0.5rem 1rem;
  background-color: #f3f4f6;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  color: #374151;
  white-space: nowrap;
}

.card-location i {
  color: #3b82f6;
}

/* 按钮样式 */
:deep(.van-button--primary) {
  background-color: #3b82f6;
  border-color: #3b82f6;
}

:deep(.van-button--primary:active) {
  background-color: #2563eb;
  border-color: #2563eb;
}

:deep(.van-button--disabled) {
  opacity: 0.5;
  cursor: not-allowed;
}

.submit-btn {
  background-color: #10b981 !important;
  border-color: #10b981 !important;
  width: auto;
  padding: 0 24px;
}

:deep(.submit-btn.van-button--primary) {
  background-color: #10b981 !important;
  border-color: #10b981 !important;
}

:deep(.submit-btn.van-button--primary:active) {
  background-color: #059669 !important;
  border-color: #059669 !important;
}

/* 自定义头像 */
.custom-avatar {
  width: 42px;
  height: 42px;
  border-radius: 50%;
  background-color: #3b82f6;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  flex-shrink: 0;
}
</style>
