<template>
  <view class="purchase-list-page">
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">‹</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">采购</text>
      </view>
      <view class="nav-right" @click="refreshList">
        <text class="refresh-text">刷新</text>
      </view>
    </view>
    
    <!-- 倒计时区域 -->
    <view class="countdown-section">
      <text class="countdown-label">采购进行中</text>
      <text class="countdown-time">{{ countdownTime }}</text>
    </view>
    
    <!-- 分页导航 -->
    <view class="pagination">
      <view 
        v-for="page in totalPages" 
        :key="page"
        class="page-item"
        :class="{ active: currentPage === page }"
        @click="changePage(page)"
      >
        {{ page }}页
      </view>
    </view>
    
    <!-- 商品列表 -->
    <view class="goods-list">
      <!-- 空状态显示 -->
      <view v-if="!loading && orderList.length === 0" class="empty-state">
        <image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">暂无商品</text>
      </view>
      
      <!-- 商品列表 -->
      <view 
        v-else 
        v-for="(item, index) in orderList" 
        :key="index"
        class="goods-item"
        @click="viewOrderDetail(item)"
      >
        <!-- 商品图片 -->
        <view class="goods-image">
          <image :src="item.image" mode="aspectFill"></image>
        </view>
        
        <!-- 商品信息 -->
        <view class="goods-info">
          <view class="goods-title">{{ item.title }}</view>
          <view class="goods-box">
            <text class="box-text">≈{{ item.boxCount }}箱</text>
          </view>
          <view class="goods-price">
            <text class="price-text">¥{{ item.price }}</text>
          </view>
          <view class="goods-status">
            <text class="status-text">等待采购</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getOrderGoods, buyGoods, getDefaultAddress } from '@/api/miao.js';

export default {
  data() {
    return {
      currentPage: 1,
      totalPages: 5,
      countdownTime: '00:12:05',
      countdownInterval: null,
      loading: false,
      orderList: []
    }
  },
  
  onLoad() {
    this.startCountdown();
    this.loadOrderList();
  },
  
  onUnload() {
    if (this.countdownInterval) {
      clearInterval(this.countdownInterval);
    }
  },
  
  methods: {
    // 加载订单列表
    async loadOrderList() {
      try {
        this.loading = true;
        // 使用真实接口获取可购买商品列表
        const res = await getOrderGoods({
          page: this.currentPage,
          limit: 20,
          type: 1 // 1:可购买
        });
        
        if (res.code === 0) {
          // 处理接口返回的数据，适配页面展示格式
          this.orderList = res.data.list.map(item => ({
            id: item.id,
            seller_id: item.sellerId,
            image: item.image || '/static/images/empty.png',
            title: item.title || '',
            boxCount: item.box_count || 0,
            price: item.price || '0.00'
          }));
          
          // 根据返回的总数计算总页数
          this.totalPages = Math.ceil(res.data.total / 10);
        }
      } catch (error) {
        console.error('加载订单列表失败:', error);
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 开始倒计时
    startCountdown() {
      // 从12分05秒开始倒计时
      let totalSeconds = 12 * 60 + 5;
      
      this.updateCountdownDisplay(totalSeconds);
      
      this.countdownInterval = setInterval(() => {
        totalSeconds--;
        
        if (totalSeconds <= 0) {
          clearInterval(this.countdownInterval);
          this.countdownTime = '00:00:00';
          // 可以在这里处理倒计时结束的逻辑
          return;
        }
        
        this.updateCountdownDisplay(totalSeconds);
      }, 1000);
    },
    
    // 更新倒计时显示
    updateCountdownDisplay(totalSeconds) {
      const hours = Math.floor(totalSeconds / 3600).toString().padStart(2, '0');
      const minutes = Math.floor((totalSeconds % 3600) / 60).toString().padStart(2, '0');
      const seconds = (totalSeconds % 60).toString().padStart(2, '0');
      
      this.countdownTime = `${hours}:${minutes}:${seconds}`;
    },
    
    // 切换页码
    changePage(page) {
      this.currentPage = page;
      this.loadOrderList();
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 刷新列表
    async refreshList() {
      await this.loadOrderList();
      // 显示刷新提示
      if (!this.loading) {
        uni.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1500
        });
      }
    },
    
    // 点击商品，显示确认采购对话框
    viewOrderDetail(item) {
      uni.showModal({
        title: '确认采购',
        content: '是否采购该商品？',
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 用户确认采购，提交抢单
            this.submitOrder(item);
          }
        }
      });
    },
    
    // 提交抢单
    async submitOrder(item) {
      try {
        // 显示加载提示
        uni.showLoading({
          title: '抢单中...',
          mask: true
        });
        
        // 调试信息，检查传递的参数
        console.log('抢单参数:', {
          id: item.id,
          seller_id: item.seller_id
        });
        
        // 检查seller_id是否存在
        if (!item.seller_id || item.seller_id === '') {
          uni.hideLoading();
          uni.showToast({
            title: '卖家信息异常，请刷新页面重试',
            icon: 'none'
          });
          return;
        }
        
        // 提交抢单，使用新的参数格式
        const res = await buyGoods({
          id: item.id,
          seller_id: item.seller_id
        });
        
        if (res.code === 0) {
          // 抢单成功
          uni.hideLoading();
          
          // 如果没有地址或需要选择地址，跳转到地址选择页
          // 并传递订单ID
          uni.navigateTo({
            url: `/pages/sub-pages/address/index?orderId=${res.data.order_id}`
          });
        } else {
          // 抢单失败
          uni.hideLoading();
          uni.showToast({
            title: res.msg || '抢单失败，请重试',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('提交抢单失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '网络错误，请检查网络连接',
          icon: 'none'
        });
      }
    }
  }
}
</script>

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

/* 顶部导航栏 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  background-color: #ffffff;
  padding: 0 30rpx;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .nav-left,
  .nav-right {
    width: 80rpx;
    display: flex;
    align-items: center;
    
    .nav-left {
      justify-content: flex-start;
    }
    
    .nav-right {
      justify-content: flex-end;
    }
  }
  
  .back-icon {
    font-size: 60rpx;
    color: #333333;
  }
  
  .nav-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
  }
  
  .refresh-text {
    font-size: 28rpx;
    color: #ff6b6b;
  }
}

/* 倒计时区域 */
.countdown-section {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
  background-color: #fff3e0;
  
  .countdown-label {
    font-size: 28rpx;
    color: #ff6b6b;
    margin-right: 10rpx;
  }
  
  .countdown-time {
    font-size: 28rpx;
    font-weight: bold;
    color: #ff6b6b;
    font-family: monospace;
  }
}

/* 分页导航 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
  background-color: #ffffff;
  margin-bottom: 20rpx;
  flex-wrap: wrap;
  
  .page-item {
    padding: 10rpx 30rpx;
    margin: 0 10rpx 10rpx 0;
    font-size: 28rpx;
    color: #666666;
    border-radius: 20rpx;
    
    &.active {
      background-color: #ff6b6b;
      color: #ffffff;
      font-weight: bold;
    }
  }
}

/* 商品列表 */
.goods-list {
  display: flex;
  flex-wrap: wrap;
  padding: 0 20rpx;
  
  .goods-item {
    width: 48%;
    margin: 0 1% 30rpx;
    background-color: #ffffff;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 15rpx rgba(0, 0, 0, 0.05);
  }
  
  .goods-image {
    width: 100%;
    height: 300rpx;
    
    image {
      width: 100%;
      height: 100%;
    }
  }
  
  .goods-info {
    padding: 20rpx;
  }
  
  .goods-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 15rpx;
    line-height: 1.4;
  }
  
  .goods-box {
    margin-bottom: 15rpx;
    
    .box-text {
      font-size: 24rpx;
      color: #4a90e2;
      font-weight: bold;
    }
  }
  
  .goods-price {
    margin-bottom: 15rpx;
    
    .price-text {
      font-size: 32rpx;
      color: #ff6b6b;
      font-weight: bold;
    }
  }
  
  .goods-status {
    
    .status-text {
      font-size: 24rpx;
      color: #ffffff;
      background-color: #ff6b6b;
      padding: 5rpx 15rpx;
      border-radius: 15rpx;
    }
  }
  
  /* 空状态样式 */
  .empty-state {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    
    .empty-image {
      width: 200rpx;
      height: 200rpx;
      opacity: 0.5;
      margin-bottom: 30rpx;
    }
    
    .empty-text {
      font-size: 28rpx;
      color: #999999;
    }
  }
}
</style>

