<template>
  <view class="batch-container">
    <common-header title="批量操作" theme="order" @back="goBack" />
    
    <view class="batch-content">
      <view class="batch-actions">
        <uni-button type="primary" size="small" @click="selectAll">全选</uni-button>
        <uni-button type="default" size="small" @click="clearSelection">清空</uni-button>
        <uni-button type="warn" size="small" @click="batchExport" :disabled="selectedOrders.length === 0">
          导出 ({{ selectedOrders.length }})
        </uni-button>
        <uni-button type="warn" size="small" @click="batchDelete" :disabled="selectedOrders.length === 0">
          删除 ({{ selectedOrders.length }})
        </uni-button>
      </view>
      
      <view class="filter-section">
        <uni-search-bar 
          v-model="searchText" 
          placeholder="搜索订单" 
          @confirm="searchOrders" 
          @clear="clearSearch" />
      </view>
      
      <scroll-view 
        class="scroll-view" 
        scroll-y 
        :refresher-enabled="true"
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
        @scrolltolower="onLoadMore">
        
        <view v-if="!loading && orderList.length === 0" class="empty-state">
          <uni-icons type="list" size="80" color="#ddd" />
          <text class="empty-text">暂无订单数据</text>
        </view>
        
        <view v-else class="order-list">
          <view 
            v-for="(item, index) in orderList" 
            :key="item.id || index" 
            class="order-item"
            :class="{ 'selected': selectedOrders.includes(item.id) }"
            @click="toggleSelection(item.id)">
            
            <view class="item-checkbox">
              <uni-icons 
                :type="selectedOrders.includes(item.id) ? 'checkbox-filled' : 'checkbox'" 
                size="20" 
                :color="selectedOrders.includes(item.id) ? '#007aff' : '#ccc'" />
            </view>
            
            <view class="item-content">
              <view class="item-header">
                <text class="order-no">{{ item.orderNo }}</text>
                <text class="order-amount">¥{{ item.totalAmount || 0 }}</text>
              </view>
              
              <view class="item-info">
                <text class="customer-name">{{ item.customerName }}</text>
                <text class="product-name">{{ item.productName }}</text>
              </view>
              
              <view class="item-footer">
                <text class="order-time">{{ formatTime(item.createTime) }}</text>
                <view class="status-badge" :class="{ 
                  'pending': item.status === 0,
                  'processing': item.status === 1,
                  'completed': item.status === 2,
                  'cancelled': item.status === 3
                }">
                  {{ getStatusText(item.status) }}
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <uni-load-more 
          :status="loadStatus" 
          :content-text="loadText" 
          @clickLoadMore="onLoadMore" />
      </scroll-view>
    </view>
  </view>
</template>

<script>
import CommonHeader from '@/components/common-header/common-header.vue'

export default {
  name: 'OrderBatch',
  components: {
    CommonHeader
  },
  
  data() {
    return {
      orderList: [],
      selectedOrders: [],
      loading: false,
      refreshing: false,
      searchText: '',
      page: 1,
      pageSize: 20,
      hasMore: true,
      loadStatus: 'more',
      loadText: {
        contentdown: '上拉加载更多',
        contentrefresh: '正在加载...',
        contentnomore: '没有更多了'
      }
    }
  },
  
  onLoad() {
    this.loadOrderList()
  },
  
  methods: {
    async loadOrderList(isRefresh = false) {
      if (isRefresh) {
        this.page = 1
        this.hasMore = true
      }
      
      if (!this.hasMore && !isRefresh) return
      
      this.loading = true
      this.loadStatus = 'loading'
      
      try {
        const params = {
          page: this.page,
          pageSize: this.pageSize,
          search: this.searchText
        }
        
        // TODO: Replace with actual API call
        const response = await this.$http.get('/brewery/order', { params })
        const { list, total } = response.data || {}
        
        if (isRefresh) {
          this.orderList = list || []
          this.selectedOrders = []
        } else {
          this.orderList = [...this.orderList, ...(list || [])]
        }
        
        this.hasMore = this.orderList.length < total
        this.loadStatus = this.hasMore ? 'more' : 'noMore'
        
      } catch (error) {
        console.error('加载订单列表失败:', error)
        this.$modal.showToast('加载失败')
        this.loadStatus = 'more'
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },
    
    onRefresh() {
      this.refreshing = true
      this.loadOrderList(true)
    },
    
    onLoadMore() {
      if (this.hasMore && !this.loading) {
        this.page++
        this.loadOrderList()
      }
    },
    
    searchOrders() {
      this.loadOrderList(true)
    },
    
    clearSearch() {
      this.searchText = ''
      this.loadOrderList(true)
    },
    
    toggleSelection(orderId) {
      const index = this.selectedOrders.indexOf(orderId)
      if (index > -1) {
        this.selectedOrders.splice(index, 1)
      } else {
        this.selectedOrders.push(orderId)
      }
    },
    
    selectAll() {
      this.selectedOrders = this.orderList.map(item => item.id)
    },
    
    clearSelection() {
      this.selectedOrders = []
    },
    
    batchExport() {
      if (this.selectedOrders.length === 0) {
        this.$modal.showToast('请先选择订单')
        return
      }
      
      uni.showModal({
        title: '确认导出',
        content: `确定要导出选中的 ${this.selectedOrders.length} 个订单吗？`,
        success: (res) => {
          if (res.confirm) {
            this.doBatchExport()
          }
        }
      })
    },
    
    async doBatchExport() {
      try {
        // TODO: Replace with actual API call
        const response = await this.$http.post('/brewery/order/export', {
          orderIds: this.selectedOrders
        })
        
        this.$modal.showToast('导出成功')
        this.clearSelection()
      } catch (error) {
        console.error('导出失败:', error)
        this.$modal.showToast('导出失败')
      }
    },
    
    batchDelete() {
      if (this.selectedOrders.length === 0) {
        this.$modal.showToast('请先选择订单')
        return
      }
      
      uni.showModal({
        title: '确认删除',
        content: `确定要删除选中的 ${this.selectedOrders.length} 个订单吗？此操作不可恢复！`,
        success: (res) => {
          if (res.confirm) {
            this.doBatchDelete()
          }
        }
      })
    },
    
    async doBatchDelete() {
      try {
        // TODO: Replace with actual API call
        const response = await this.$http.post('/brewery/order/batch-delete', {
          orderIds: this.selectedOrders
        })
        
        this.$modal.showToast('删除成功')
        this.clearSelection()
        this.loadOrderList(true)
      } catch (error) {
        console.error('删除失败:', error)
        this.$modal.showToast('删除失败')
      }
    },
    
    getStatusText(status) {
      const statusMap = {
        0: '待处理',
        1: '处理中',
        2: '已完成',
        3: '已取消'
      }
      return statusMap[status] || '未知'
    },
    
    formatTime(time) {
      if (!time) return ''
      return time.substring(0, 16)
    },
    
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.batch-container {
  min-height: 100vh;
  background: #f5f7fa;
}

.batch-content {
  padding: 20rpx;
}

.batch-actions {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 16rpx;
}

.filter-section {
  margin-bottom: 20rpx;
}

.scroll-view {
  height: calc(100vh - 280rpx);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-top: 20rpx;
  }
}

.order-list {
  .order-item {
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
    
    &.selected {
      background: #f0f9ff;
      border: 2rpx solid #007aff;
    }
    
    .item-checkbox {
      margin-right: 20rpx;
    }
    
    .item-content {
      flex: 1;
      
      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12rpx;
        
        .order-no {
          font-size: 30rpx;
          font-weight: bold;
          color: #333;
        }
        
        .order-amount {
          font-size: 28rpx;
          font-weight: bold;
          color: #007aff;
        }
      }
      
      .item-info {
        margin-bottom: 12rpx;
        
        .customer-name {
          display: block;
          font-size: 26rpx;
          color: #666;
          margin-bottom: 4rpx;
        }
        
        .product-name {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .item-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .order-time {
          font-size: 24rpx;
          color: #999;
        }
        
        .status-badge {
          padding: 6rpx 12rpx;
          border-radius: 16rpx;
          font-size: 22rpx;
          
          &.pending {
            background: #fff2e8;
            color: #fa8c16;
          }
          
          &.processing {
            background: #e6f7ff;
            color: #1890ff;
          }
          
          &.completed {
            background: #e8f5e8;
            color: #52c41a;
          }
          
          &.cancelled {
            background: #ffebee;
            color: #f44336;
          }
        }
      }
    }
  }
}
</style> 