<template>
  <view class="container">
    <!-- 订单类型选项卡 -->
    <view class="tab-bar">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        class="tab-item"
        :class="{ active: currentTab === index }"
        @click="switchTab(index)"
      >
        <text>{{ tab.text }}</text>
      </view>
    </tab-bar>

    <!-- 订单列表 -->
    <scroll-view 
      class="order-list" 
      scroll-y="true"
      @scrolltolower="loadMore"
    >
      <view v-if="orders.length === 0" class="empty-tip">
        <image src="/static/user/empty-order.png" class="empty-image"></image>
        <text>暂无相关订单</text>
      </view>
      
      <view 
        v-for="(order, index) in orders" 
        :key="index"
        class="order-item"
        @click="navigateToDetail(order.id)"
      >
        <!-- 订单头部 -->
        <view class="order-header">
          <text class="order-type">{{ getOrderTypeName(order.type) }}</text>
          <text class="order-status">{{ getStatusText(order.status) }}</text>
        </view>
        
        <!-- 订单内容 -->
        <view class="order-content">
          <image :src="order.image" class="order-image"></image>
          <view class="order-info">
            <text class="order-title">{{ order.title }}</text>
            <text class="order-desc">{{ order.description }}</text>
            <view class="order-price-box">
              <text class="order-price">¥{{ order.price }}</text>
              <text class="order-count">x{{ order.count }}</text>
            </view>
          </view>
        </view>
        
        <!-- 订单操作 -->
        <view class="order-actions">
          <button 
            v-for="action in getAvailableActions(order.status)" 
            :key="action.type"
            class="action-btn"
            :class="action.type"
            @click.stop="handleAction(action.type, order)"
          >
            {{ action.text }}
          </button>
        </view>
      </view>
      
      <!-- 加载更多提示 -->
      <view class="load-more" v-if="loading">
        <text>加载中...</text>
      </view>
      <view class="load-more" v-else-if="hasMore">
        <text>上拉加载更多</text>
      </view>
      <view class="load-more" v-else-if="orders.length > 0">
        <text>没有更多了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { orderService } from '../../api/services.js'

export default {
  data() {
    return {
      currentTab: 0,
      tabs: [
        { type: 'all', text: '全部' },
        { type: 'unpaid', text: '待付款' },
        { type: 'undelivered', text: '待发货' },
        { type: 'delivered', text: '待收货' },
        { type: 'completed', text: '已完成' }
      ],
      orders: [],
      loading: false,
      hasMore: true,
      page: 1,
      pageSize: 10,
      statusFilter: 'all'
    }
  },
  
  onLoad(options) {
    if (options.type) {
      const tabIndex = this.tabs.findIndex(tab => tab.type === options.type)
      if (tabIndex !== -1) {
        this.currentTab = tabIndex
        this.statusFilter = options.type
      }
    }
    this.loadOrders()
  },
  
  methods: {
    async loadOrders() {
      if (this.loading || !this.hasMore) return
      
      this.loading = true
      try {
        const params = {
          page: this.page,
          pageSize: this.pageSize
        }
        
        if (this.statusFilter !== 'all') {
          params.status = this.statusFilter
        }
        
        const data = await orderService.getList(params)
        const newOrders = data.orders || data
        
        if (this.page === 1) {
          this.orders = newOrders
        } else {
          this.orders = [...this.orders, ...newOrders]
        }
        
        this.hasMore = newOrders.length === this.pageSize
        this.page++
      } catch (error) {
        console.error('获取订单列表失败:', error)
        uni.showToast({
          title: '获取订单失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    async loadMore() {
      if (this.hasMore && !this.loading) {
        this.loadOrders()
      }
    },
    
    switchTab(index) {
      this.currentTab = index
      this.statusFilter = this.tabs[index].type
      this.page = 1
      this.orders = []
      this.hasMore = true
      this.loadOrders()
    },
    
    getOrderTypeName(type) {
      const types = {
        travel: '旅行计划',
        animal: '动物认养',
        flower: '送花服务'
      }
      return types[type] || '未知类型'
    },
    
    getStatusText(status) {
      const statuses = {
        unpaid: '待付款',
        undelivered: '待发货',
        delivered: '待收货',
        completed: '已完成',
        cancelled: '已取消'
      }
      return statuses[status] || '未知状态'
    },
    
    getAvailableActions(status) {
      const actions = {
        unpaid: [
          { type: 'cancel', text: '取消订单' },
          { type: 'pay', text: '立即付款' }
        ],
        undelivered: [
          { type: 'cancel', text: '取消订单' }
        ],
        delivered: [
          { type: 'confirm', text: '确认收货' }
        ],
        completed: [],
        cancelled: []
      }
      return actions[status] || []
    },
    
    async handleAction(actionType, order) {
      try {
        switch (actionType) {
          case 'cancel':
            await orderService.cancel(order.id)
            uni.showToast({ title: '订单已取消' })
            break
          case 'pay':
            // 跳转到支付页面
            uni.navigateTo({ url: `/pages/payment/index?orderId=${order.id}` })
            return
          case 'confirm':
            await orderService.confirm(order.id)
            uni.showToast({ title: '已确认收货' })
            break
        }
        
        // 重新加载订单列表
        this.page = 1
        this.orders = []
        this.hasMore = true
        this.loadOrders()
      } catch (error) {
        console.error('操作失败:', error)
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },
    
    navigateToDetail(id) {
      uni.navigateTo({ url: `/pages/order/detail?id=${id}` })
    }
  }
}
</script>

<style scoped>
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
}

.tab-bar {
  display: flex;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  font-size: 28rpx;
  color: #666;
}

.tab-item.active {
  color: #007aff;
  border-bottom: 4rpx solid #007aff;
}

.order-list {
  height: calc(100vh - 100rpx);
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.order-item {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
}

.order-type {
  font-weight: bold;
  color: #333;
}

.order-status {
  color: #ff6b35;
}

.order-content {
  display: flex;
  padding: 30rpx;
}

.order-image {
  width: 150rpx;
  height: 150rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.order-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.order-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.order-desc {
  color: #999;
  font-size: 24rpx;
  margin-bottom: 10rpx;
}

.order-price-box {
  display: flex;
  justify-content: space-between;
}

.order-price {
  color: #ff6b35;
  font-weight: bold;
}

.order-count {
  color: #999;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
}

.action-btn {
  padding: 10rpx 20rpx;
  margin-left: 20rpx;
  border-radius: 6rpx;
  font-size: 26rpx;
  border: 1rpx solid #ddd;
}

.action-btn.cancel {
  color: #ff3b30;
  border-color: #ff3b30;
}

.action-btn.pay, .action-btn.confirm {
  color: #007aff;
  border-color: #007aff;
}

.load-more {
  text-align: center;
  padding: 30rpx;
  color: #999;
  font-size: 26rpx;
}
</style>