<script setup lang="ts">
import AdminStatusTag from '@/components/admin/AdminStatusTag.vue'
import type { AdminInventoryItemListItem } from '@/types/admin'
import { hasAdminRole } from '@/utils/admin-auth'

import { invalidateAdminInventoryItem, releaseAdminInventoryItem } from '@/services/admin'

defineProps<{
  loading: boolean
  items: AdminInventoryItemListItem[]
  pagination: { page: number; pageSize: number; total: number }
  pageSummary: { availableCount: number; reservedCount: number; deliveredCount: number; invalidCount: number }
  actionLoadingId: number | null
  loadInventoryItems: (page?: number) => Promise<void>
  runRowAction: (id: number, action: () => Promise<unknown>, msg: string, confirm: string) => Promise<void>
  formatInventoryStatus: (item: AdminInventoryItemListItem) => string
  getCredentialTypeLabel: (value: string) => string
  formatAdminDateTime: (value: string) => string
}>()
</script>

<template>
  <div class="table-toolbar">
    当前筛选共 {{ pagination.total }} 条，本页可用 {{ pageSummary.availableCount }} 条，预占
    {{ pageSummary.reservedCount }} 条，已发放 {{ pageSummary.deliveredCount }} 条，作废
    {{ pageSummary.invalidCount }} 条。
  </div>

  <el-table :data="items" stripe size="small" class="inventory-table data-table">
    <el-table-column label="库存项" min-width="200">
      <template #default="{ row }">
        <div class="item-cell">
          <RouterLink
            v-if="row.reservedByTaskNo"
            :to="`/admin/tasks/${row.reservedByTaskNo}`"
            class="item-title"
            >#{{ row.inventoryItemId }}</RouterLink
          >
          <span v-else class="item-title">#{{ row.inventoryItemId }}</span>
          <code class="item-value">{{ row.displayValue }}</code>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="内部履约 SKU" min-width="160">
      <template #default="{ row }">
        <div class="sku-cell">
          <span class="sku-title">{{ row.skuCode }}</span>
          <span class="sku-subline">{{ getCredentialTypeLabel(row.credentialType) }}</span>
          <span class="sku-subline sku-raw">{{ row.credentialType || '-' }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="批次 / 库存组" min-width="160">
      <template #default="{ row }">
        <div class="info-cell">
          <span class="info-subline">批次 {{ row.batchNo || '未分批' }}</span>
          <span class="info-subline">库存组 {{ row.inventoryGroupCode || '未分组' }}</span>
          <span class="status-copy">{{ formatInventoryStatus(row) }}</span>
          <span v-if="row.invalidReason" class="status-warning"
            >原因：{{ row.invalidReason }}</span
          >
        </div>
      </template>
    </el-table-column>
    <el-table-column label="状态 / 绑定" min-width="180">
      <template #default="{ row }">
        <div class="status-stack">
          <AdminStatusTag :status="row.status" />
          <AdminStatusTag :status="row.systemBindingStatus" />
          <AdminStatusTag :status="row.userBindingStatus" />
        </div>
      </template>
    </el-table-column>
    <el-table-column label="关联任务 / 订单" min-width="160">
      <template #default="{ row }">
        <div class="info-cell">
          <span class="link-title">{{ row.reservedByTaskNo || '-' }}</span>
          <span class="link-subline">任务号</span>
          <span class="link-title">{{ row.platformOrderId || '-' }}</span>
          <span class="link-subline">平台订单号</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="时间" min-width="180">
      <template #default="{ row }">
        <div class="info-cell">
          <span class="time-line">入库 {{ formatAdminDateTime(row.createdAt) }}</span>
          <span class="time-line">更新 {{ formatAdminDateTime(row.updatedAt) }}</span>
          <span v-if="row.deliveredAt" class="time-line"
            >发放 {{ formatAdminDateTime(row.deliveredAt) }}</span
          >
        </div>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="120" align="center">
      <template #default="{ row }">
        <div class="action-stack">
          <el-button
            v-if="hasAdminRole('admin') && row.status === 'reserved'"
            :loading="actionLoadingId === row.inventoryItemId"
            size="small"
            @click="
              runRowAction(
                row.inventoryItemId,
                () => releaseAdminInventoryItem(row.inventoryItemId),
                '库存项已释放',
                `确认释放库存项 #${row.inventoryItemId} 吗？释放后任务需要重新分配库存。`,
              )
            "
            >释放</el-button
          >
          <el-button
            v-if="hasAdminRole('admin') && row.status === 'available'"
            :loading="actionLoadingId === row.inventoryItemId"
            size="small"
            type="danger"
            plain
            @click="
              runRowAction(
                row.inventoryItemId,
                () =>
                  invalidateAdminInventoryItem(row.inventoryItemId, {
                    reason: '后台手动作废',
                  }),
                '库存项已作废',
                `确认作废库存项 #${row.inventoryItemId} 吗？作废后不会再参与自动分配。`,
              )
            "
            >作废</el-button
          >
        </div>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    v-if="pagination.total > 0"
    v-model:current-page="pagination.page"
    :page-size="pagination.pageSize"
    :total="pagination.total"
    layout="total, prev, pager, next"
    class="pagination-center"
    @current-change="loadInventoryItems"
  />
</template>

<style scoped>
@import '../../../../styles/admin-list-pages.css';

.table-toolbar {
  margin-bottom: var(--space-2);
  padding-top: var(--space-2);
  color: var(--text-secondary);
  font-size: var(--text-xs);
  line-height: 1.6;
  word-break: break-word;
}

.item-cell,
.sku-cell,
.info-cell {
  display: grid;
  gap: 6px;
}

.item-title,
.sku-title,
.link-title {
  color: var(--text-primary);
  font-weight: 700;
}

.item-value {
  display: inline-flex;
  max-width: 100%;
  width: fit-content;
  padding: 6px 8px;
  border-radius: var(--radius-sm);
  background: rgba(15, 23, 42, 0.06);
  color: #0f172a;
  white-space: pre-wrap;
  word-break: break-all;
}

.info-subline,
.sku-subline,
.link-subline,
.time-line,
.status-copy {
  color: var(--text-secondary);
  font-size: var(--text-xs);
  line-height: 1.5;
}

.sku-raw {
  font-family: var(--font-mono);
  font-size: var(--text-xs);
}

.status-stack,
.action-stack {
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-2);
  align-items: center;
}
.action-stack {
  justify-content: center;
}

.status-warning {
  color: #b54708;
  font-size: var(--text-xs);
}

@media (max-width: 640px) {
  .status-stack,
  .action-stack {
    justify-content: flex-start;
  }
}
</style>
