<template>
  <view class="page">
    <NavBar title="补货首页" />

    <!-- 补货员信息卡片 -->
    <view class="user-section">
      <view class="user-card" @click="navigateToMy">
        <view class="user-header">
          <view class="avatar">
            <text class="avatar-text">{{ replenisherInfo.name?.charAt(0) || '补' }}</text>
          </view>
          <view class="user-info">
            <text class="user-name">{{ replenisherInfo.name || '未知' }}</text>
            <text class="user-role">补货员</text>
            <text class="user-employee" v-if="replenisherInfo.employeeId">工号: {{ replenisherInfo.employeeId }}</text>
          </view>
        </view>
        <view class="user-stats">
          <view class="stat-item">
            <text class="stat-value">{{ deviceList.length }}</text>
            <text class="stat-label">绑定设备</text>
          </view>
          <view class="stat-divider"></view>
          <view class="stat-item">
            <text class="stat-value">{{ totalTaskCount }}</text>
            <text class="stat-label">累计任务</text>
          </view>
          <view class="stat-divider"></view>
          <view class="stat-item">
            <text class="stat-value">{{ lowStockTotal }}</text>
            <text class="stat-label">待补货</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 快捷入口 -->
    <view class="quick-actions">
      <view class="action-btn" @click="goToOrders">
        <text class="action-icon">📋</text>
        <text class="action-label">补货单</text>
      </view>
    </view>

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

    <!-- 设备列表 -->
    <view class="device-section" v-else>
      <view class="section-header">
        <text class="section-title">我的设备</text>
        <view class="section-actions">
          <view class="scan-btn" @click="handleScanDevice">
            <text class="scan-icon">📷</text>
            <text class="scan-text">扫码开柜</text>
          </view>
          <text class="section-count" v-if="deviceList.length">共 {{ deviceList.length }} 台</text>
        </view>
      </view>

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

      <!-- 设备卡片 -->
      <view
        class="device-card"
        v-for="(device, index) in deviceList"
        :key="index"
        @click="goToOperation(device)"
      >
        <view class="device-header">
          <view class="device-info">
            <text class="device-name">{{ device.name || device.deviceId }}</text>
            <text class="device-id">SN: {{ device.deviceId }}</text>
          </view>
          <view :class="['device-status', device.status === 1 ? 'online' : 'offline']">
            {{ device.statusLabel }}
          </view>
        </view>

        <view class="device-address" v-if="device.address">
          <text class="address-text">{{ device.address }}</text>
        </view>

        <!-- 库存概览 -->
        <view class="stock-overview">
          <view class="stock-item">
            <text class="stock-label">商品种类</text>
            <text class="stock-value">{{ device.productCount || 0 }}</text>
          </view>
          <view class="stock-item">
            <text class="stock-label">总库存</text>
            <text class="stock-value">{{ device.totalStock || 0 }}</text>
          </view>
          <view class="stock-item warn" v-if="device.lowStockCount > 0">
            <text class="stock-label">低库存</text>
            <text class="stock-value">{{ device.lowStockCount }}</text>
          </view>
          <view class="stock-item danger" v-if="device.zeroStockCount > 0">
            <text class="stock-label">缺货</text>
            <text class="stock-value">{{ device.zeroStockCount }}</text>
          </view>
        </view>

        <!-- 库存条形 -->
        <view class="stock-bar">
          <view class="bar-bg">
            <view
              class="bar-fill"
              :style="{ width: getStockRatio(device) + '%' }"
            ></view>
          </view>
          <text class="bar-text">{{ getStockRatio(device) }}%</text>
        </view>

        <view class="device-action">
          <text class="action-text">查看商品库存 ></text>
        </view>
      </view>
    </view>

    <CustomTabBar />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import NavBar from '@/components/NavBar.vue';
import CustomTabBar from '@/components/CustomTabBar.vue';
import { getReplenisherInfo, getHomePath } from '@/utils/auth';
import { getMyInfo, getDeviceList } from '@/api/replenish';

const replenisherInfo = ref<any>({});
const deviceList = ref<any[]>([]);
const loading = ref(true);
const totalTaskCount = ref(0);
const lowStockTotal = ref(0);

const navigateToMy = () => {
  uni.switchTab({ url: '/pages/my/my' });
};

const goToOrders = () => {
  uni.navigateTo({ url: '/pages/replenish/orders' });
};

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

const getStockRatio = (device: any): number => {
  if (!device.totalStock || !device.productCount) return 0;
  // 简单计算：假设每个商品标准库存为20，计算整体库存率
  const standardTotal = device.productCount * 20;
  if (standardTotal === 0) return 0;
  const ratio = Math.round((device.totalStock / standardTotal) * 100);
  return Math.min(ratio, 100);
};

const handleScanDevice = () => {
  uni.scanCode({
    onlyFromCamera: false,
    scanType: ['qrCode'],
    success: (res: any) => {
      const result = res.result || '';
      // 机身二维码格式: https://dev-haha.kuaiyuman.cn/{deviceId}
      const deviceIdMatch = result.match(/\/([^/]+)$/);
      if (!deviceIdMatch) {
        uni.showToast({ title: '无效的设备二维码', icon: 'none' });
        return;
      }
      const scannedDeviceId = deviceIdMatch[1];
      // 校验设备是否在补货员绑定列表中
      const found = deviceList.value.find((d: any) => d.deviceId === scannedDeviceId);
      if (!found) {
        uni.showToast({ title: '该设备未绑定，请联系管理员', icon: 'none' });
        return;
      }
      uni.navigateTo({
        url: `/pages/replenish/operation?deviceId=${scannedDeviceId}`
      });
    },
    fail: () => {
      // 用户取消扫码，不做提示
    }
  });
};

onMounted(async () => {
  try {
    // 获取补货员信息
    const info = getReplenisherInfo();
    if (info && info.id) {
      replenisherInfo.value = info;
    }

    // 获取补货员详情
    const detail = await getMyInfo();
    if (detail) {
      replenisherInfo.value = detail;
      totalTaskCount.value = detail.totalTasks || 0;
    }

    // 获取设备列表
    const devices = await getDeviceList();
    deviceList.value = devices || [];

    // 统计待补货数量
    lowStockTotal.value = devices.reduce((sum: number, d: any) => {
      return sum + (d.lowStockCount || 0) + (d.zeroStockCount || 0);
    }, 0);
  } 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;
}

/* 用户区域 */
.user-section {
  padding: 16rpx 24rpx;
}

.user-card {
  background: $bg-color-card;
  border: 1rpx solid $border-color;
  border-radius: 20rpx;
  padding: 28rpx;

  .user-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .avatar {
      width: 80rpx;
      height: 80rpx;
      background: $success-color-bg;
      border-radius: 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
      border: 2rpx solid $primary-color;

      .avatar-text {
        font-size: 36rpx;
        font-weight: 700;
        color: $primary-color;
      }
    }

    .user-info {
      flex: 1;

      .user-name {
        display: block;
        font-size: 32rpx;
        font-weight: 700;
        color: $text-color-primary;
      }

      .user-role {
        font-size: 24rpx;
        color: $primary-color;
        font-weight: 500;
      }

      .user-employee {
        font-size: 22rpx;
        color: $text-color-muted;
      }
    }
  }

  .user-stats {
    display: flex;
    background: $bg-color-page;
    border-radius: 12rpx;
    padding: 16rpx 0;

    .stat-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;

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

      .stat-label {
        font-size: 22rpx;
        color: $text-color-tertiary;
      }
    }

    .stat-divider {
      width: 1rpx;
      background: $border-color;
    }
  }
}

/* 快捷入口 */
.quick-actions {
  display: flex;
  padding: 0 24rpx 16rpx;
  gap: 16rpx;

  .action-btn {
    display: flex;
    align-items: center;
    gap: 8rpx;
    background: $bg-color-card;
    border: 1rpx solid $border-color;
    border-radius: 12rpx;
    padding: 16rpx 28rpx;

    .action-icon {
      font-size: 28rpx;
    }

    .action-label {
      font-size: 26rpx;
      font-weight: 500;
      color: $text-color-primary;
    }

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

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

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

/* 设备区域 */
.device-section {
  padding: 0 24rpx;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0 16rpx;

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

  .section-actions {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .scan-btn {
      display: flex;
      align-items: center;
      gap: 6rpx;
      padding: 10rpx 20rpx;
      background: $primary-color;
      border-radius: 10rpx;

      .scan-icon {
        font-size: 24rpx;
      }

      .scan-text {
        font-size: 24rpx;
        font-weight: 600;
        color: #fff;
      }

      &:active {
        opacity: 0.85;
      }
    }
  }

  .section-count {
    font-size: 24rpx;
    color: $text-color-muted;
  }
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;

  .empty-icon {
    width: 120rpx;
    height: 120rpx;
    background: $bg-color-secondary;
    border-radius: 24rpx;
    margin-bottom: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .icon-device {
      width: 40rpx;
      height: 32rpx;
      border: 4rpx solid $text-color-muted;
      border-radius: 6rpx;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        bottom: -8rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 20rpx;
        height: 8rpx;
        background: $text-color-muted;
        border-radius: 0 0 6rpx 6rpx;
      }
    }
  }

  .empty-text {
    font-size: 28rpx;
    color: $text-color-tertiary;
    margin-bottom: 8rpx;
  }

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

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

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

  .device-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12rpx;

    .device-info {
      flex: 1;

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

      .device-id {
        font-size: 22rpx;
        color: $text-color-muted;
      }
    }

    .device-status {
      padding: 6rpx 16rpx;
      border-radius: 8rpx;
      font-size: 22rpx;
      font-weight: 500;

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

      &.offline {
        background: $bg-color-secondary;
        color: $text-color-muted;
      }
    }
  }

  .device-address {
    margin-bottom: 16rpx;

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

  .stock-overview {
    display: flex;
    gap: 16rpx;
    margin-bottom: 12rpx;

    .stock-item {
      flex: 1;
      background: $bg-color-page;
      border-radius: 10rpx;
      padding: 12rpx;
      text-align: center;

      .stock-label {
        display: block;
        font-size: 20rpx;
        color: $text-color-muted;
        margin-bottom: 4rpx;
      }

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

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

        .stock-value { color: $warning-color; }
      }

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

        .stock-value { color: $error-color; }
      }
    }
  }

  .stock-bar {
    display: flex;
    align-items: center;
    gap: 12rpx;
    margin-bottom: 12rpx;

    .bar-bg {
      flex: 1;
      height: 8rpx;
      background: $bg-color-secondary;
      border-radius: 4rpx;
      overflow: hidden;

      .bar-fill {
        height: 100%;
        background: $primary-color;
        border-radius: 4rpx;
        transition: width 0.3s;
      }
    }

    .bar-text {
      font-size: 20rpx;
      color: $text-color-muted;
      width: 48rpx;
      text-align: right;
    }
  }

  .device-action {
    padding-top: 12rpx;
    border-top: 1rpx solid $bg-color-secondary;

    .action-text {
      font-size: 24rpx;
      color: $primary-color;
      font-weight: 500;
    }
  }
}
</style>
