<template>
  <view class="products-page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="errorMsg" class="error-container">
      <text class="error-icon">!</text>
      <text class="error-text">{{ errorMsg }}</text>
      <view class="error-btn" @click="goBack">返回</view>
    </view>

    <!-- 商品内容 -->
    <view v-else class="content">
      <!-- 顶部设备信息 -->
      <view class="device-header">
        <view class="device-name">{{ templateName || '智能零售柜' }}</view>
        <view class="device-info">
          <text class="info-tag">{{ deviceTypeText }}</text>
          <text class="info-tag">共{{ shelfNum }}层</text>
        </view>
      </view>

      <!-- 双门柜Tab切换 -->
      <view v-if="hasRightDoor" class="door-tabs">
        <view
          class="door-tab"
          :class="{ active: activeDoor === 'left' }"
          @click="activeDoor = 'left'"
        >左门</view>
        <view
          class="door-tab"
          :class="{ active: activeDoor === 'right' }"
          @click="activeDoor = 'right'"
        >右门</view>
      </view>

      <!-- 商品列表 -->
      <view class="floors-list">
        <view
          v-for="floor in currentFloors"
          :key="floor.floor"
          class="floor-card"
        >
          <view class="floor-header">
            <view class="floor-badge">{{ floor.floor }}</view>
            <text class="floor-title">第{{ floor.floor }}层</text>
            <text class="floor-count">{{ floor.goods?.length || 0 }}件商品</text>
          </view>

          <!-- 该层无商品 -->
          <view v-if="!floor.goods || floor.goods.length === 0" class="empty-floor">
            <text class="empty-text">该层暂无商品</text>
          </view>

          <!-- 商品列表 -->
          <view v-else class="goods-list">
            <view
              v-for="(item, index) in floor.goods"
              :key="index"
              class="goods-item"
            >
              <!-- 商品图片 -->
              <view class="goods-image-wrap">
                <image
                  v-if="item.pic"
                  :src="item.pic"
                  class="goods-image"
                  mode="aspectFill"
                />
                <view v-else class="goods-image-placeholder">
                  <text class="placeholder-text">暂无图片</text>
                </view>
              </view>

              <!-- 商品信息 -->
              <view class="goods-info">
                <text class="goods-name">{{ item.label || '未知商品' }}</text>
                <text v-if="item.type" class="goods-type">{{ item.type }}</text>
                <view class="goods-price-row">
                  <text class="goods-price">¥{{ item.c_price || '0.00' }}</text>
                  <text
                    v-if="item.dis_price && item.dis_price !== item.c_price"
                    class="goods-discount-price"
                  >¥{{ item.dis_price }}</text>
                </view>
                <view v-if="item.stock !== undefined && item.stock !== null" class="goods-stock">
                  <text class="stock-label">库存: </text>
                  <text :class="item.stock > 0 ? 'stock-normal' : 'stock-empty'">{{ item.stock }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 无任何层数据 -->
        <view v-if="currentFloors.length === 0" class="empty-container">
          <text class="empty-icon">📦</text>
          <text class="empty-main-text">暂无商品信息</text>
          <text class="empty-sub-text">该设备尚未配置商品</text>
        </view>
      </view>

      <!-- 底部占位，避免被固定栏遮挡 -->
      <view class="bottom-placeholder"></view>
    </view>

    <!-- 底部操作栏 -->
    <view v-if="!loading && !errorMsg" class="bottom-bar">
      <view class="btn-exit" @click="goBack">退出</view>
      <view class="btn-open" @click="handleOpenDoor">开门购物</view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getDeviceProducts, scanDoor } from '@/api/device';
import type { FloorConfig } from '@/api/device';

// 页面参数
const deviceId = ref('');

// 数据状态
const loading = ref(true);
const errorMsg = ref('');
const templateName = ref('');
const shelfNum = ref(0);
const deviceType = ref(0);
const leftFloors = ref<FloorConfig[]>([]);
const rightFloors = ref<FloorConfig[]>([]);
const opening = ref(false);

// 双门柜切换
const activeDoor = ref<'left' | 'right'>('left');

// 是否双门柜
const hasRightDoor = computed(() => rightFloors.value.length > 0);

// 设备类型文字
const deviceTypeText = computed(() => {
  return hasRightDoor.value ? '双门柜' : '单门柜';
});

// 当前显示的层数据
const currentFloors = computed(() => {
  if (activeDoor.value === 'right' && hasRightDoor.value) {
    return rightFloors.value;
  }
  return leftFloors.value;
});

// 页面加载
onLoad((options: any) => {
  if (options?.deviceId) {
    deviceId.value = options.deviceId;
    loadProducts();
  } else {
    errorMsg.value = '缺少设备ID参数';
    loading.value = false;
  }
});

// 加载商品数据
const loadProducts = async () => {
  loading.value = true;
  errorMsg.value = '';

  try {
    const data = await getDeviceProducts(deviceId.value);
    templateName.value = data.templateName || '';
    shelfNum.value = data.shelfNum || 0;
    deviceType.value = data.deviceType || 0;
    leftFloors.value = data.leftFloors || [];
    rightFloors.value = data.rightFloors || [];
  } catch (error: any) {
    console.error('加载商品数据失败:', error);
    errorMsg.value = error.message || '加载失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 开门购物
const handleOpenDoor = async () => {
  if (opening.value) return;
  opening.value = true;

  uni.showLoading({
    title: '正在开门...',
    mask: true
  });

  try {
    const response = await scanDoor(deviceId.value);

    uni.hideLoading();
    uni.showToast({
      title: '开门成功',
      icon: 'success'
    });

    // 存储设备信息
    uni.setStorageSync('currentDeviceId', response.deviceId);
    uni.setStorageSync('currentOutTradeNo', response.outTradeNo);
    uni.setStorageSync('currentOrderNo', response.orderNo);
    uni.removeStorageSync('shoppingPollingActive');

    // 跳转到购物页面
    setTimeout(() => {
      uni.redirectTo({
        url: '/pages/shopping/shopping'
      });
    }, 1000);
  } catch (error: any) {
    uni.hideLoading();
    opening.value = false;
    console.error('开门失败:', error);
  }
};

// 返回
const goBack = () => {
  uni.navigateBack({
    fail: () => {
      uni.reLaunch({ url: '/pages/index/index' });
    }
  });
};
</script>

<style lang="scss" scoped>
.products-page {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
}
.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #e0e0e0;
  border-top-color: #FFD700;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}
@keyframes spin {
  to { transform: rotate(360deg); }
}
.loading-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999;
}

/* 错误状态 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  padding: 0 60rpx;
}
.error-icon {
  width: 80rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background: #ff4d4f;
  color: #fff;
  border-radius: 50%;
  font-size: 40rpx;
  font-weight: bold;
}
.error-text {
  margin-top: 24rpx;
  font-size: 28rpx;
  color: #666;
  text-align: center;
}
.error-btn {
  margin-top: 40rpx;
  padding: 16rpx 60rpx;
  background: #FFD700;
  color: #333;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: bold;
}

/* 设备信息头部 */
.device-header {
  background: linear-gradient(135deg, #FFD700, #FFA500);
  padding: 30rpx;
  color: #333;
}
.device-name {
  font-size: 36rpx;
  font-weight: bold;
}
.device-info {
  display: flex;
  gap: 16rpx;
  margin-top: 12rpx;
}
.info-tag {
  font-size: 24rpx;
  background: rgba(255,255,255,0.5);
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  color: #555;
}

/* 门Tab切换 */
.door-tabs {
  display: flex;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}
.door-tab {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
}
.door-tab.active {
  color: #333;
  font-weight: bold;
}
.door-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: #FFD700;
  border-radius: 2rpx;
}

/* 楼层列表 */
.floors-list {
  padding: 20rpx;
}
.floor-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}
.floor-header {
  display: flex;
  align-items: center;
  padding: 20rpx 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}
.floor-badge {
  width: 44rpx;
  height: 44rpx;
  line-height: 44rpx;
  text-align: center;
  background: #FFD700;
  color: #333;
  border-radius: 10rpx;
  font-size: 24rpx;
  font-weight: bold;
  margin-right: 16rpx;
}
.floor-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}
.floor-count {
  font-size: 24rpx;
  color: #999;
}

/* 空楼层 */
.empty-floor {
  padding: 40rpx 0;
  text-align: center;
}
.empty-text {
  font-size: 26rpx;
  color: #ccc;
}

/* 商品列表 */
.goods-list {
  padding: 0 24rpx;
}
.goods-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}
.goods-item:last-child {
  border-bottom: none;
}

/* 商品图片 */
.goods-image-wrap {
  width: 140rpx;
  height: 140rpx;
  border-radius: 12rpx;
  overflow: hidden;
  flex-shrink: 0;
  background: #f9f9f9;
}
.goods-image {
  width: 100%;
  height: 100%;
}
.goods-image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f0f0;
}
.placeholder-text {
  font-size: 20rpx;
  color: #ccc;
}

/* 商品信息 */
.goods-info {
  flex: 1;
  margin-left: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.goods-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.goods-type {
  font-size: 22rpx;
  color: #999;
  margin-top: 6rpx;
}
.goods-price-row {
  display: flex;
  align-items: baseline;
  gap: 12rpx;
  margin-top: 8rpx;
}
.goods-price {
  font-size: 32rpx;
  color: #ff4d4f;
  font-weight: bold;
}
.goods-discount-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}
.goods-stock {
  margin-top: 6rpx;
  font-size: 22rpx;
}
.stock-label {
  color: #999;
}
.stock-normal {
  color: #52c41a;
}
.stock-empty {
  color: #ff4d4f;
}

/* 无数据 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;
}
.empty-icon {
  font-size: 80rpx;
}
.empty-main-text {
  margin-top: 20rpx;
  font-size: 30rpx;
  color: #333;
  font-weight: bold;
}
.empty-sub-text {
  margin-top: 8rpx;
  font-size: 26rpx;
  color: #999;
}

/* 底部占位 */
.bottom-placeholder {
  height: 140rpx;
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.08);
}
.btn-exit {
  flex: 1;
  text-align: center;
  padding: 22rpx 0;
  border-radius: 44rpx;
  font-size: 30rpx;
  font-weight: bold;
  color: #666;
  background: #f0f0f0;
}
.btn-open {
  flex: 2;
  text-align: center;
  padding: 22rpx 0;
  border-radius: 44rpx;
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  background: linear-gradient(135deg, #FFD700, #FFC107);
  box-shadow: 0 4rpx 12rpx rgba(255, 215, 0, 0.4);
}
</style>
