<script setup lang="ts">
/**
 * 防汛物资管理 — 物资库存列表
 *
 * 展示防汛物资库存情况，支持按类型筛选、搜索和下拉刷新，
 * 每条物资显示库存数量和库存状态。
 * DESIGN: #1E74FF NavBar, #F4F7F8 bg, white cards border-radius 10px.
 */
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'

const router = useRouter()

// ── 类型 ──
type MaterialType = 'pump' | 'sandbag' | 'tool' | 'rescue'
type StockStatus = 'sufficient' | 'normal' | 'low' | 'shortage'

interface Material {
  id: number
  name: string
  type: MaterialType
  stock: number
  unit: string
  minStock: number
  status: StockStatus
  location: string
}

// ── 状态 ──
const searchText = ref('')
const activeTab = ref(0)
const loading = ref(false)
const refreshing = ref(false)

// ── 映射 ──
const typeMap: Record<MaterialType, string> = {
  pump: '水泵类',
  sandbag: '沙袋类',
  tool: '工具类',
  rescue: '救援类',
}

const typeColorMap: Record<MaterialType, string> = {
  pump: '#1989fa',
  sandbag: '#ff976a',
  tool: '#07c160',
  rescue: '#ee0a24',
}

const stockStatusMap: Record<StockStatus, { label: string; type: string; icon: string }> = {
  sufficient: { label: '充足', type: 'success', icon: 'passed' },
  normal: { label: '正常', type: 'primary', icon: 'info-o' },
  low: { label: '偏低', type: 'warning', icon: 'warning-o' },
  shortage: { label: '紧缺', type: 'danger', icon: 'close' },
}

const typeTabs = ['all', 'pump', 'sandbag', 'tool', 'rescue']
const typeTabNames = ['全部', '水泵类', '沙袋类', '工具类', '救援类']

// ── 数据 ──
const materials = ref<Material[]>([])

const mockMaterials: Material[] = [
  { id: 1, name: '柴油水泵', type: 'pump', stock: 12, unit: '台', minStock: 5, status: 'sufficient', location: '1号仓库' },
  { id: 2, name: '防洪沙袋', type: 'sandbag', stock: 500, unit: '个', minStock: 200, status: 'sufficient', location: '2号仓库' },
  { id: 3, name: '救生衣', type: 'rescue', stock: 30, unit: '件', minStock: 50, status: 'low', location: '1号仓库' },
  { id: 4, name: '铁锹', type: 'tool', stock: 8, unit: '把', minStock: 20, status: 'shortage', location: '2号仓库' },
  { id: 5, name: '发电机', type: 'pump', stock: 6, unit: '台', minStock: 3, status: 'normal', location: '1号仓库' },
  { id: 6, name: '应急照明灯', type: 'tool', stock: 15, unit: '个', minStock: 10, status: 'normal', location: '3号仓库' },
  { id: 7, name: '救生圈', type: 'rescue', stock: 45, unit: '个', minStock: 30, status: 'sufficient', location: '3号仓库' },
  { id: 8, name: '编织袋', type: 'sandbag', stock: 80, unit: '条', minStock: 300, status: 'shortage', location: '2号仓库' },
]

// ── 计算属性 ──
const filteredList = computed(() => {
  let list = materials.value
  if (searchText.value) {
    const kw = searchText.value.toLowerCase()
    list = list.filter(m =>
      m.name.toLowerCase().includes(kw) ||
      m.location.toLowerCase().includes(kw)
    )
  }
  if (activeTab.value > 0) {
    list = list.filter(m => m.type === typeTabs[activeTab.value])
  }
  return list
})

// ── 方法 ──
async function fetchData() {
  loading.value = true
  await new Promise(resolve => setTimeout(resolve, 400))
  materials.value = mockMaterials
  loading.value = false
}

async function onRefresh() {
  refreshing.value = true
  await new Promise(resolve => setTimeout(resolve, 600))
  materials.value = [...mockMaterials]
  refreshing.value = false
  showToast('刷新成功')
}

function goInventory(item: Material) {
  router.push(`/managementInventory/${item.id}`)
}

/** 库存进度百分比 */
function stockPercent(item: Material): number {
  const max = Math.max(item.minStock * 2, item.stock)
  return Math.min((item.stock / max) * 100, 100)
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="page-container">
    <!-- 导航栏 -->
    <van-nav-bar title="物资管理" left-arrow fixed placeholder @click-left="router.back()" />

    <!-- 搜索栏 -->
    <van-search v-model="searchText" placeholder="搜索物资名称、存放位置" shape="round" />

    <!-- 标签页 -->
    <van-tabs v-model:active="activeTab" sticky color="var(--color-primary)">
      <van-tab v-for="(name, i) in typeTabNames" :key="i" :title="name" />
    </van-tabs>

    <!-- 下拉刷新 + 列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="pull-refresh-wrap">
      <!-- 加载骨架 -->
      <div v-if="loading" class="skeleton-wrap">
        <div v-for="i in 4" :key="i" class="skeleton-card">
          <van-skeleton title :row="2" />
        </div>
      </div>

      <!-- 空状态 -->
      <van-empty v-else-if="filteredList.length === 0" description="暂无物资">
        <van-button type="primary" size="small" @click="onRefresh">刷新</van-button>
      </van-empty>

      <!-- 物资卡片列表 -->
      <div v-else class="card-list">
        <div
          v-for="item in filteredList"
          :key="item.id"
          class="mat-card"
          @click="goInventory(item)"
        >
          <div class="card-hd">
            <div class="card-title-wrap">
              <span
                class="type-badge"
                :style="{ background: typeColorMap[item.type] }"
              >
                {{ typeMap[item.type] }}
              </span>
              <span class="card-name">{{ item.name }}</span>
            </div>
            <van-tag :type="stockStatusMap[item.status].type as any" size="medium">
              {{ stockStatusMap[item.status].label }}
            </van-tag>
          </div>

          <div class="card-bd">
            <div class="stock-info">
              <div class="stock-row">
                <span class="stock-label">库存数量</span>
                <span class="stock-value" :class="{ 'stock-low': item.status === 'low' || item.status === 'shortage' }">
                  {{ item.stock }} <small>{{ item.unit }}</small>
                </span>
              </div>
              <div class="stock-row">
                <span class="stock-label">最低库存</span>
                <span class="stock-min">{{ item.minStock }} {{ item.unit }}</span>
              </div>
            </div>

            <!-- 库存进度条 -->
            <div class="stock-progress">
              <div
                class="progress-fill"
                :style="{
                  width: stockPercent(item) + '%',
                  background: typeColorMap[item.type],
                }"
              />
            </div>
          </div>

          <div class="card-ft">
            <span class="card-location">
              <van-icon name="location-o" size="13" />
              {{ item.location }}
            </span>
          </div>
        </div>
      </div>
    </van-pull-refresh>
  </div>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background: var(--color-bg-page);

  :deep(.van-nav-bar) {
    background: var(--color-primary);
    --van-nav-bar-title-text-color: #fff;
    --van-nav-bar-text-color: #fff;
    --van-nav-bar-icon-color: #fff;
  }
}

.pull-refresh-wrap {
  min-height: calc(100vh - 140px);
}

// ── 骨架屏 ──
.skeleton-wrap {
  padding: 8px 16px;
}
.skeleton-card {
  padding: 16px;
  margin-bottom: 8px;
  background: var(--color-bg-card);
  border-radius: 10px;
}

// ── 物资卡片 ──
.card-list {
  padding: 8px 12px;
}

.mat-card {
  background: var(--color-bg-card);
  border-radius: 10px;
  padding: 16px;
  margin-bottom: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
  cursor: pointer;

  &:active {
    opacity: 0.85;
  }

  .card-hd {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 14px;
    gap: 8px;
  }

  .card-title-wrap {
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 1;
    min-width: 0;
  }

  .type-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 600;
    color: #fff;
    white-space: nowrap;
    flex-shrink: 0;
  }

  .card-name {
    font-size: 15px;
    font-weight: 600;
    color: var(--color-text-primary);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .card-bd {
    margin-bottom: 10px;
  }

  // ── 库存信息 ──
  .stock-info {
    margin-bottom: 8px;
  }

  .stock-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
  }

  .stock-label {
    font-size: 13px;
    color: var(--color-text-secondary);
  }

  .stock-value {
    font-size: 18px;
    font-weight: 700;
    color: var(--color-text-primary);

    &.stock-low {
      color: var(--color-danger);
    }

    small {
      font-size: 12px;
      font-weight: 400;
      color: var(--color-text-secondary);
    }
  }

  .stock-min {
    font-size: 12px;
    color: var(--color-text-placeholder);
  }

  // ── 进度条 ──
  .stock-progress {
    height: 6px;
    background: var(--color-border-light);
    border-radius: 3px;
    overflow: hidden;
  }

  .progress-fill {
    height: 100%;
    border-radius: 3px;
    transition: width 0.6s ease;
  }

  // ── 底部 ──
  .card-ft {
    padding-top: 8px;
    border-top: 1px solid var(--color-border-light);
  }

  .card-location {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    color: var(--color-text-placeholder);
  }
}
</style>
