<template>
  <view class="livestock-page">
    <!-- 顶部搜索栏 -->
    <view class="search-section">
      <Search
        v-model="searchKeyword"
        placeholder="搜索牲畜编号、品种"
        @search="handleSearch"
        @clear="handleSearchClear"
      />
    </view>
    
    <!-- 筛选标签 -->
    <view class="filter-section">
      <Tabs
        :tabs="filterTabs"
        :activeIndex="activeFilterIndex"
        type="button"
        size="small"
        @change="handleFilterChange"
      />
    </view>
    
    <!-- 统计卡片 -->
    <view class="stats-section">
      <view class="stats-grid">
        <Card
          v-for="stat in statsData"
          :key="stat.key"
          :title="stat.value"
          :subtitle="stat.label"
          :type="stat.type"
          size="small"
          :clickable="true"
          @click="handleStatClick(stat)"
        >
          <template #extra>
            <text class="stat-icon">{{ stat.icon }}</text>
          </template>
        </Card>
      </view>
    </view>
    
    <!-- 牲畜列表 -->
    <view class="livestock-list">
      <Card
        v-for="animal in filteredLivestock"
        :key="animal.id"
        :clickable="true"
        class="livestock-card"
        @click="handleAnimalClick(animal)"
      >
        <view class="animal-info">
          <!-- 基本信息 -->
          <view class="animal-basic">
            <view class="animal-header">
              <text class="animal-id">{{ animal.id }}</text>
              <view class="animal-status" :class="getStatusClass(animal.status)">
                {{ getStatusText(animal.status) }}
              </view>
            </view>
            
            <view class="animal-details">
              <view class="detail-item">
                <text class="label">品种：</text>
                <text class="value">{{ animal.breed }}</text>
              </view>
              <view class="detail-item">
                <text class="label">性别：</text>
                <text class="value">{{ animal.gender === 'male' ? '公' : '母' }}</text>
              </view>
              <view class="detail-item">
                <text class="label">年龄：</text>
                <text class="value">{{ animal.age }}个月</text>
              </view>
              <view class="detail-item">
                <text class="label">体重：</text>
                <text class="value">{{ animal.weight }}kg</text>
              </view>
            </view>
          </view>
          
          <!-- 健康状态 -->
          <view class="animal-health">
            <view class="health-item">
              <text class="health-label">健康状态</text>
              <view class="health-status" :class="getHealthClass(animal.healthStatus)">
                {{ getHealthText(animal.healthStatus) }}
              </view>
            </view>
            
            <view class="health-item" v-if="animal.lastCheckDate">
              <text class="health-label">最后检查</text>
              <text class="health-value">{{ formatDate(animal.lastCheckDate) }}</text>
            </view>
          </view>
          
          <!-- 操作按钮 -->
          <view class="animal-actions">
            <button 
              class="action-btn primary"
              @click.stop="handleHealthCheck(animal)"
            >
              健康检查
            </button>
            <button 
              class="action-btn"
              @click.stop="handleFeedRecord(animal)"
            >
              喂养记录
            </button>
            <button 
              class="action-btn"
              @click.stop="handleMoreActions(animal)"
            >
              更多
            </button>
          </view>
        </view>
      </Card>
    </view>
    
    <!-- 空状态 -->
    <Empty
      v-if="filteredLivestock.length === 0"
      description="暂无牲畜数据"
      image="🐄"
    />
    
    <!-- 添加按钮 -->
    <view class="add-btn" @click="handleAddAnimal">
      <text class="add-icon">+</text>
    </view>
    
    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore">
      <button class="load-more-btn" @click="loadMore" :loading="loading">
        {{ loading ? '加载中...' : '加载更多' }}
      </button>
    </view>
  </view>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import Search from '@/common/components/search/search.vue'
import Tabs from '@/common/components/tabs/tabs.vue'
import Card from '@/common/components/card/card.vue'
import Empty from '@/common/components/empty/empty.vue'
import { farmingApi } from '@/common/api'
import { formatDate } from '@/common/utils/format'

export default {
  name: 'LivestockPage',
  components: {
    Search,
    Tabs,
    Card,
    Empty
  },
  setup() {
    // 响应式数据
    const searchKeyword = ref('')
    const activeFilterIndex = ref(0)
    const loading = ref(false)
    const hasMore = ref(true)
    const currentPage = ref(1)
    
    // 筛选标签
    const filterTabs = [
      { title: '全部', value: 'all' },
      { title: '健康', value: 'healthy' },
      { title: '生病', value: 'sick' },
      { title: '怀孕', value: 'pregnant' },
      { title: '幼崽', value: 'young' }
    ]
    
    // 牲畜数据
    const livestockData = ref([])
    
    // 统计数据
    const statsData = computed(() => [
      {
        key: 'total',
        label: '总数量',
        value: livestockData.value.length,
        icon: '🐄',
        type: 'primary'
      },
      {
        key: 'healthy',
        label: '健康',
        value: livestockData.value.filter(item => item.healthStatus === 'healthy').length,
        icon: '💚',
        type: 'success'
      },
      {
        key: 'sick',
        label: '生病',
        value: livestockData.value.filter(item => item.healthStatus === 'sick').length,
        icon: '🤒',
        type: 'danger'
      },
      {
        key: 'pregnant',
        label: '怀孕',
        value: livestockData.value.filter(item => item.status === 'pregnant').length,
        icon: '🤱',
        type: 'warning'
      }
    ])
    
    // 过滤后的牲畜数据
    const filteredLivestock = computed(() => {
      let result = livestockData.value
      
      // 关键词搜索
      if (searchKeyword.value) {
        result = result.filter(item => 
          item.id.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
          item.breed.toLowerCase().includes(searchKeyword.value.toLowerCase())
        )
      }
      
      // 状态筛选
      const filterValue = filterTabs[activeFilterIndex.value].value
      if (filterValue !== 'all') {
        result = result.filter(item => {
          switch (filterValue) {
            case 'healthy':
              return item.healthStatus === 'healthy'
            case 'sick':
              return item.healthStatus === 'sick'
            case 'pregnant':
              return item.status === 'pregnant'
            case 'young':
              return item.age < 12
            default:
              return true
          }
        })
      }
      
      return result
    })
    
    // 方法
    const loadLivestockData = async () => {
      try {
        loading.value = true
        const response = await farmingApi.getLivestockList({
          page: currentPage.value,
          pageSize: 20
        })
        
        if (currentPage.value === 1) {
          livestockData.value = response.data.list
        } else {
          livestockData.value.push(...response.data.list)
        }
        
        hasMore.value = response.data.hasMore
      } catch (error) {
        console.error('加载牲畜数据失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'error'
        })
      } finally {
        loading.value = false
      }
    }
    
    const handleSearch = (keyword) => {
      console.log('搜索:', keyword)
    }
    
    const handleSearchClear = () => {
      searchKeyword.value = ''
    }
    
    const handleFilterChange = (index) => {
      activeFilterIndex.value = index
    }
    
    const handleStatClick = (stat) => {
      // 根据统计项筛选
      const filterMap = {
        total: 0,
        healthy: 1,
        sick: 2,
        pregnant: 3
      }
      if (filterMap[stat.key] !== undefined) {
        activeFilterIndex.value = filterMap[stat.key]
      }
    }
    
    const handleAnimalClick = (animal) => {
      uni.navigateTo({
        url: `/pages/livestock/detail?id=${animal.id}`
      })
    }
    
    const handleHealthCheck = (animal) => {
      uni.navigateTo({
        url: `/pages/health/check?animalId=${animal.id}`
      })
    }
    
    const handleFeedRecord = (animal) => {
      uni.navigateTo({
        url: `/pages/feed/record?animalId=${animal.id}`
      })
    }
    
    const handleMoreActions = (animal) => {
      uni.showActionSheet({
        itemList: ['编辑信息', '疫苗记录', '繁殖记录', '删除'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              // 编辑信息
              uni.navigateTo({
                url: `/pages/livestock/edit?id=${animal.id}`
              })
              break
            case 1:
              // 疫苗记录
              uni.navigateTo({
                url: `/pages/vaccine/record?animalId=${animal.id}`
              })
              break
            case 2:
              // 繁殖记录
              uni.navigateTo({
                url: `/pages/breeding/record?animalId=${animal.id}`
              })
              break
            case 3:
              // 删除
              handleDeleteAnimal(animal)
              break
          }
        }
      })
    }
    
    const handleDeleteAnimal = (animal) => {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除牲畜 ${animal.id} 吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await farmingApi.deleteLivestock(animal.id)
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
              loadLivestockData()
            } catch (error) {
              uni.showToast({
                title: '删除失败',
                icon: 'error'
              })
            }
          }
        }
      })
    }
    
    const handleAddAnimal = () => {
      uni.navigateTo({
        url: '/pages/livestock/add'
      })
    }
    
    const loadMore = () => {
      if (loading.value || !hasMore.value) return
      currentPage.value++
      loadLivestockData()
    }
    
    const getStatusClass = (status) => {
      const classMap = {
        normal: 'status-normal',
        pregnant: 'status-pregnant',
        sick: 'status-sick',
        sold: 'status-sold'
      }
      return classMap[status] || 'status-normal'
    }
    
    const getStatusText = (status) => {
      const textMap = {
        normal: '正常',
        pregnant: '怀孕',
        sick: '生病',
        sold: '已售'
      }
      return textMap[status] || '正常'
    }
    
    const getHealthClass = (healthStatus) => {
      const classMap = {
        healthy: 'health-good',
        sick: 'health-bad',
        warning: 'health-warning'
      }
      return classMap[healthStatus] || 'health-good'
    }
    
    const getHealthText = (healthStatus) => {
      const textMap = {
        healthy: '健康',
        sick: '生病',
        warning: '注意'
      }
      return textMap[healthStatus] || '健康'
    }
    
    // 生命周期
    onMounted(() => {
      loadLivestockData()
    })
    
    return {
      searchKeyword,
      activeFilterIndex,
      loading,
      hasMore,
      filterTabs,
      livestockData,
      statsData,
      filteredLivestock,
      handleSearch,
      handleSearchClear,
      handleFilterChange,
      handleStatClick,
      handleAnimalClick,
      handleHealthCheck,
      handleFeedRecord,
      handleMoreActions,
      handleAddAnimal,
      loadMore,
      getStatusClass,
      getStatusText,
      getHealthClass,
      getHealthText,
      formatDate
    }
  }
}
</script>

<style lang="scss" scoped>
.livestock-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.search-section {
  padding: 32rpx;
  background-color: #fff;
  border-bottom: 2rpx solid #f0f0f0;
}

.filter-section {
  padding: 24rpx 32rpx;
  background-color: #fff;
  border-bottom: 2rpx solid #f0f0f0;
}

.stats-section {
  padding: 32rpx;
  background-color: #fff;
  margin-bottom: 16rpx;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16rpx;
}

.stat-icon {
  font-size: 32rpx;
}

.livestock-list {
  padding: 0 32rpx;
}

.livestock-card {
  margin-bottom: 24rpx;
}

.animal-info {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.animal-basic {
  .animal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16rpx;
  }
  
  .animal-id {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }
  
  .animal-status {
    padding: 8rpx 16rpx;
    border-radius: 20rpx;
    font-size: 24rpx;
    
    &.status-normal {
      background-color: #f6ffed;
      color: #52c41a;
    }
    
    &.status-pregnant {
      background-color: #fff7e6;
      color: #faad14;
    }
    
    &.status-sick {
      background-color: #fff2f0;
      color: #ff4d4f;
    }
    
    &.status-sold {
      background-color: #f0f0f0;
      color: #999;
    }
  }
  
  .animal-details {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12rpx;
  }
  
  .detail-item {
    display: flex;
    align-items: center;
    
    .label {
      font-size: 24rpx;
      color: #666;
      margin-right: 8rpx;
    }
    
    .value {
      font-size: 24rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

.animal-health {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  
  .health-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
  }
  
  .health-label {
    font-size: 22rpx;
    color: #666;
  }
  
  .health-status {
    padding: 6rpx 12rpx;
    border-radius: 16rpx;
    font-size: 22rpx;
    
    &.health-good {
      background-color: #f6ffed;
      color: #52c41a;
    }
    
    &.health-warning {
      background-color: #fff7e6;
      color: #faad14;
    }
    
    &.health-bad {
      background-color: #fff2f0;
      color: #ff4d4f;
    }
  }
  
  .health-value {
    font-size: 22rpx;
    color: #333;
  }
}

.animal-actions {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  flex: 1;
  height: 64rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 8rpx;
  background-color: #fff;
  font-size: 24rpx;
  color: #666;
  
  &.primary {
    border-color: #2e8b57;
    background-color: #2e8b57;
    color: #fff;
  }
  
  &:active {
    opacity: 0.8;
  }
}

.add-btn {
  position: fixed;
  right: 32rpx;
  bottom: 32rpx;
  width: 112rpx;
  height: 112rpx;
  background-color: #2e8b57;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(46, 139, 87, 0.3);
  z-index: 100;
  
  .add-icon {
    font-size: 48rpx;
    color: #fff;
    font-weight: bold;
  }
  
  &:active {
    transform: scale(0.95);
  }
}

.load-more {
  padding: 32rpx;
  text-align: center;
}

.load-more-btn {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 8rpx;
  background-color: #fff;
  font-size: 28rpx;
  color: #666;
  
  &:active {
    background-color: #f8f9fa;
  }
}
</style>