<template>
  <view class="page">
    <NavBar title="库存盘点" showBack />

    <!-- 设备信息 -->
    <view class="device-bar">
      <text class="device-bar-text">{{ deviceId }}<text v-if="deviceName"> · {{ deviceName }}</text></text>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-icon"></view>
      <input class="search-input" v-model="searchKeyword" placeholder="搜索商品名称或编码" confirm-type="search" />
      <view class="search-clear" v-if="searchKeyword" @click="searchKeyword = ''"><text>✕</text></view>
    </view>

    <!-- 加载中 -->
    <view class="empty-state" v-if="loading">
      <text class="empty-text">加载中...</text>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else-if="auditItems.length === 0">
      <view class="empty-icon-box"><view class="empty-doc-icon"></view></view>
      <text class="empty-text">暂无商品数据</text>
    </view>

    <!-- 搜索无结果 -->
    <view class="empty-state" v-else-if="currentFloors.length === 0">
      <text class="empty-text">未找到匹配商品</text>
    </view>

    <!-- 楼层列表 -->
    <view v-else class="floors-scroll">
      <view v-for="floor in currentFloors" :key="'floor-' + floor.floor" class="floor-card">
        <!-- 楼层头部（单层柜模版不显示层号） -->
        <view class="floor-header" v-if="currentFloors.length > 1">
          <view class="floor-badge">{{ floor.floor }}</view>
          <text class="floor-title">{{ floor.name }}</text>
          <text class="floor-count">{{ floor.entries.length }}件商品</text>
        </view>
        <view class="floor-header floor-header-single" v-else>
          <text class="floor-title">商品清单</text>
          <text class="floor-count">{{ floor.entries.length }}件商品</text>
        </view>

        <!-- 商品网格（3列） -->
        <view class="goods-grid">
          <view v-for="entry in floor.entries" :key="entry.idx" class="goods-cell">
            <view class="goods-cell-inner">
            <!-- 商品图片 -->
            <view class="cell-image-wrap">
              <image
                v-if="entry.item.productImage"
                :src="entry.item.productImage"
                class="cell-image"
                mode="aspectFill"
              />
              <view v-else class="cell-image-placeholder">
                <text>无图</text>
              </view>
            </view>

            <!-- 商品名称 -->
            <text class="cell-name">{{ entry.item.productName || '未知' }}</text>

            <!-- 状态标签 -->
            <view class="cell-badge" :class="getDiffClass(entry.item, entry.idx)">{{ getDiffLabel(entry.item, entry.idx) }}</view>

            <!-- 库存信息 -->
            <view class="cell-stock-row">
              <text class="cell-stock-label">标{{ entry.item.standardStock }}</text>
              <text class="cell-stock-cur">当{{ auditItems[entry.idx]?.newStock ?? 0 }}</text>
            </view>

            <!-- 数量调节 -->
            <view class="cell-qty">
              <view class="cell-qty-btn" @click="decrease(entry.idx)"><text>-</text></view>
              <input class="cell-qty-input" type="number" v-model.number="auditItems[entry.idx].newStock" />
              <view class="cell-qty-btn" @click="increase(entry.idx)"><text>+</text></view>
            </view>

            <!-- 快捷操作 -->
            <view class="cell-actions">
              <text class="cell-action-btn" @click="setToStandard(entry.idx)">设标</text>
              <text class="cell-action-divider">|</text>
              <text class="cell-action-btn cell-action-reset" @click="setToCurrent(entry.idx)">重置</text>
            </view>
            </view>
          </view>
        </view>
      </view>

      <view class="scroll-bottom-spacer"></view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar" v-if="auditItems.length > 0">
      <text class="total-label">修正 <text class="total-num">{{ changedCount }}</text> 项</text>
      <view class="submit-btn" :class="{ disabled: submitting || changedCount === 0 }" @click="handleSubmit">
        <view class="btn-spinner" v-if="submitting"></view>
        <text>{{ submitting ? '提交中' : '提交盘点' }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import NavBar from '@/components/NavBar.vue';
import { getDeviceInventory } from '@/api/replenish';
import { adjustStock } from '@/api/inventory';

// ── 类型 ──
interface AuditEntry {
  productId: number | null;
  productCode: string;
  productName: string;
  productImage: string;
  standardStock: number;
  newStock: number;
  originalStock: number;
  floorNumber: number;
  floorName: string;
}

interface FloorGroup {
  floor: number;
  name: string;
  entries: { item: AuditEntry; idx: number }[];
}

// ── 状态 ──
const deviceId = ref('');
const deviceName = ref('');
const loading = ref(true);
const auditItems = ref<AuditEntry[]>([]);
const submitting = ref(false);
const searchKeyword = ref('');

// ── 搜索过滤 ──
const filteredItems = computed(() => {
  const kw = searchKeyword.value.trim().toLowerCase();
  return auditItems.value
    .map((item, idx) => ({ item, idx }))
    .filter(({ item }) => {
      if (!kw) return true;
      const name = (item.productName || '').toLowerCase();
      const code = (item.productCode || '').toLowerCase();
      return name.includes(kw) || code.includes(kw);
    });
});

// ── 按楼层分组 ──
const currentFloors = computed(() => {
  const map = new Map<number, { item: AuditEntry; idx: number }[]>();
  for (const { item, idx } of filteredItems.value) {
    const fn = item.floorNumber;
    if (!map.has(fn)) map.set(fn, []);
    map.get(fn)!.push({ item, idx });
  }
  return Array.from(map.entries())
    .sort((a, b) => a[0] - b[0])
    .map(([floor, entries]) => ({
      floor,
      name: entries[0]?.item.floorName || ('第' + floor + '层'),
      entries,
    }));
});

// ── 变更计数 ──
const changedCount = computed(() =>
  auditItems.value.filter(i => i.productId != null && i.newStock !== i.originalStock).length
);

// ── 数量操作 ──
function decrease(index: number) {
  const it = auditItems.value[index];
  if (it && it.newStock > 0) it.newStock--;
}
function increase(index: number) {
  const it = auditItems.value[index];
  if (it && it.newStock < 9999) it.newStock++;
}
function setToStandard(index: number) {
  const it = auditItems.value[index];
  if (it) it.newStock = it.standardStock;
}
function setToCurrent(index: number) {
  const it = auditItems.value[index];
  if (it) it.newStock = it.originalStock;
}

// ── 状态标签 ──
function getDiffLabel(item: AuditEntry, index: number) {
  const cur = auditItems.value[index]?.newStock ?? item.originalStock;
  if (cur < item.standardStock) return '偏少';
  if (cur > item.standardStock) return '偏多';
  return '正常';
}
function getDiffClass(item: AuditEntry, index: number) {
  const cur = auditItems.value[index]?.newStock ?? item.originalStock;
  if (cur < item.standardStock) return 'warning';
  if (cur > item.standardStock) return 'danger';
  return 'normal';
}

// ── 提交 ──
async function handleSubmit() {
  if (submitting.value || changedCount.value === 0) return;
  const changes = auditItems.value.filter(i => i.productId != null && i.newStock !== i.originalStock);
  if (!changes.length) { uni.showToast({ title: '无变更', icon: 'none' }); return; }

  submitting.value = true;
  let success = 0;
  let fail = 0;
  for (const item of changes) {
    try {
      await adjustStock({
        deviceId: deviceId.value,
        productId: item.productId!,
        newStock: item.newStock,
        remark: '小程序盘点修正',
      });
      success++;
    } catch {
      fail++;
    }
  }

  if (fail === 0) {
    uni.showToast({ title: `盘点完成，修正${success}项`, icon: 'success' });
    setTimeout(() => uni.navigateBack(), 800);
  } else {
    uni.showToast({ title: `成功${success}项，失败${fail}项`, icon: 'none' });
  }
  submitting.value = false;
}

// ── 初始化：单个 API 调用，后端已合并楼层+库存 ──
onMounted(async () => {
  const pages = getCurrentPages();
  const opts = (pages[pages.length - 1] as any)?.$page?.options || (pages[pages.length - 1] as any)?.options || {};
  deviceId.value = opts.deviceId || '';
  if (!deviceId.value) {
    uni.showToast({ title: '缺少设备ID', icon: 'none' });
    setTimeout(() => uni.navigateBack(), 500);
    return;
  }

  try {
    const data = await getDeviceInventory(deviceId.value);
    deviceName.value = data?.name || '';

    // 后端已在 floors 中合并了模版楼层和库存数据
    const floors: any[] = data?.floors || [];
    const items: AuditEntry[] = [];

    for (const floor of floors) {
      const floorNum = floor.floorNumber || 1;
      const floorName = floor.floorName || ('第' + floorNum + '层');

      for (const slot of (floor.slots || [])) {
        const code = (slot.productCode || '').toString().trim();
        if (!code) continue;

        const curStock = slot.currentStock ?? 0;
        items.push({
          productId: slot.inventoryProductId ?? null,
          productCode: code,
          productName: slot.productName || code,
          productImage: slot.productImage || '',
          standardStock: slot.standardStock ?? 0,
          newStock: curStock,
          originalStock: curStock,
          floorNumber: floorNum,
          floorName,
        });
      }
    }

    auditItems.value = items;
  } catch (e: any) {
    uni.showToast({ title: e.message || '加载失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
});
</script>

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

/* ── 设备信息 ── */
.device-bar { margin: 12rpx 24rpx; padding: 16rpx 20rpx; background: $bg-color-card; border-radius: $radius-md; box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04); }
.device-bar-text { font-size: $font-size-sm; font-weight: 600; color: $text-color-primary; }

/* ── 搜索栏 ── */
.search-bar { display: flex; align-items: center; margin: 0 24rpx 10rpx; padding: 0 16rpx; height: 60rpx; background: $bg-color-card; border: 1rpx solid $border-color; border-radius: $radius-base; }
.search-icon { width: 28rpx; height: 28rpx; border: 2.5rpx solid $text-color-muted; border-radius: 50%; position: relative; flex-shrink: 0; margin-right: 10rpx;
  &::after { content: ''; position: absolute; bottom: -2rpx; right: -4rpx; width: 2.5rpx; height: 10rpx; background: $text-color-muted; border-radius: 1rpx; transform: rotate(-45deg); }
}
.search-input { flex: 1; font-size: $font-size-sm; color: $text-color-primary; height: 100%; }
.search-clear { width: 36rpx; height: 36rpx; display: flex; align-items: center; justify-content: center; border-radius: 50%; background: $bg-color-secondary; flex-shrink: 0; margin-left: 8rpx;
  text { font-size: 20rpx; color: $text-color-muted; line-height: 1; }
}

/* ── 空状态 ── */
.empty-state { display: flex; flex-direction: column; align-items: center; padding: 80rpx 0; }
.empty-icon-box { width: 96rpx; height: 96rpx; background: $bg-color-secondary; border-radius: $radius-lg; display: flex; align-items: center; justify-content: center; margin-bottom: $spacing-2; }
.empty-doc-icon { width: 40rpx; height: 48rpx; border: 2.5rpx solid $text-color-placeholder; border-radius: 4rpx; position: relative;
  &::after { content: ''; position: absolute; top: 14rpx; left: 8rpx; right: 8rpx; height: 2.5rpx; background: $text-color-placeholder; border-radius: 1rpx; box-shadow: 0 8rpx 0 $text-color-placeholder, 0 16rpx 0 $text-color-placeholder; }
}
.empty-text { font-size: $font-size-base; color: $text-color-muted; }

/* ── 楼层列表滚动区 ── */
.floors-scroll { flex: 1; height: 0; overflow-y: auto; padding: 0 24rpx; }

/* ── 楼层卡片 ── */
.floor-card { background: $bg-color-card; border-radius: $radius-md; margin-bottom: 12rpx; overflow: hidden; box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04); }
.floor-header { display: flex; align-items: center; padding: 18rpx 20rpx; border-bottom: 1rpx solid $border-color-light; }
.floor-header-single { border-bottom: none; }
.floor-badge { width: 40rpx; height: 40rpx; line-height: 40rpx; text-align: center; background: $primary-color; color: $text-color-primary; border-radius: $radius-sm; font-size: 22rpx; font-weight: 600; margin-right: 10rpx; }
.floor-title { font-size: $font-size-base; font-weight: 600; color: $text-color-primary; flex: 1; }
.floor-count { font-size: $font-size-sm; color: $text-color-muted; }

/* ── 商品网格（3列） ── */
.goods-grid { display: flex; flex-wrap: wrap; padding: 8rpx; }

/* ── 商品单元格 ── */
.goods-cell { width: 33.33%; padding: 6rpx; box-sizing: border-box; }
.goods-cell-inner { display: flex; flex-direction: column; align-items: center; padding: 12rpx 8rpx; background: $bg-color-page; border-radius: $radius-sm; width: 100%; box-sizing: border-box; }

.cell-image-wrap { width: 120rpx; height: 120rpx; border-radius: $radius-sm; overflow: hidden; background: $bg-color-tertiary; margin-bottom: 8rpx; flex-shrink: 0; }
.cell-image { width: 100%; height: 100%; }
.cell-image-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;
  text { font-size: 20rpx; color: $text-color-muted; }
}

.cell-name { font-size: 22rpx; font-weight: 500; color: $text-color-primary; width: 100%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-bottom: 4rpx; }

.cell-badge { padding: 2rpx 8rpx; border-radius: 6rpx; font-size: 18rpx; font-weight: 500; margin-bottom: 6rpx;
  &.normal { background: $success-color-bg; color: $success-color; }
  &.warning { background: $warning-color-bg; color: $warning-color; }
  &.danger { background: $error-color-bg; color: $error-color; }
}

.cell-stock-row { display: flex; gap: 10rpx; margin-bottom: 6rpx; }
.cell-stock-label { font-size: 20rpx; color: $text-color-muted; }
.cell-stock-cur { font-size: 20rpx; font-weight: 500; color: $text-color-primary; }

/* 数量调节 */
.cell-qty { display: flex; align-items: center; gap: 0; border: 1rpx solid $border-color; border-radius: 8rpx; overflow: hidden; margin-bottom: 8rpx; }
.cell-qty-btn { width: 52rpx; height: 52rpx; display: flex; align-items: center; justify-content: center; background: $bg-color-card;
  text { font-size: 32rpx; color: $text-color-secondary; line-height: 1; }
  &:active { background: $bg-color-secondary; }
}
.cell-qty-input { width: 64rpx; height: 52rpx; text-align: center; font-size: 26rpx; font-weight: 600; color: $text-color-primary; border-left: 1rpx solid $border-color; border-right: 1rpx solid $border-color; }

/* 快捷操作 */
.cell-actions { display: flex; align-items: center; gap: 4rpx; }
.cell-action-btn { font-size: 18rpx; color: $text-color-secondary; padding: 2rpx 4rpx;
  &:active { opacity: 0.7; }
}
.cell-action-reset { color: $error-color; }
.cell-action-divider { font-size: 18rpx; color: $border-color; }

/* 滚动底部占位 */
.scroll-bottom-spacer { height: 20rpx; }

/* ── 底部操作栏 ── */
.bottom-bar { display: flex; align-items: center; gap: 12rpx; padding: 16rpx 24rpx; padding-bottom: calc(16rpx + env(safe-area-inset-bottom)); background: $bg-color-card; border-top: 1rpx solid $border-color-light; flex-shrink: 0; }
.total-label { font-size: $font-size-sm; color: $text-color-muted; flex-shrink: 0; }
.total-num { font-size: $font-size-xl; font-weight: 700; color: $primary-color-dark; margin: 0 4rpx; }
.submit-btn { flex: 1; display: flex; align-items: center; justify-content: center; gap: 12rpx; height: 72rpx; background: $primary-color; border-radius: $radius-base;
  text { font-size: $font-size-md; font-weight: 600; color: $text-color-primary; }
  &:active { opacity: 0.8; }
  &.disabled { opacity: 0.5; pointer-events: none; }
}
.btn-spinner { width: 28rpx; height: 28rpx; border: 3rpx solid rgba(30,41,59,0.2); border-top-color: $text-color-primary; border-radius: 50%; animation: spin 0.7s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>
