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

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

      <!-- 商品清单 -->
      <view class="inventory-section">
        <view class="section-head">
          <text class="section-title">盘点清单</text>
          <text class="section-count">{{ searchKeyword ? filteredInventoryList.length + ' / ' + inventoryList.length : inventoryList.length }} 种</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="inventoryList.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="inventoryList.length > 0 && filteredInventoryList.length === 0">
          <text class="empty-text">未找到匹配商品</text>
        </view>

        <view class="inventory-card" v-for="({ item, idx }, i) in filteredInventoryList" :key="idx">
          <view class="item-row">
            <image v-if="item.product_image" :src="item.product_image" class="item-img" mode="aspectFill" />
            <view v-else class="item-img-placeholder"><text>无图</text></view>
            <view class="item-info">
              <view class="item-name-row">
                <text class="item-name">{{ item.product_name || item.productName || '未知商品' }}</text>
                <view class="stock-badge" :class="getDiffClass(item, idx)">{{ getDiffLabel(item, idx) }}</view>
              </view>
              <view class="item-meta">
                <text class="item-code" v-if="item.product_code || item.productCode">{{ item.product_code || item.productCode }}</text>
                <text class="item-std">标准 {{ item.standard_stock || item.standardStock || '-' }}</text>
                <text class="item-cur">当前 {{ item.stock || 0 }}</text>
              </view>
            </view>
          </view>
          <view class="audit-row">
            <view class="qty-control">
              <view class="qty-btn" @click="decrease(idx)"><text>-</text></view>
              <input class="qty-input" type="number" v-model.number="auditItems[idx].newStock" />
              <view class="qty-btn" @click="increase(idx)"><text>+</text></view>
            </view>
            <view class="quick-btn" @click="setToStandard(item, idx)"><text>设标</text></view>
            <view class="quick-btn quick-reset" @click="setToCurrentStock(item, idx)"><text>重置</text></view>
          </view>
        </view>
      </view>

      <!-- 底部操作栏 -->
      <view class="bottom-bar" v-if="inventoryList.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>
    </template>
  </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 AuditInput {
  productId: number | null;
  productCode: string;
  productName: string;
  newStock: number;
  originalStock: number;
}

const deviceId = ref('');
const deviceName = ref('');
const inventoryList = ref<any[]>([]);
const auditItems = ref<AuditInput[]>([]);
const submitting = ref(false);
const searchKeyword = ref('');

const filteredInventoryList = computed(() => {
  const kw = searchKeyword.value.trim().toLowerCase();
  return inventoryList.value
    .map((item, idx) => ({ item, idx }))
    .filter(({ item }) => {
      if (!kw) return true;
      const name = (item.product_name || item.productName || '').toLowerCase();
      const code = (item.product_code || item.productCode || '').toLowerCase();
      return name.includes(kw) || code.includes(kw);
    });
});

const changedCount = computed(() =>
  auditItems.value.filter(i => i.productId != null && i.newStock !== i.originalStock).length
);

function decrease(index: number) {
  if (auditItems.value[index].newStock > 0) auditItems.value[index].newStock--;
}
function increase(index: number) {
  if (auditItems.value[index].newStock < 9999) auditItems.value[index].newStock++;
}
function setToCurrentStock(item: any, index: number) {
  auditItems.value[index].newStock = item.stock || 0;
}
function setToStandard(item: any, index: number) {
  const std = item.standard_stock || item.standardStock || 0;
  auditItems.value[index].newStock = std;
}
function getDiffLabel(item: any, index: number) {
  if (!auditItems.value[index]) return '正常';
  const cur = auditItems.value[index].newStock;
  const std = item.standard_stock || item.standardStock || 0;
  if (cur < std) return '偏少';
  if (cur > std) return '偏多';
  return '正常';
}
function getDiffClass(item: any, index: number) {
  if (!auditItems.value[index]) return 'normal';
  const cur = auditItems.value[index].newStock;
  const std = item.standard_stock || item.standardStock || 0;
  if (cur < std) return 'warning';
  if (cur > std) 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;
}

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 || '';
    const list = (data?.inventoryList || data || []) as any[];
    // 兼容两种返回格式
    if (Array.isArray(data)) {
      inventoryList.value = data;
    } else if (data?.inventoryList) {
      inventoryList.value = data.inventoryList;
      deviceName.value = data.name || '';
    } else {
      inventoryList.value = [];
    }

    auditItems.value = inventoryList.value.map((it: any) => ({
      productId: it.product_id || it.productId || null,
      productCode: it.product_code || it.productCode || '',
      productName: it.product_name || it.productName || '',
      newStock: it.stock || 0,
      originalStock: it.stock || 0
    }));
  } catch (e: any) {
    uni.showToast({ title: e.message || '加载失败', icon: 'none' });
  }
});
</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; }

.inventory-section { padding: 0 24rpx; flex: 1; height: 0; overflow-y: auto; }
.section-head { display: flex; align-items: center; justify-content: space-between; padding: 16rpx 0 12rpx; }
.section-title { font-size: $font-size-md; font-weight: 700; color: $text-color-primary; }
.section-count { font-size: $font-size-sm; color: $text-color-muted; }
.search-bar { display: flex; align-items: center; background: $bg-color-card; border: 1rpx solid $border-color; border-radius: $radius-base; padding: 0 16rpx; height: 60rpx; margin-bottom: 12rpx; }
.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; }

.inventory-card { margin-bottom: 10rpx; padding: 16rpx; background: $bg-color-card; border-radius: $radius-md; box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04); }

.item-row { display: flex; align-items: center; margin-bottom: 10rpx; }
.item-img { width: 56rpx; height: 56rpx; border-radius: $radius-sm; background: $bg-color-page; flex-shrink: 0; margin-right: 12rpx; }
.item-img-placeholder { width: 56rpx; height: 56rpx; border-radius: $radius-sm; background: $bg-color-page; flex-shrink: 0; margin-right: 12rpx; display: flex; align-items: center; justify-content: center;
  text { font-size: 18rpx; color: $text-color-muted; }
}
.item-info { flex: 1; min-width: 0; overflow: hidden; }
.item-name-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 4rpx; }
.item-name { font-size: $font-size-base; font-weight: 600; color: $text-color-primary; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; }
.item-meta { display: flex; gap: 16rpx; }
.item-code { font-size: 20rpx; color: $text-color-muted; }
.item-std { font-size: 20rpx; color: $text-color-muted; }
.item-cur { font-size: 20rpx; font-weight: 500; color: $text-color-primary; }

.stock-badge { padding: 2rpx 10rpx; border-radius: $radius-sm; font-size: 20rpx; font-weight: 500; flex-shrink: 0; margin-left: 8rpx;
  &.normal { background: $success-color-bg; color: $success-color; }
  &.warning { background: $warning-color-bg; color: $warning-color; }
  &.danger { background: $error-color-bg; color: $error-color; }
}

.audit-row { display: flex; align-items: center; gap: 10rpx; background: $bg-color-page; border-radius: $radius-base; padding: 8rpx 12rpx; }
.qty-control { display: flex; align-items: center; border: 1rpx solid $border-color; border-radius: $radius-sm; overflow: hidden; }
.qty-btn { width: 44rpx; height: 44rpx; display: flex; align-items: center; justify-content: center; background: $bg-color-card;
  text { font-size: 26rpx; color: $text-color-secondary; line-height: 1; }
  &:active { background: $bg-color-secondary; }
}
.qty-input { width: 64rpx; height: 44rpx; text-align: center; font-size: $font-size-base; font-weight: 600; color: $text-color-primary; border-left: 1rpx solid $border-color; border-right: 1rpx solid $border-color; }
.quick-btn { padding: 8rpx 16rpx; background: $bg-color-secondary; border-radius: $radius-sm;
  text { font-size: 22rpx; color: $text-color-secondary; }
  &:active { opacity: 0.7; }
  &.quick-reset { background: $error-color-bg; text { color: $error-color; } }
}

.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; }
.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>
