<template>
  <view class="distiller-container">
    <common-header title="酒头接管" theme="distiller" @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.activeCount || 0}}</text>
          <text class="stat-label">活跃酒头</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{statsData.pendingCount || 0}}</text>
          <text class="stat-label">待接管</text>
        </view>
      </view>
    </uni-card>
    
    <!-- 搜索栏 -->
    <uni-search-bar v-model="searchText" placeholder="搜索酒头名称或负责人" @confirm="searchDistiller" />
    
    <!-- 筛选标签 -->
    <uni-segmented-control :current="currentTab" :values="tabList" @clickItem="switchTab" />
    
    <!-- 操作按钮 -->
    <view class="action-bar">
      <uni-button type="primary" size="small" @click="addDistiller">创建酒头</uni-button>
      <uni-button type="success" size="small" @click="viewHistory">接管历史</uni-button>
      <uni-button type="default" size="small" @click="getDistillerList">刷新</uni-button>
    </view>
    
    <!-- 酒头列表 -->
    <uni-list>
      <uni-list-item v-for="(item, index) in distillerList" :key="index" 
        :title="item.name" 
        :note="`负责人: ${item.manager}`"
        :rightText="item.region"
        :badgeText="getStatusText(item.status)"
        :badge-type="getStatusType(item.status)"
        @click="viewDistiller(item)">
        
        <template v-slot:footer>
          <view class="item-footer">
            <view class="info-row">
              <text class="info-text">产量: {{item.production}}吨</text>
              <text class="info-text">创建时间: {{formatTime(item.createTime)}}</text>
            </view>
            <view class="actions">
              <uni-button size="mini" type="primary" @click.stop="editDistiller(item)">编辑</uni-button>
              <uni-button v-if="item.status === 0" size="mini" type="success" @click.stop="takeoverDistiller(item)">接管</uni-button>
              <uni-button v-if="item.status === 1" size="mini" type="warn" @click.stop="transferDistiller(item)">转让</uni-button>
              <uni-button v-if="item.status === 0" size="mini" type="primary" @click.stop="auditDistiller(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 { getDistillerList, getDistillerStats, takeoverDistiller, auditDistiller } from '@/api/brewery/distiller'

export default {
  components: {
    CommonHeader
  },
  
  data() {
    return {
      searchText: '',
      distillerList: [],
      statsData: {},
      loadStatus: 'more',
      pageNum: 1,
      pageSize: 10,
      currentTab: 0,
      tabList: ['全部', '待接管', '已接管', '已转让', '已停用']
    }
  },
  
  onLoad() {
    this.getStatsData()
    this.getDistillerList()
  },
  
  onReachBottom() {
    if (this.loadStatus === 'more') {
      this.pageNum++
      this.getDistillerList()
    }
  },
  
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    async getStatsData() {
      try {
        const res = await getDistillerStats()
        this.statsData = res.data
      } catch (error) {
        console.log('获取统计数据失败', error)
      }
    },
    
    async getDistillerList() {
      try {
        this.loadStatus = 'loading'
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.searchText,
          status: this.currentTab === 0 ? '' : this.currentTab - 1
        }
        const res = await getDistillerList(params)
        
        if (this.pageNum === 1) {
          this.distillerList = res.rows
        } else {
          this.distillerList = [...this.distillerList, ...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.getDistillerList()
    },
    
    searchDistiller() {
      this.pageNum = 1
      this.getDistillerList()
    },
    
    addDistiller() {
      uni.navigateTo({
        url: '/subpages/distiller/add'
      })
    },
    
    viewDistiller(item) {
      uni.navigateTo({
        url: `/subpages/distiller/detail?id=${item.id}`
      })
    },
    
    editDistiller(item) {
      uni.navigateTo({
        url: `/subpages/distiller/edit?id=${item.id}`
      })
    },
    
    viewHistory() {
      uni.navigateTo({
        url: '/subpages/distiller/history'
      })
    },
    
    async takeoverDistiller(item) {
      try {
        const res = await this.$modal.showConfirm('确定接管此酒头吗？')
        if (res.confirm) {
          await takeoverDistiller(item.id)
          this.$modal.showToast('接管成功')
          this.pageNum = 1
          this.getDistillerList()
        }
      } catch (error) {
        this.$modal.showToast('接管失败')
      }
    },
    
    async auditDistiller(item) {
      try {
        const res = await this.$modal.showConfirm('确定审核通过此酒头吗？')
        if (res.confirm) {
          await auditDistiller({
            id: item.id,
            status: 1
          })
          this.$modal.showToast('审核成功')
          this.pageNum = 1
          this.getDistillerList()
        }
      } catch (error) {
        this.$modal.showToast('审核失败')
      }
    },
    
    transferDistiller(item) {
      uni.navigateTo({
        url: `/subpages/distiller/transfer?id=${item.id}`
      })
    },
    
    getStatusText(status) {
      const statusMap = {
        0: '待接管',
        1: '已接管',
        2: '已转让',
        3: '已停用'
      }
      return statusMap[status] || '未知'
    },
    
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'success',
        2: 'primary',
        3: 'error'
      }
      return typeMap[status] || 'default'
    },
    
    formatTime(time) {
      if (!time) return ''
      return time.substring(0, 16)
    }
  }
}
</script>

<style lang="scss" scoped>
.distiller-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: 10rpx;
}

.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> 