<template>
  <view class="shipping-container">
    <common-header title="发货历史" theme="shipping" @back="goBack" />
    
    <!-- 统计卡片 -->
    <uni-card title="发货统计" :is-shadow="false">
      <view class="stats-row">
        <view class="stat-item">
          <text class="stat-value">{{statsData.totalCount || 0}}</text>
          <text class="stat-label">总发货数</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{statsData.todayCount || 0}}</text>
          <text class="stat-label">今日发货</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{statsData.deliveredCount || 0}}</text>
          <text class="stat-label">已送达</text>
        </view>
      </view>
    </uni-card>
    
    <!-- 搜索栏 -->
    <uni-search-bar v-model="searchText" placeholder="搜索订单号或物流单号" @confirm="searchShipping" />
    
    <!-- 筛选标签 -->
    <uni-segmented-control :current="currentTab" :values="tabList" @clickItem="switchTab" />
    
    <!-- 操作按钮 -->
    <view class="action-bar">
      <uni-button type="primary" size="small" @click="addShipping">创建发货</uni-button>
      <uni-button type="success" size="small" @click="batchShipping">批量发货</uni-button>
      <uni-button type="default" size="small" @click="exportHistory">导出</uni-button>
      <uni-button type="default" size="small" @click="getShippingList">刷新</uni-button>
    </view>
    
    <!-- 发货列表 -->
    <uni-list>
      <uni-list-item v-for="(item, index) in shippingList" :key="index" 
        :title="item.orderNo" 
        :note="`物流单号: ${item.trackingNo}`"
        :rightText="item.logisticsCompany"
        :badgeText="getStatusText(item.status)"
        :badge-type="getStatusType(item.status)"
        @click="viewShipping(item)">
        
        <template v-slot:footer>
          <view class="item-footer">
            <view class="info-row">
              <text class="info-text">收货人: {{item.receiverName}}</text>
              <text class="info-text">发货时间: {{formatTime(item.shippingTime)}}</text>
            </view>
            <view class="actions">
              <uni-button size="mini" type="primary" @click.stop="viewLogistics(item)">物流</uni-button>
              <uni-button v-if="item.status === 0" size="mini" type="success" @click.stop="confirmShipping(item)">确认发货</uni-button>
              <uni-button v-if="item.status === 1" size="mini" type="primary" @click.stop="confirmReceipt(item)">确认收货</uni-button>
              <uni-button size="mini" type="default" @click.stop="editShipping(item)">编辑</uni-button>
            </view>
          </view>
        </template>
      </uni-list-item>
    </uni-list>
    
    <!-- 加载更多 -->
    <uni-load-more :status="loadStatus" />
  </view>
</template>

<script>
import CommonHeader from '@/components/common-header/common-header.vue'
import { getShippingList, getShippingStats, confirmShipping, confirmReceipt, exportShippingHistory, batchShipping } from '@/api/brewery/shipping'

export default {
  components: {
    CommonHeader
  },
  
  data() {
    return {
      searchText: '',
      shippingList: [],
      statsData: {},
      loadStatus: 'more',
      pageNum: 1,
      pageSize: 10,
      currentTab: 0,
      tabList: ['全部', '待发货', '已发货', '运输中', '已送达']
    }
  },
  
  onLoad() {
    this.getStatsData()
    this.getShippingList()
  },
  
  onReachBottom() {
    if (this.loadStatus === 'more') {
      this.pageNum++
      this.getShippingList()
    }
  },
  
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    async getStatsData() {
      try {
        const res = await getShippingStats()
        this.statsData = res.data
      } catch (error) {
        console.log('获取统计数据失败', error)
      }
    },
    
    async getShippingList() {
      try {
        this.loadStatus = 'loading'
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          orderNo: this.searchText,
          status: this.currentTab === 0 ? '' : this.currentTab - 1
        }
        const res = await getShippingList(params)
        
        if (this.pageNum === 1) {
          this.shippingList = res.rows
        } else {
          this.shippingList = [...this.shippingList, ...res.rows]
        }
        
        this.loadStatus = res.rows.length < this.pageSize ? 'noMore' : 'more'
      } catch (error) {
        this.loadStatus = 'more'
        this.$modal.showToast('获取发货列表失败')
      }
    },
    
    switchTab(e) {
      this.currentTab = e.currentIndex
      this.pageNum = 1
      this.getShippingList()
    },
    
    searchShipping() {
      this.pageNum = 1
      this.getShippingList()
    },
    
    addShipping() {
      uni.navigateTo({
        url: '/subpages/shipping/add'
      })
    },
    
    viewShipping(item) {
      uni.navigateTo({
        url: `/subpages/shipping/detail?id=${item.id}`
      })
    },
    
    editShipping(item) {
      uni.navigateTo({
        url: `/subpages/shipping/edit?id=${item.id}`
      })
    },
    
    viewLogistics(item) {
      uni.navigateTo({
        url: `/subpages/shipping/logistics?trackingNo=${item.trackingNo}`
      })
    },
    
    async confirmShipping(item) {
      try {
        const res = await this.$modal.showConfirm('确定确认发货吗？')
        if (res.confirm) {
          await confirmShipping(item.id)
          this.$modal.showToast('确认成功')
          this.pageNum = 1
          this.getShippingList()
        }
      } catch (error) {
        this.$modal.showToast('确认失败')
      }
    },
    
    async confirmReceipt(item) {
      try {
        const res = await this.$modal.showConfirm('确定确认收货吗？')
        if (res.confirm) {
          await confirmReceipt(item.id)
          this.$modal.showToast('确认成功')
          this.pageNum = 1
          this.getShippingList()
        }
      } catch (error) {
        this.$modal.showToast('确认失败')
      }
    },
    
    async batchShipping() {
      uni.navigateTo({
        url: '/subpages/shipping/batch'
      })
    },
    
    async exportHistory() {
      try {
        const res = await exportShippingHistory({
          status: this.currentTab === 0 ? '' : this.currentTab - 1
        })
        this.$modal.showToast('导出成功')
      } catch (error) {
        this.$modal.showToast('导出失败')
      }
    },
    
    getStatusText(status) {
      const statusMap = {
        0: '待发货',
        1: '已发货',
        2: '运输中',
        3: '已送达'
      }
      return statusMap[status] || '未知'
    },
    
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'info',
        3: 'success'
      }
      return typeMap[status] || 'default'
    },
    
    formatTime(time) {
      if (!time) return ''
      return time.substring(0, 16)
    }
  }
}
</script>

<style lang="scss" scoped>
.shipping-container {
  padding: 20rpx;
}

.stats-row {
  display: flex;
  justify-content: space-around;
  
  .stat-item {
    text-align: center;
    
    .stat-value {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #007aff;
    }
    
    .stat-label {
      display: block;
      font-size: 24rpx;
      color: #666;
      margin-top: 10rpx;
    }
  }
}

.action-bar {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
  gap: 5rpx;
}

.item-footer {
  padding: 10rpx 0;
  
  .info-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10rpx;
    
    .info-text {
      font-size: 24rpx;
      color: #666;
    }
  }
  
  .actions {
    display: flex;
    gap: 10rpx;
  }
}
</style> 