<template>
  <view class="page">
    <NavBar title="补货单详情" :showBack="true" />

    <view class="load-tip" v-if="loading">
      <view class="dot-row"><view class="pulse-dot"></view><view class="pulse-dot"></view><view class="pulse-dot"></view></view>
    </view>

    <template v-else-if="order">
      <scroll-view class="detail-scroll" scroll-y>
        <!-- 订单头 -->
        <view class="header-card">
          <view class="head-row">
            <text class="head-title">{{ order.deviceName || order.deviceId }}</text>
            <text class="head-status" :class="statusClass(order.status)">{{ statusLabel(order.status) }}</text>
          </view>
          <view class="head-info">
            <text class="hi-label">门店</text>
            <text class="hi-value">{{ order.shopName || '-' }}</text>
          </view>
          <view class="head-info">
            <text class="hi-label">编号</text>
            <text class="hi-value">{{ order.orderNo || '-' }}</text>
          </view>
          <view class="head-info">
            <text class="hi-label">创建时间</text>
            <text class="hi-value">{{ order.createTime || '-' }}</text>
          </view>
        </view>

        <!-- 待下架商品 -->
        <view class="section">
          <view class="section-head">
            <text class="section-title">待下架商品</text>
            <text class="section-count">{{ pendingRemovalItems.length }} 种</text>
          </view>
          <view class="empty-tip" v-if="pendingRemovalItems.length === 0">
            <text>暂无待下架商品</text>
          </view>
          <view class="product-row" v-for="(item, i) in pendingRemovalItems" :key="'rm-' + i">
            <image v-if="item.productImage" :src="item.productImage" class="product-img" mode="aspectFill" />
            <view v-else class="product-img-placeholder"><text>无图</text></view>
            <view class="product-info">
              <text class="product-name">{{ item.productName || '未知商品' }}</text>
            </view>
            <text class="product-qty">{{ item.plannedQuantity || item.quantity || 0 }}</text>
          </view>
        </view>

        <!-- 待补货商品 -->
        <view class="section">
          <view class="section-head">
            <view class="section-head-left">
              <text class="section-title">待补货商品</text>
              <text class="section-count">{{ displayReplenishItems.length }} 种</text>
            </view>
            <view class="zero-toggle" @click="showZeroQty = !showZeroQty">
              <text class="toggle-label">含零</text>
              <view class="toggle-switch" :class="{ on: showZeroQty }"><view class="toggle-knob"></view></view>
            </view>
          </view>

          <view class="sort-bar">
            <view class="sort-item" :class="{ active: sortField === 'name' }" @click="toggleSort('name')">
              <text>名称</text>
            </view>
            <view class="sort-item" :class="{ active: sortField === 'shelfNum' }" @click="toggleSort('shelfNum')">
              <text>层数</text>
            </view>
            <view class="sort-item" :class="{ active: sortField === 'quantity' }" @click="toggleSort('quantity')">
              <text>数量</text>
            </view>
          </view>

          <view class="product-row" v-for="(item, i) in displayReplenishItems" :key="'rp-' + i">
            <image v-if="item.productImage" :src="item.productImage" class="product-img" mode="aspectFill" />
            <view v-else class="product-img-placeholder"><text>无图</text></view>
            <view class="product-info">
              <text class="product-name">{{ item.productName || '未知商品' }}</text>
              <text class="product-shelf" v-if="item.shelfNum">层 {{ item.shelfNum }} · {{ item.position || '' }}</text>
            </view>
            <text class="product-qty">
              <text>{{ item.plannedQuantity || item.quantity || 0 }}</text>
              <text class="qty-actual" v-if="item.actualQuantity != null"> / {{ item.actualQuantity }}</text>
            </text>
          </view>
        </view>

        <view class="bottom-spacer" v-if="canExecute(order)"></view>
      </scroll-view>

      <!-- 底部操作 -->
      <view class="bottom-bar" v-if="canExecute(order)">
        <view class="action-btn" @click="goReplenish"><text>按补货单执行补货</text></view>
      </view>
    </template>
  </view>
</template>

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

const loading = ref(true);
const order = ref<any>(null);
const items = ref<any[]>([]);
const showZeroQty = ref(false);
const sortField = ref('shelfNum');
const sortAsc = ref(true);

const statusMap: Record<number, string> = { 0: '草稿', 1: '已提交', 2: '已同步', 3: '已完成', 4: '已取消' };

function statusLabel(s: number) { return statusMap[s] || '未知'; }
function statusClass(s: number) {
  const m: Record<number, string> = { 0: 'draft', 1: 'submitted', 2: 'synced', 3: 'done', 4: 'cancelled' };
  return m[s] || '';
}

function canExecute(o: any) { return o.status === 0 || o.status === 1; }

const pendingRemovalItems = computed(() =>
  items.value.filter((item: any) => item.isRemoval || (item.plannedQuantity || item.quantity || 0) <= 0)
);

const replenishItems = computed(() =>
  items.value.filter((item: any) => !item.isRemoval && (item.plannedQuantity || item.quantity || 0) > 0)
);

const displayReplenishItems = computed(() => {
  let list = showZeroQty.value ? [...replenishItems.value] : replenishItems.value.filter((i: any) => (i.plannedQuantity || i.quantity || 0) > 0);
  const dir = sortAsc.value ? 1 : -1;
  list.sort((a: any, b: any) => {
    if (sortField.value === 'name') return dir * (a.productName || '').localeCompare(b.productName || '');
    if (sortField.value === 'shelfNum') return dir * ((a.shelfNum || 0) - (b.shelfNum || 0));
    return dir * ((a.plannedQuantity || a.quantity || 0) - (b.plannedQuantity || b.quantity || 0));
  });
  return list;
});

function toggleSort(field: string) {
  if (sortField.value === field) { sortAsc.value = !sortAsc.value; } else { sortField.value = field; sortAsc.value = true; }
}

function goReplenish() {
  if (!order.value) return;
  const orderData = {
    orderId: order.value.id, orderNo: order.value.orderNo,
    items: items.value.map((item: any) => ({
      productCode: (item.productCode || '').trim(), productName: item.productName,
      plannedQuantity: item.plannedQuantity || item.quantity || 0,
      shelfNum: item.shelfNum, position: item.position
    }))
  };
  uni.setStorageSync('pendingReplenishOrder', JSON.stringify(orderData));
  uni.navigateTo({ url: `/pages/replenish/operation?deviceId=${order.value.deviceId}&orderId=${order.value.id}` });
}

onMounted(async () => {
  try {
    const pages = getCurrentPages();
    const id = (pages[pages.length - 1] as any)?.options?.id;
    if (!id) { uni.showToast({ title: '参数错误', icon: 'none' }); loading.value = false; setTimeout(() => uni.navigateBack(), 800); return; }
    const data = await getReplenisherOrderDetail(id);
    order.value = data?.order; items.value = data?.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; overflow: hidden; }
.detail-scroll { flex: 1; height: 0; overflow: hidden; }

// ====== Loading ======
.load-tip { display: flex; justify-content: center; padding: 200rpx 0; }
.dot-row { display: flex; gap: $spacing-1; }
.pulse-dot { width: 10rpx; height: 10rpx; background: $text-color-placeholder; border-radius: 50%; animation: pulse 1.2s ease-in-out infinite;
  &:nth-child(2) { animation-delay: 0.2s; } &:nth-child(3) { animation-delay: 0.4s; }
}
@keyframes pulse { 0%,80%,100% { transform: scale(0.5); opacity: 0.4; } 40% { transform: scale(1); opacity: 1; } }

// ====== Header card ======
.header-card { margin: 16rpx 24rpx; padding: $spacing-3; background: $bg-color-card; border-radius: $radius-md; box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05); }
.head-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16rpx;
  .head-title { font-size: $font-size-lg; font-weight: 700; color: $text-color-primary; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .head-status { padding: 4rpx 16rpx; border-radius: $radius-sm; font-size: 22rpx; font-weight: 500;
    &.draft { background: $bg-color-secondary; color: $text-color-muted; }
    &.submitted { background: $warning-color-bg; color: $warning-color; }
    &.synced { background: $info-color-bg; color: $info-color; }
    &.done { background: $success-color-bg; color: $success-color; }
    &.cancelled { background: $error-color-bg; color: $error-color; }
  }
}
.head-info { padding: 6rpx 0; display: flex;
  .hi-label { font-size: $font-size-sm; color: $text-color-muted; margin-right: $spacing-1; flex-shrink: 0; }
  .hi-value { font-size: $font-size-sm; color: $text-color-primary; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
}

// ====== Section ======
.section { padding: 0 24rpx; margin-top: 16rpx; width: 100%; box-sizing: border-box; overflow: hidden; }
.section-head { display: flex; align-items: center; justify-content: space-between; padding: 16rpx 0;
  .section-title { font-size: $font-size-base; font-weight: 700; color: $text-color-primary; }
  .section-count { font-size: $font-size-sm; color: $text-color-muted; }
}
.section-head-left { display: flex; align-items: baseline; gap: 8rpx; }
.empty-tip { text-align: center; padding: 40rpx 0; text { font-size: 26rpx; color: $text-color-muted; } }

// ====== Toggle ======
.zero-toggle { display: flex; align-items: center; gap: 8rpx;
  .toggle-label { font-size: 20rpx; color: $text-color-muted; }
}
.toggle-switch { width: 56rpx; height: 32rpx; border-radius: 16rpx; background: $border-color; position: relative; transition: background 0.2s;
  .toggle-knob { width: 26rpx; height: 26rpx; border-radius: 50%; background: $bg-color-card; position: absolute; top: 3rpx; left: 3rpx; transition: left 0.2s; box-shadow: 0 1rpx 4rpx rgba(0,0,0,0.1); }
  &.on { background: $primary-color; .toggle-knob { left: 27rpx; } }
}

// ====== Sort bar ======
.sort-bar { display: flex; background: $bg-color-card; border-radius: $radius-sm; border: 1rpx solid $border-color; overflow: hidden; margin-bottom: 8rpx; }
.sort-item { flex: 1; padding: 12rpx 0; text-align: center; font-size: 22rpx; color: $text-color-muted; border-right: 1rpx solid $border-color-light;
  &:last-child { border-right: none; }
  &.active { color: $primary-color-dark; font-weight: 600; background: $primary-color-bg; }
  &:active { opacity: 0.7; }
}

// ====== Product row ======
.product-row { display: flex; align-items: center; padding: 16rpx 0; border-bottom: 1rpx solid $border-color-light; width: 100%; box-sizing: border-box;
  &:last-child { border-bottom: none; }
}
.product-img { width: 72rpx; height: 72rpx; border-radius: $radius-sm; background: $bg-color-page; margin-right: 16rpx; flex-shrink: 0; }
.product-img-placeholder { width: 72rpx; height: 72rpx; border-radius: $radius-sm; background: $bg-color-page; margin-right: 16rpx; flex-shrink: 0; display: flex; align-items: center; justify-content: center;
  text { font-size: 20rpx; color: $text-color-muted; }
}
.product-info { flex: 1; min-width: 0; overflow: hidden;
  .product-name { display: block; font-size: 26rpx; color: $text-color-primary; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; }
  .product-shelf { font-size: 20rpx; color: $text-color-muted; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
}
.product-qty { font-size: 30rpx; font-weight: 700; color: $text-color-primary; margin-left: 16rpx; flex-shrink: 0; min-width: 40rpx; text-align: right; }
.qty-actual { font-size: 24rpx; font-weight: 500; color: $text-color-muted; }

// ====== Bottom ======
.bottom-spacer { height: 120rpx; }
.bottom-bar { position: fixed; bottom: 0; left: 0; right: 0; padding: $spacing-3 $spacing-4; padding-bottom: calc($spacing-3 + env(safe-area-inset-bottom)); background: $bg-color-card; border-top: 1rpx solid $border-color-light; }
.action-btn { display: flex; align-items: center; justify-content: center; width: 100%; padding: 26rpx 0; border-radius: $radius-xl; background: $primary-color;
  text { font-size: $font-size-md; font-weight: 600; color: $text-color-primary; }
  &:active { opacity: 0.8; }
}
</style>
