<template>
  <view class="page">
    <NavBar title="补货操作" showBack />

    <view class="loading-container" v-if="loading">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载设备信息...</text>
    </view>

    <template v-else>
      <!-- 设备信息 -->
      <view class="device-section">
        <view class="device-card">
          <view class="device-header">
            <view class="device-icon"></view>
            <view class="device-info">
              <text class="device-name">{{ deviceInfo.name || deviceInfo.deviceId }}</text>
              <text class="device-id" v-if="deviceInfo.address">{{ deviceInfo.address }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 商品库存清单 -->
      <view class="inventory-section">
        <view class="section-header">
          <text class="section-title">商品库存清单</text>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="inventoryList.length === 0">
          <text class="empty-text">暂无商品库存数据</text>
        </view>

        <!-- 商品列表 -->
        <view
          class="inventory-card"
          v-for="(item, index) in inventoryList"
          :key="index"
        >
          <view class="item-header">
            <text class="item-name">{{ item.product_name || item.productName || '未知商品' }}</text>
            <text class="item-code" v-if="item.product_code || item.productCode">
              {{ item.product_code || item.productCode }}
            </text>
            <view :class="['stock-status', getStockStatus(item)]">
              {{ getStockStatusText(item) }}
            </view>
          </view>

          <view class="item-stock">
            <view class="stock-row">
              <text class="stock-label">当前库存</text>
              <text :class="['stock-value', { 'low-stock': isLowStock(item), 'out-of-stock': isOutOfStock(item) }]">
                {{ item.stock || 0 }}
              </text>
            </view>
            <view class="stock-row">
              <text class="stock-label">预警阈值</text>
              <text class="stock-value muted">{{ item.warning_threshold || item.warningThreshold || 5 }}</text>
            </view>
          </view>

          <!-- 补货输入 -->
          <view class="replenish-input-section">
            <text class="input-label">补货数量</text>
            <view class="quantity-control">
              <view class="qty-btn" @click="decrease(item, index)">-</view>
              <input
                class="qty-input"
                type="number"
                v-model="replenishItems[index].quantity"
                @blur="validateQuantity(index)"
              />
              <view class="qty-btn" @click="increase(item, index)">+</view>
            </view>
            <view class="suggest-btn" @click="suggestQuantity(item, index)">
              一键补满
            </view>
          </view>
        </view>
      </view>

      <!-- 底部提交 -->
      <view class="bottom-actions" v-if="inventoryList.length > 0">
        <view class="total-info">
          <text class="total-label">共补货</text>
          <text class="total-value">{{ totalReplenishCount }}</text>
          <text class="total-label">件商品</text>
        </view>
        <button class="submit-btn" :loading="submitting" :disabled="submitting || totalReplenishCount === 0" @click="handleSubmit">
          <text v-if="!submitting">确认补货</text>
          <text v-else>提交中...</text>
        </button>
      </view>
    </template>
  </view>
</template>

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

interface InventoryItem {
  product_id?: number;
  productId?: number;
  product_code?: string;
  productCode?: string;
  product_name?: string;
  productName?: string;
  stock?: number;
  warning_threshold?: number;
  warningThreshold?: number;
  shelf_num?: number;
  shelfNum?: number;
  position?: string;
}

interface ReplenishInput {
  productId: number;
  productCode?: string;
  productName?: string;
  quantity: number;
  shelfNum?: number;
  position?: string;
}

const deviceId = ref('');
const deviceInfo = ref<any>({});
const inventoryList = ref<InventoryItem[]>([]);
const replenishItems = ref<ReplenishInput[]>([]);
const loading = ref(true);
const submitting = ref(false);

const totalReplenishCount = computed(() => {
  return replenishItems.value.reduce((sum, item) => sum + (item.quantity || 0), 0);
});

const isLowStock = (item: any): boolean => {
  const stock = item.stock || 0;
  const threshold = item.warning_threshold || item.warningThreshold || 5;
  return stock > 0 && stock <= threshold;
};

const isOutOfStock = (item: any): boolean => {
  return (item.stock || 0) === 0;
};

const getStockStatus = (item: any): string => {
  if (isOutOfStock(item)) return 'danger';
  if (isLowStock(item)) return 'warning';
  return 'normal';
};

const getStockStatusText = (item: any): string => {
  if ((item.stock || 0) === 0) return '缺货';
  const threshold = item.warning_threshold || item.warningThreshold || 5;
  if ((item.stock || 0) <= threshold) return '低库存';
  return '正常';
};

const decrease = (item: any, index: number) => {
  if (replenishItems.value[index].quantity > 0) {
    replenishItems.value[index].quantity--;
  }
};

const increase = (item: any, index: number) => {
  replenishItems.value[index].quantity++;
};

const suggestQuantity = (item: any, index: number) => {
  const threshold = item.warning_threshold || item.warningThreshold || 5;
  const currentStock = item.stock || 0;
  // 建议补满到预警阈值的3倍（即建议库存水平）
  const suggestLevel = threshold * 3;
  const suggest = Math.max(suggestLevel - currentStock, 0);
  replenishItems.value[index].quantity = suggest || 1;
};

const validateQuantity = (index: number) => {
  if (replenishItems.value[index].quantity < 0) {
    replenishItems.value[index].quantity = 0;
  }
};

const handleSubmit = async () => {
  if (totalReplenishCount.value === 0) {
    uni.showToast({ title: '请至少补货一件商品', icon: 'none' });
    return;
  }

  // 过滤掉数量为0的项
  const items = replenishItems.value
    .filter(item => item.quantity > 0)
    .map(item => ({
      productId: item.productId,
      productCode: item.productCode,
      productName: item.productName,
      quantity: item.quantity,
      shelfNum: item.shelfNum,
      position: item.position
    }));

  if (items.length === 0) {
    uni.showToast({ title: '请至少补货一件商品', icon: 'none' });
    return;
  }

  submitting.value = true;
  try {
    const result = await replenishStock({
      deviceId: deviceId.value,
      items
    });

    uni.showToast({ title: `补货完成，成功${result.success}项`, icon: 'success' });
    setTimeout(() => {
      uni.navigateBack();
    }, 800);
  } catch (error: any) {
    uni.showToast({ title: error.message || '补货失败', icon: 'none' });
  } finally {
    submitting.value = false;
  }
};

onMounted(async () => {
  // 获取参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = (currentPage as any).$page?.options || (currentPage as any).options || {};
  deviceId.value = options.deviceId || '';

  if (!deviceId.value) {
    uni.showToast({ title: '缺少设备ID', icon: 'none' });
    setTimeout(() => uni.navigateBack(), 500);
    return;
  }

  try {
    const data = await getDeviceInventory(deviceId.value);
    deviceInfo.value = data;

    const list = data.inventoryList || [];
    inventoryList.value = list;

    // 初始化补货输入
    replenishItems.value = list.map((item: any) => ({
      productId: item.product_id || item.productId || 0,
      productCode: item.product_code || item.productCode || '',
      productName: item.product_name || item.productName || '',
      quantity: 0,
      shelfNum: item.shelf_num || item.shelfNum || null,
      position: item.position || null
    }));
  } catch (error: any) {
    uni.showToast({ title: error.message || '加载失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
});
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: $bg-color-page;
  padding-bottom: 200rpx;
}

/* 加载 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;

  .loading-text {
    margin-top: 16rpx;
    font-size: 26rpx;
    color: $text-color-muted;
  }
}

/* 设备信息 */
.device-section {
  padding: 16rpx 24rpx 0;

  .device-card {
    background: $bg-color-card;
    border: 1rpx solid $border-color;
    border-radius: 16rpx;
    padding: 24rpx;

    .device-header {
      display: flex;
      align-items: center;

      .device-icon {
        width: 48rpx;
        height: 48rpx;
        background: $success-color-bg;
        border-radius: 12rpx;
        margin-right: 16rpx;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          top: 8rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 20rpx;
          height: 16rpx;
          border: 3rpx solid $primary-color;
          border-radius: 4rpx;
        }

        &::after {
          content: '';
          position: absolute;
          bottom: 4rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 12rpx;
          height: 6rpx;
          background: $primary-color;
          border-radius: 0 0 4rpx 4rpx;
        }
      }

      .device-info {
        flex: 1;

        .device-name {
          display: block;
          font-size: 30rpx;
          font-weight: 600;
          color: $text-color-primary;
        }

        .device-id {
          font-size: 24rpx;
          color: $text-color-tertiary;
        }
      }
    }
  }
}

/* 库存区域 */
.inventory-section {
  padding: 0 24rpx;
}

.section-header {
  padding: 24rpx 0 16rpx;

  .section-title {
    font-size: 30rpx;
    font-weight: 700;
    color: $text-color-primary;
  }
}

.empty-state {
  text-align: center;
  padding: 60rpx 0;

  .empty-text {
    font-size: 26rpx;
    color: $text-color-muted;
  }
}

/* 商品卡片 */
.inventory-card {
  background: $bg-color-card;
  border: 1rpx solid $border-color;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 16rpx;

  .item-header {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;

    .item-name {
      font-size: 28rpx;
      font-weight: 600;
      color: $text-color-primary;
      flex: 1;
    }

    .item-code {
      font-size: 20rpx;
      color: $text-color-muted;
      margin-right: 12rpx;
    }

    .stock-status {
      padding: 4rpx 12rpx;
      border-radius: 6rpx;
      font-size: 20rpx;
      font-weight: 500;

      &.normal {
        background: $success-color-bg;
        color: $primary-color;
      }

      &.warning {
        background: $warning-color-bg;
        color: $warning-color;
      }

      &.danger {
        background: $error-color-bg;
        color: $error-color;
      }
    }
  }

  .item-stock {
    display: flex;
    gap: 24rpx;
    margin-bottom: 16rpx;

    .stock-row {
      flex: 1;
      display: flex;
      align-items: center;

      .stock-label {
        font-size: 24rpx;
        color: $text-color-muted;
        margin-right: 8rpx;
      }

      .stock-value {
        font-size: 28rpx;
        font-weight: 700;
        color: $text-color-primary;

        &.muted {
          color: $text-color-muted;
        }

        &.low-stock {
          color: $warning-color;
        }

        &.out-of-stock {
          color: $error-color;
        }
      }
    }
  }

  .replenish-input-section {
    display: flex;
    align-items: center;
    background: $bg-color-page;
    border-radius: 12rpx;
    padding: 16rpx;

    .input-label {
      font-size: 24rpx;
      color: $text-color-tertiary;
      margin-right: 16rpx;
    }

    .quantity-control {
      display: flex;
      align-items: center;
      border: 1rpx solid $border-color;
      border-radius: 8rpx;
      overflow: hidden;

      .qty-btn {
        width: 56rpx;
        height: 56rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        font-weight: 500;
        color: $text-color-tertiary;
        background: $bg-color-card;

        &:active {
          background: $bg-color-secondary;
        }
      }

      .qty-input {
        width: 80rpx;
        height: 56rpx;
        text-align: center;
        font-size: 28rpx;
        font-weight: 600;
        color: $text-color-primary;
        border-left: 1rpx solid $border-color;
        border-right: 1rpx solid $border-color;
      }
    }

    .suggest-btn {
      margin-left: auto;
      padding: 10rpx 20rpx;
      background: $success-color-bg;
      border-radius: 8rpx;
      font-size: 22rpx;
      color: $primary-color;
      font-weight: 500;

      &:active {
        background: $success-color-bg;
      }
    }
  }
}

/* 底部操作 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: $bg-color-card;
  border-top: 1rpx solid $border-color;
  padding: 20rpx 24rpx;
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  display: flex;
  align-items: center;
  gap: 20rpx;

  .total-info {
    display: flex;
    align-items: center;

    .total-label {
      font-size: 24rpx;
      color: $text-color-tertiary;
    }

    .total-value {
      font-size: 36rpx;
      font-weight: 700;
      color: $primary-color;
      margin: 0 8rpx;
    }
  }

  .submit-btn {
    flex: 1;
    height: 88rpx;
    line-height: 88rpx;
    padding: 0;
    background: $primary-color;
    color: #fff;
    font-size: 30rpx;
    font-weight: 600;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    &::after {
      border: none;
    }

    &:active {
      background: $primary-color-dark;
    }

    &[disabled] {
      opacity: 0.6;
    }
  }
}
</style>
