<template>
  <view class="page">
    <!-- 导航栏 -->
    <NavBar title="库存查询" :showBack="true" />
    
    <!-- 统计卡片 -->
    <view class="stats-section">
      <view class="stats-grid">
        <view class="stat-card warning">
          <text class="stat-value">{{ inventoryStats.lowStockCount }}</text>
          <text class="stat-label">库存预警</text>
          <view class="alert-dot"></view>
        </view>
        <view class="stat-card error">
          <text class="stat-value">{{ inventoryStats.zeroStockCount }}</text>
          <text class="stat-label">缺货商品</text>
          <view class="alert-dot"></view>
        </view>
        <view class="stat-card primary">
          <text class="stat-value">{{ inventoryStats.totalStock }}</text>
          <text class="stat-label">总库存量</text>
        </view>
      </view>
    </view>
    
    <!-- 筛选栏 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view 
          class="filter-tab" 
          :class="{ active: currentStatus === 'all' }"
          @click="changeStatus('all')"
        >
          <text>全部</text>
        </view>
        <view 
          class="filter-tab warning" 
          :class="{ active: currentStatus === 'low' }"
          @click="changeStatus('low')"
        >
          <text>低库存</text>
        </view>
        <view 
          class="filter-tab error" 
          :class="{ active: currentStatus === 'out' }"
          @click="changeStatus('out')"
        >
          <text>缺货</text>
        </view>
      </view>
    </view>
    
    <!-- 库存列表 -->
    <scroll-view 
      class="inventory-scroll" 
      scroll-y 
      @scrolltolower="loadMore"
    >
      <view class="inventory-list">
        <view 
          class="inventory-card" 
          v-for="item in inventoryList" 
          :key="item.id"
        >
          <view class="card-header">
            <view class="product-info">
              <text class="product-name">{{ item.productName }}</text>
              <text class="location">{{ item.shopName }} · {{ item.deviceName }}</text>
            </view>
            <view class="status-badge" :class="item.status">
              <text>{{ getStatusText(item.status) }}</text>
            </view>
          </view>
          
          <view class="card-body">
            <view class="progress-bar">
              <view 
                class="progress-fill" 
                :class="item.status"
                :style="{ width: getProgressWidth(item) + '%' }"
              ></view>
            </view>
            <view class="stock-info">
              <text class="current">当前 {{ item.currentStock }}</text>
              <text class="range">预警 {{ item.minStock }} / 上限 {{ item.maxStock }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <view class="loading-more" v-if="loading">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
      
      <view class="no-more" v-if="!hasMore && inventoryList.length > 0">
        <text>— 没有更多了 —</text>
      </view>
      
      <view class="empty-state" v-if="!loading && inventoryList.length === 0">
        <view class="empty-icon">
          <view class="empty-icon-inner"></view>
        </view>
        <text class="empty-text">暂无库存数据</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { logger } from '@/utils/logger';
import NavBar from '@/components/NavBar.vue';
import { getInventoryList, getInventoryStatistics } from '@/api/inventory';
import { formatMoney as formatMoneyUtil } from '@/utils/common';

const inventoryList = ref<any[]>([]);
const inventoryStats = ref({
  totalRecords: 0,
  lowStockCount: 0,
  zeroStockCount: 0,
  totalStock: 0
});
const currentStatus = ref('all');
const loading = ref(false);
const hasMore = ref(true);
const page = ref(1);
const pageSize = 10;

const formatMoney = formatMoneyUtil;

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    normal: '正常',
    low: '低库存',
    out: '缺货'
  };
  return map[status] || '未知';
};

const getProgressWidth = (item: any) => {
  if (item.maxStock === 0) return 0;
  return Math.min(100, (item.currentStock / item.maxStock) * 100);
};

const loadStats = async () => {
  try {
    const stats = await getInventoryStatistics();
    inventoryStats.value = stats || inventoryStats.value;
  } catch (error) {
    logger.warn('加载库存统计失败', error);
  }
};

const changeStatus = (status: string) => {
  currentStatus.value = status;
  page.value = 1;
  hasMore.value = true;
  loadInventory();
};

const loadInventory = async () => {
  loading.value = true;
  try {
    const params: any = { page: page.value, pageSize };
    if (currentStatus.value === 'low') {
      params.lowStock = true;
    } else if (currentStatus.value === 'out') {
      params.stockStatus = 0;
    }
    const res = await getInventoryList(params);
    if (!res) return;

    if (page.value === 1) {
      inventoryList.value = res.list || [];
    } else {
      inventoryList.value = [...inventoryList.value, ...res.list];
    }
    
    hasMore.value = inventoryList.value.length < res.total;
  } catch (error) {
    logger.warn('加载库存列表失败', error);
  } finally {
    loading.value = false;
  }
};

const loadMore = () => {
  if (loading.value || !hasMore.value) return;
  page.value++;
  loadInventory();
};

onMounted(() => {
  loadStats();
  loadInventory();
});
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: $bg-color-page;
  display: flex;
  flex-direction: column;
}

/* 统计区域 */
.stats-section {
  padding: 12rpx 24rpx;
  background: $bg-color-card;
  border-bottom: 1rpx solid $border-color;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1.2fr;
  gap: 12rpx;
}

.stat-card {
  background: $bg-color-page;
  border: 1rpx solid $border-color;
  border-radius: 16rpx;
  padding: 20rpx 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  
  &.warning {
    border-top: 3rpx solid $accent-color;
  }
  
  &.error {
    border-top: 3rpx solid $error-color;
  }
  
  &.primary {
    border-top: 3rpx solid $primary-color;
  }
  
  .stat-value {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: 700;
    color: $text-color-primary;
    margin-bottom: 4rpx;
  }
  
  .stat-label {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22rpx;
    color: $text-color-tertiary;
  }
  
  .alert-dot {
    position: absolute;
    top: 12rpx;
    right: 12rpx;
    width: 10rpx;
    height: 10rpx;
    border-radius: 50%;
    animation: pulse 2s ease-in-out infinite;
  }
  
  &.warning .alert-dot {
    background: $accent-color;
  }
  
  &.error .alert-dot {
    background: $error-color;
  }
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 筛选栏 */
.filter-section {
  padding: 12rpx 24rpx;
  background: $bg-color-card;
}

.filter-tabs {
  display: flex;
  gap: 10rpx;
  
  .filter-tab {
    padding: 12rpx 24rpx;
    background: $bg-color-page;
    border: 2rpx solid $border-color;
    border-radius: 20rpx;
    font-size: 26rpx;
    color: $text-color-tertiary;
    transition: all 0.15s;
    
    &.active {
      color: #fff;
    }
    
    &.warning.active {
      background: $accent-color;
      border-color: $accent-color;
    }
    
    &.error.active {
      background: $error-color;
      border-color: $error-color;
    }
    
    &:not(.warning):not(.error).active {
      background: $primary-color;
      border-color: $primary-color;
    }
  }
}

/* 库存列表 */
.inventory-scroll {
  flex: 1;
  height: 0;
}

.inventory-list {
  padding: 16rpx 24rpx;
}

.inventory-card {
  background: $bg-color-card;
  border: 1rpx solid $border-color;
  border-radius: 16rpx;
  margin-bottom: 12rpx;
  overflow: hidden;
  transition: transform 0.15s;
  
  &:active {
    transform: scale(0.98);
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20rpx 24rpx 16rpx;
  
  .product-info {
    .product-name {
      display: block;
      font-size: 28rpx;
      font-weight: 600;
      color: $text-color-primary;
      margin-bottom: 4rpx;
    }
    
    .location {
      font-size: 22rpx;
      color: $text-color-muted;
    }
  }
  
  .status-badge {
    padding: 6rpx 14rpx;
    border-radius: 8rpx;
    font-size: 22rpx;
    font-weight: 500;
    
    &.normal {
      background: $success-color-bg;
      color: $primary-color;
    }
    
    &.low {
      background: $accent-color-bg;
      color: $accent-color;
    }
    
    &.out {
      background: $error-color-bg;
      color: $error-color;
    }
  }
}

.card-body {
  padding: 0 24rpx 20rpx;
  
  .progress-bar {
    height: 10rpx;
    background: $bg-color-secondary;
    border-radius: 5rpx;
    overflow: hidden;
    margin-bottom: 10rpx;
    
    .progress-fill {
      height: 100%;
      border-radius: 5rpx;
      
      &.normal { background: $primary-color; }
      &.low { background: $accent-color; }
      &.out { background: $error-color; }
    }
  }
  
  .stock-info {
    display: flex;
    justify-content: space-between;
    
    .current {
      font-size: 26rpx;
      color: $text-color-primary;
      font-weight: 500;
    }
    
    .range {
      font-size: 22rpx;
      color: $text-color-muted;
    }
  }
}

/* 加载状态 */
.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  padding: 32rpx;
  color: $text-color-muted;
  font-size: 24rpx;
  
  .loading-spinner {
    width: 32rpx;
    height: 32rpx;
    border: 3rpx solid $border-color;
    border-top-color: $primary-color;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.no-more {
  text-align: center;
  padding: 32rpx;
  font-size: 24rpx;
  color: $text-color-placeholder;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-icon {
    width: 120rpx;
    height: 120rpx;
    background: $bg-color-secondary;
    border-radius: 24rpx;
    margin-bottom: 20rpx;
    display: flex;
    align-items: flex-end;
    justify-content: center;
    padding-bottom: 24rpx;
    gap: 8rpx;
    
    .empty-icon-inner {
      display: flex;
      align-items: flex-end;
      gap: 8rpx;
      
      &::before, &::after, & {
        content: '';
        width: 16rpx;
        background: $text-color-placeholder;
        border-radius: 4rpx;
      }
      
      &::before { height: 32rpx; }
      & { height: 48rpx; }
      &::after { height: 24rpx; }
    }
  }
  
  .empty-text {
    font-size: 28rpx;
    color: $text-color-muted;
  }
}
</style>
