<template>
  <view class="page">
    <view class="yellow-header">
      <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
      <view class="header-content">
        <image class="header-logout" src="/static/icon-logout.svg" @click="handleLogout" />
        <text class="header-title">补货管理</text>
      </view>
    </view>
    <view class="header-placeholder" :style="{ height: (statusBarHeight + 44) + 'px' }"></view>

    <!-- 加载 -->
    <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>

    <!-- 设备列表 -->
    <scroll-view class="device-scroll" scroll-y v-else>
      <view class="empty-state" v-if="deviceList.length === 0">
        <view class="empty-icon-box"><view class="empty-device-icon"></view></view>
        <text class="empty-text">暂无绑定的设备</text>
        <text class="empty-hint">请联系管理员绑定设备后开始补货</text>
      </view>

      <view class="device-card" v-for="(device, index) in deviceList" :key="device.deviceId || index" @click="goToOperation(device)">
        <view class="card-left">
          <view class="card-icon"></view>
        </view>
        <view class="card-main">
          <text class="card-name">{{ device.deviceId }} - {{ device.name || '' }}</text>
          <view class="card-stats">
            <view class="cs-item">
              <text class="cs-label">标准</text>
              <text class="cs-value">{{ device.standardStock || 0 }}</text>
            </view>
            <view class="cs-item">
              <text class="cs-label">剩余</text>
              <text class="cs-value" :class="{ warn: device.remainingStock < device.standardStock }">{{ device.remainingStock || 0 }}</text>
            </view>
            <view class="cs-item" v-if="device.pendingOrderCount > 0">
              <text class="cs-label">待补</text>
              <text class="cs-value accent">{{ device.pendingOrderCount }}</text>
            </view>
          </view>
        </view>
        <view class="card-badge" :class="device.remainingStock < device.standardStock ? 'warn' : 'normal'">
          <text>{{ device.remainingStock < device.standardStock ? '待补货' : '正常' }}</text>
        </view>
        <view class="card-audit" @click.stop="goToAudit(device)"><text>盘点</text></view>
      </view>
    </scroll-view>

    <!-- 扫码浮钮 -->
    <view class="scan-fab" @click="handleScan">
      <view class="scan-icon"></view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { getDeviceList } from '@/api/replenish';
import { clearAuth } from '@/utils/auth';

const statusBarHeight = ref(0);
const deviceList = ref<any[]>([]);
const loading = ref(true);

const loadData = async () => {
  loading.value = true;
  try {
    const devices = await getDeviceList();
    deviceList.value = devices || [];
  } catch { /* ignore */ }
  finally { loading.value = false; }
};

const goToOperation = (device: any) => {
  uni.navigateTo({ url: `/pages/replenish/operation?deviceId=${device.deviceId}` });
};

const goToAudit = (device: any) => {
  uni.navigateTo({ url: `/pages/replenish/audit?deviceId=${device.deviceId}` });
};

const handleScan = () => {
  uni.scanCode({
    onlyFromCamera: true,
    scanType: ['qrCode', 'barCode'],
    success: (res: any) => {
      // 与 haha-mp 一致的 deviceId 提取逻辑
      let deviceId = '';
      try {
        const urlPattern = /\/([A-Z0-9]+)(\?|$)/;
        const match = res.result.match(urlPattern);
        if (match && match[1]) {
          deviceId = match[1];
        } else {
          try {
            const qrData = JSON.parse(res.result);
            if (qrData.deviceId) deviceId = qrData.deviceId;
          } catch (e) {
            deviceId = res.result;
          }
        }
        if (!deviceId) throw new Error('无法解析设备ID');
      } catch (error) {
        uni.showToast({ title: '二维码格式错误', icon: 'none' });
        return;
      }

      uni.showActionSheet({
        itemList: ['设备补货', '库存盘点'],
        success: (sheetRes) => {
          if (sheetRes.tapIndex === 0) {
            uni.navigateTo({ url: `/pages/replenish/operation?deviceId=${deviceId}` });
          } else if (sheetRes.tapIndex === 1) {
            uni.navigateTo({ url: `/pages/replenish/audit?deviceId=${deviceId}` });
          }
        }
      });
    },
    fail: () => { /* 用户取消扫码 */ }
  });
};

const handleLogout = () => {
  uni.showModal({
    title: '退出登录',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) { clearAuth(); uni.reLaunch({ url: '/pages/login/login' }); }
    }
  });
};

onMounted(() => {
  const info = uni.getSystemInfoSync();
  statusBarHeight.value = info.statusBarHeight || 20;
});

onShow(async () => { await loadData(); });
</script>

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

// ====== Header ======
.yellow-header { position: fixed; top: 0; left: 0; right: 0; z-index: 999; background: $primary-color; padding-top: constant(safe-area-inset-top); padding-top: env(safe-area-inset-top); }
.header-content { display: flex; align-items: center; justify-content: center; height: 44px; padding: 0 16rpx; position: relative; }
.header-title { font-size: $font-size-xl; font-weight: 700; color: $text-color-primary; }
.header-logout { position: absolute; left: 24rpx; width: 40rpx; height: 40rpx; &:active { opacity: 0.7; } }
.header-placeholder { width: 100%; }

// ====== 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; } }

// ====== Device ======
.device-scroll { flex: 1; height: 0; }
.empty-state { display: flex; flex-direction: column; align-items: center; padding: 160rpx 0;
  .empty-icon-box { width: 120rpx; height: 120rpx; background: $bg-color-secondary; border-radius: $radius-xl; display: flex; align-items: center; justify-content: center; margin-bottom: $spacing-3; }
  .empty-device-icon { width: 44rpx; height: 36rpx; border: 3rpx solid $text-color-placeholder; border-radius: 6rpx; position: relative;
    &::after { content: ''; position: absolute; bottom: -8rpx; left: 50%; transform: translateX(-50%); width: 22rpx; height: 6rpx; background: $text-color-placeholder; border-radius: 0 0 4rpx 4rpx; }
  }
  .empty-text { font-size: $font-size-base; color: $text-color-secondary; margin-bottom: $spacing-1; }
  .empty-hint { font-size: $font-size-sm; color: $text-color-muted; }
}

.device-card { display: flex; align-items: center; gap: 16rpx; margin: 16rpx 24rpx; padding: 24rpx; background: $bg-color-card; border-radius: $radius-md; box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  &:active { opacity: 0.7; }
}
.card-left { flex-shrink: 0; }
.card-icon { width: 56rpx; height: 56rpx; background: $success-color-bg; border-radius: $radius-base; position: relative;
  &::before { content: ''; position: absolute; top: 10rpx; left: 50%; transform: translateX(-50%); width: 24rpx; height: 18rpx; border: 2.5rpx solid $success-color; border-radius: 4rpx; }
  &::after { content: ''; position: absolute; bottom: 6rpx; left: 50%; transform: translateX(-50%); width: 14rpx; height: 5rpx; background: $success-color; border-radius: 0 0 3rpx 3rpx; }
}
.card-main { flex: 1; min-width: 0; }
.card-name { display: block; font-size: $font-size-base; font-weight: 600; color: $text-color-primary; margin-bottom: 10rpx; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.card-stats { display: flex; gap: 24rpx; }
.cs-item { display: flex; align-items: baseline; gap: 6rpx; }
.cs-label { font-size: 22rpx; color: $text-color-muted; }
.cs-value { font-size: $font-size-base; font-weight: 700; color: $text-color-primary;
  &.warn { color: $warning-color; }
  &.accent { color: $accent-color; }
}
.card-badge { padding: 8rpx 16rpx; border-radius: $radius-sm; font-size: 22rpx; font-weight: 500; flex-shrink: 0;
  &.normal { background: $success-color-bg; color: $success-color; }
  &.warn { background: $warning-color-bg; color: $warning-color; }
}
.card-audit { margin-left: 12rpx; padding: 8rpx 16rpx; border-radius: $radius-sm; background: $info-color-bg; font-size: 22rpx; color: $info-color; font-weight: 500; flex-shrink: 0;
  &:active { opacity: 0.7; }
}

.scan-fab { position: fixed; left: 50%; bottom: calc(120rpx + env(safe-area-inset-bottom)); transform: translateX(-50%); width: 128rpx; height: 128rpx; border-radius: 50%; background: $primary-color; box-shadow: 0 12rpx 36rpx rgba(255,193,7,0.4); display: flex; align-items: center; justify-content: center; z-index: 100;
  &:active { transform: translateX(-50%) scale(0.92); background: $primary-color-dark; }
}
.scan-icon { width: 56rpx; height: 56rpx; position: relative;
  &::before { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; border: 5rpx solid $text-color-primary; border-radius: 10rpx; }
  &::after { content: ''; position: absolute; top: 50%; left: 8rpx; right: 8rpx; height: 3rpx; background: $text-color-primary; border-radius: 2rpx; transform: translateY(-50%); }
}
</style>
