<template>
  <view class="animal-list-container">
    <!-- 顶部搜索和筛选 -->
    <view class="search-filter-bar">
      <view class="search-wrapper">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input"
          type="text"
          placeholder="搜索动物编号或名称"
          v-model="searchKeyword"
          @input="onSearchInput"
        />
      </view>
      <button class="filter-btn" @tap="showFilterModal = true">
        <text class="filter-icon">📊</text>
      </button>
    </view>
    
    <!-- 快速统计 -->
    <view class="quick-stats">
      <view class="stat-item">
        <text class="stat-number">{{ stats.total }}</text>
        <text class="stat-label">总数量</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ stats.healthy }}</text>
        <text class="stat-label">健康</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ stats.sick }}</text>
        <text class="stat-label">患病</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ stats.pregnant }}</text>
        <text class="stat-label">怀孕</text>
      </view>
    </view>
    
    <!-- 动物列表 -->
    <view class="animal-list">
      <view 
        class="animal-card" 
        v-for="animal in filteredAnimals" 
        :key="animal.id"
        @tap="goToAnimalDetail(animal.id)"
      >
        <!-- 动物头像 -->
        <view class="animal-avatar">
          <image 
            :src="animal.avatar || getDefaultAvatar(animal.species)" 
            mode="aspectFill"
            class="avatar-image"
          ></image>
          <view class="health-indicator" :class="animal.healthStatus"></view>
        </view>
        
        <!-- 动物信息 -->
        <view class="animal-info">
          <view class="animal-header">
            <text class="animal-name">{{ animal.name || animal.code }}</text>
            <view class="animal-tags">
              <text class="tag species-tag">{{ getSpeciesText(animal.species) }}</text>
              <text class="tag gender-tag" :class="animal.gender">{{ getGenderText(animal.gender) }}</text>
            </view>
          </view>
          
          <view class="animal-details">
            <view class="detail-row">
              <text class="detail-label">编号：</text>
              <text class="detail-value">{{ animal.code }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">年龄：</text>
              <text class="detail-value">{{ calculateAge(animal.birthDate) }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">体重：</text>
              <text class="detail-value">{{ animal.weight }}kg</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">健康状态：</text>
              <text class="detail-value" :class="animal.healthStatus">{{ getHealthStatusText(animal.healthStatus) }}</text>
            </view>
          </view>
          
          <view class="animal-footer">
            <text class="update-time">{{ formatTime(animal.updatedAt) }}</text>
            <view class="quick-actions">
              <button class="action-btn health-btn" @tap.stop="recordHealth(animal)">
                <text class="btn-icon">🏥</text>
              </button>
              <button class="action-btn feed-btn" @tap.stop="recordFeed(animal)">
                <text class="btn-icon">🌾</text>
              </button>
              <button class="action-btn more-btn" @tap.stop="showMoreActions(animal)">
                <text class="btn-icon">⋯</text>
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <empty 
      v-if="!loading && filteredAnimals.length === 0"
      title="暂无动物档案"
      description="点击右下角按钮添加第一个动物档案"
      :show-action="true"
      action-text="添加动物"
      @action="addAnimal"
    ></empty>
    
    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && !loading">
      <button class="load-more-btn" @tap="loadMore">加载更多</button>
    </view>
    
    <!-- 添加按钮 -->
    <view class="fab-button" @tap="addAnimal">
      <text class="fab-icon">+</text>
    </view>
    
    <!-- 筛选弹窗 -->
    <modal 
      :show="showFilterModal" 
      title="筛选条件"
      @close="showFilterModal = false"
      @confirm="applyFilter"
    >
      <view class="filter-content">
        <!-- 物种筛选 -->
        <view class="filter-section">
          <text class="section-title">物种</text>
          <view class="filter-options">
            <view 
              class="filter-chip" 
              :class="{ active: filterData.species.includes(species.value) }"
              v-for="species in speciesOptions" 
              :key="species.value"
              @tap="toggleSpecies(species.value)"
            >
              <text class="chip-text">{{ species.label }}</text>
            </view>
          </view>
        </view>
        
        <!-- 健康状态筛选 -->
        <view class="filter-section">
          <text class="section-title">健康状态</text>
          <view class="filter-options">
            <view 
              class="filter-chip" 
              :class="{ active: filterData.healthStatus.includes(status.value) }"
              v-for="status in healthStatusOptions" 
              :key="status.value"
              @tap="toggleHealthStatus(status.value)"
            >
              <text class="chip-text">{{ status.label }}</text>
            </view>
          </view>
        </view>
        
        <!-- 年龄范围 -->
        <view class="filter-section">
          <text class="section-title">年龄范围</text>
          <view class="age-range">
            <input 
              class="age-input"
              type="number"
              placeholder="最小年龄"
              v-model="filterData.minAge"
            />
            <text class="range-separator">-</text>
            <input 
              class="age-input"
              type="number"
              placeholder="最大年龄"
              v-model="filterData.maxAge"
            />
          </view>
        </view>
      </view>
    </modal>
    
    <!-- 更多操作弹窗 -->
    <modal 
      :show="showActionsModal" 
      title="更多操作"
      :show-footer="false"
      @close="showActionsModal = false"
    >
      <view class="actions-content">
        <button class="action-item" @tap="editAnimal">
          <text class="action-icon">✏️</text>
          <text class="action-text">编辑信息</text>
        </button>
        <button class="action-item" @tap="viewHistory">
          <text class="action-icon">📋</text>
          <text class="action-text">查看记录</text>
        </button>
        <button class="action-item" @tap="generateQR">
          <text class="action-icon">📱</text>
          <text class="action-text">生成二维码</text>
        </button>
        <button class="action-item danger" @tap="deleteAnimal">
          <text class="action-icon">🗑️</text>
          <text class="action-text">删除档案</text>
        </button>
      </view>
    </modal>
    
    <!-- 加载组件 -->
    <loading :show="loading" text="加载中..."></loading>
  </view>
</template>

<script>
import Empty from '@/common/components/empty/empty.vue'
import Modal from '@/common/components/modal/modal.vue'
import Loading from '@/common/components/loading/loading.vue'

export default {
  name: 'AnimalList',
  
  components: {
    Empty,
    Modal,
    Loading
  },
  
  data() {
    return {
      searchKeyword: '',
      loading: false,
      hasMore: true,
      currentPage: 1,
      pageSize: 20,
      
      // 统计数据
      stats: {
        total: 0,
        healthy: 0,
        sick: 0,
        pregnant: 0
      },
      
      // 动物列表
      animals: [],
      
      // 筛选相关
      showFilterModal: false,
      filterData: {
        species: [],
        healthStatus: [],
        minAge: '',
        maxAge: ''
      },
      
      // 更多操作
      showActionsModal: false,
      selectedAnimal: null,
      
      // 筛选选项
      speciesOptions: [
        { label: '牛', value: 'cattle' },
        { label: '羊', value: 'sheep' },
        { label: '猪', value: 'pig' },
        { label: '鸡', value: 'chicken' }
      ],
      
      healthStatusOptions: [
        { label: '健康', value: 'healthy' },
        { label: '患病', value: 'sick' },
        { label: '治疗中', value: 'treating' },
        { label: '康复中', value: 'recovering' }
      ]
    }
  },
  
  computed: {
    // 过滤后的动物列表
    filteredAnimals() {
      let result = this.animals
      
      // 搜索过滤
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        result = result.filter(animal => 
          (animal.name && animal.name.toLowerCase().includes(keyword)) ||
          animal.code.toLowerCase().includes(keyword)
        )
      }
      
      return result
    }
  },
  
  onLoad() {
    this.loadAnimals()
    this.loadStats()
  },
  
  onPullDownRefresh() {
    this.refreshData()
  },
  
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  
  methods: {
    // 加载动物列表
    async loadAnimals(refresh = false) {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const params = {
          page: refresh ? 1 : this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchKeyword,
          ...this.filterData
        }
        
        const res = await this.$request({
          url: '/farming/animals',
          method: 'GET',
          data: params,
          loading: false
        })
        
        if (refresh) {
          this.animals = res.data.list
          this.currentPage = 1
        } else {
          this.animals = [...this.animals, ...res.data.list]
        }
        
        this.hasMore = res.data.hasMore
        this.currentPage++
        
      } catch (error) {
        console.error('加载动物列表失败：', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        
        if (refresh) {
          uni.stopPullDownRefresh()
        }
      }
    },
    
    // 加载统计数据
    async loadStats() {
      try {
        const res = await this.$request({
          url: '/farming/animals/stats',
          method: 'GET',
          loading: false
        })
        
        this.stats = res.data
        
      } catch (error) {
        console.error('加载统计数据失败：', error)
      }
    },
    
    // 刷新数据
    refreshData() {
      this.loadAnimals(true)
      this.loadStats()
    },
    
    // 加载更多
    loadMore() {
      this.loadAnimals()
    },
    
    // 搜索输入
    onSearchInput() {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.refreshData()
      }, 500)
    },
    
    // 切换物种筛选
    toggleSpecies(species) {
      const index = this.filterData.species.indexOf(species)
      if (index > -1) {
        this.filterData.species.splice(index, 1)
      } else {
        this.filterData.species.push(species)
      }
    },
    
    // 切换健康状态筛选
    toggleHealthStatus(status) {
      const index = this.filterData.healthStatus.indexOf(status)
      if (index > -1) {
        this.filterData.healthStatus.splice(index, 1)
      } else {
        this.filterData.healthStatus.push(status)
      }
    },
    
    // 应用筛选
    applyFilter() {
      this.showFilterModal = false
      this.refreshData()
    },
    
    // 跳转到动物详情
    goToAnimalDetail(animalId) {
      uni.navigateTo({
        url: `/pages/animal/detail?id=${animalId}`
      })
    },
    
    // 添加动物
    addAnimal() {
      uni.navigateTo({
        url: '/pages/animal/add'
      })
    },
    
    // 记录健康信息
    recordHealth(animal) {
      uni.navigateTo({
        url: `/pages/health/record?animalId=${animal.id}`
      })
    },
    
    // 记录喂养信息
    recordFeed(animal) {
      uni.navigateTo({
        url: `/pages/feed/record?animalId=${animal.id}`
      })
    },
    
    // 显示更多操作
    showMoreActions(animal) {
      this.selectedAnimal = animal
      this.showActionsModal = true
    },
    
    // 编辑动物
    editAnimal() {
      this.showActionsModal = false
      uni.navigateTo({
        url: `/pages/animal/edit?id=${this.selectedAnimal.id}`
      })
    },
    
    // 查看历史记录
    viewHistory() {
      this.showActionsModal = false
      uni.navigateTo({
        url: `/pages/animal/history?id=${this.selectedAnimal.id}`
      })
    },
    
    // 生成二维码
    generateQR() {
      this.showActionsModal = false
      uni.navigateTo({
        url: `/pages/animal/qrcode?id=${this.selectedAnimal.id}`
      })
    },
    
    // 删除动物
    async deleteAnimal() {
      this.showActionsModal = false
      
      const result = await uni.showModal({
        title: '确认删除',
        content: '删除后无法恢复，确定要删除这个动物档案吗？',
        confirmColor: '#ff4444'
      })
      
      if (result.confirm) {
        try {
          await this.$request({
            url: `/farming/animals/${this.selectedAnimal.id}`,
            method: 'DELETE'
          })
          
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
          
          this.refreshData()
          
        } catch (error) {
          console.error('删除动物失败：', error)
        }
      }
    },
    
    // 获取默认头像
    getDefaultAvatar(species) {
      const avatarMap = {
        cattle: '/static/images/cattle-avatar.png',
        sheep: '/static/images/sheep-avatar.png',
        pig: '/static/images/pig-avatar.png',
        chicken: '/static/images/chicken-avatar.png'
      }
      return avatarMap[species] || '/static/images/animal-default.png'
    },
    
    // 获取物种文本
    getSpeciesText(species) {
      const speciesMap = {
        cattle: '牛',
        sheep: '羊',
        pig: '猪',
        chicken: '鸡'
      }
      return speciesMap[species] || '未知'
    },
    
    // 获取性别文本
    getGenderText(gender) {
      const genderMap = {
        male: '公',
        female: '母'
      }
      return genderMap[gender] || '未知'
    },
    
    // 获取健康状态文本
    getHealthStatusText(status) {
      const statusMap = {
        healthy: '健康',
        sick: '患病',
        treating: '治疗中',
        recovering: '康复中'
      }
      return statusMap[status] || '未知'
    },
    
    // 计算年龄
    calculateAge(birthDate) {
      if (!birthDate) return '未知'
      
      const birth = new Date(birthDate)
      const now = new Date()
      const diffTime = Math.abs(now - birth)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      
      if (diffDays < 30) {
        return `${diffDays}天`
      } else if (diffDays < 365) {
        return `${Math.floor(diffDays / 30)}个月`
      } else {
        return `${Math.floor(diffDays / 365)}岁`
      }
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
.animal-list-container {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 120rpx;
}

.search-filter-bar {
  background: #ffffff;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  
  .search-wrapper {
    flex: 1;
    background: #f5f5f5;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    
    .search-icon {
      font-size: 28rpx;
      color: #999999;
      margin-right: 16rpx;
    }
    
    .search-input {
      flex: 1;
      height: 70rpx;
      font-size: 28rpx;
      color: #333333;
    }
  }
  
  .filter-btn {
    width: 70rpx;
    height: 70rpx;
    background: #2E8B57;
    border: none;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .filter-icon {
      font-size: 28rpx;
      color: #ffffff;
    }
    
    &::after {
      border: none;
    }
  }
}

.quick-stats {
  display: flex;
  padding: 20rpx 30rpx;
  gap: 15rpx;
  
  .stat-item {
    flex: 1;
    background: #ffffff;
    border-radius: 12rpx;
    padding: 20rpx 15rpx;
    text-align: center;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    
    .stat-number {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #2E8B57;
      margin-bottom: 6rpx;
    }
    
    .stat-label {
      font-size: 22rpx;
      color: #666666;
    }
  }
}

.animal-list {
  padding: 0 30rpx;
  
  .animal-card {
    background: #ffffff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
    display: flex;
    gap: 24rpx;
    
    .animal-avatar {
      position: relative;
      
      .avatar-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 12rpx;
      }
      
      .health-indicator {
        position: absolute;
        bottom: -6rpx;
        right: -6rpx;
        width: 24rpx;
        height: 24rpx;
        border-radius: 50%;
        border: 3rpx solid #ffffff;
        
        &.healthy {
          background: #4CAF50;
        }
        
        &.sick {
          background: #F44336;
        }
        
        &.treating {
          background: #FF9800;
        }
        
        &.recovering {
          background: #2196F3;
        }
      }
    }
    
    .animal-info {
      flex: 1;
      
      .animal-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16rpx;
        
        .animal-name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
        }
        
        .animal-tags {
          display: flex;
          gap: 8rpx;
          
          .tag {
            font-size: 20rpx;
            padding: 4rpx 8rpx;
            border-radius: 6rpx;
            
            &.species-tag {
              background: rgba(46, 139, 87, 0.1);
              color: #2E8B57;
            }
            
            &.gender-tag {
              &.male {
                background: rgba(33, 150, 243, 0.1);
                color: #2196F3;
              }
              
              &.female {
                background: rgba(233, 30, 99, 0.1);
                color: #E91E63;
              }
            }
          }
        }
      }
      
      .animal-details {
        margin-bottom: 16rpx;
        
        .detail-row {
          display: flex;
          margin-bottom: 8rpx;
          
          .detail-label {
            font-size: 24rpx;
            color: #999999;
            width: 120rpx;
          }
          
          .detail-value {
            font-size: 24rpx;
            color: #666666;
            
            &.healthy {
              color: #4CAF50;
            }
            
            &.sick {
              color: #F44336;
            }
            
            &.treating {
              color: #FF9800;
            }
            
            &.recovering {
              color: #2196F3;
            }
          }
        }
      }
      
      .animal-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .update-time {
          font-size: 22rpx;
          color: #999999;
        }
        
        .quick-actions {
          display: flex;
          gap: 12rpx;
          
          .action-btn {
            width: 60rpx;
            height: 60rpx;
            border: none;
            border-radius: 8rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .btn-icon {
              font-size: 24rpx;
            }
            
            &.health-btn {
              background: rgba(244, 67, 54, 0.1);
              
              .btn-icon {
                color: #F44336;
              }
            }
            
            &.feed-btn {
              background: rgba(255, 152, 0, 0.1);
              
              .btn-icon {
                color: #FF9800;
              }
            }
            
            &.more-btn {
              background: rgba(158, 158, 158, 0.1);
              
              .btn-icon {
                color: #9E9E9E;
              }
            }
            
            &::after {
              border: none;
            }
          }
        }
      }
    }
  }
}

.load-more {
  padding: 30rpx;
  text-align: center;
  
  .load-more-btn {
    background: #ffffff;
    color: #2E8B57;
    border: 2rpx solid #2E8B57;
    border-radius: 12rpx;
    padding: 20rpx 40rpx;
    font-size: 28rpx;
    
    &::after {
      border: none;
    }
  }
}

.fab-button {
  position: fixed;
  bottom: 40rpx;
  right: 40rpx;
  width: 120rpx;
  height: 120rpx;
  background: linear-gradient(135deg, #2E8B57, #3CB371);
  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;
  
  .fab-icon {
    font-size: 60rpx;
    color: #ffffff;
    font-weight: 300;
  }
}

.filter-content {
  .filter-section {
    margin-bottom: 40rpx;
    
    .section-title {
      display: block;
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
      margin-bottom: 20rpx;
    }
    
    .filter-options {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx;
      
      .filter-chip {
        padding: 16rpx 24rpx;
        border: 2rpx solid #e0e0e0;
        border-radius: 20rpx;
        background: #ffffff;
        
        .chip-text {
          font-size: 28rpx;
          color: #666666;
        }
        
        &.active {
          border-color: #2E8B57;
          background: rgba(46, 139, 87, 0.1);
          
          .chip-text {
            color: #2E8B57;
          }
        }
      }
    }
    
    .age-range {
      display: flex;
      align-items: center;
      gap: 20rpx;
      
      .age-input {
        flex: 1;
        height: 80rpx;
        border: 2rpx solid #e0e0e0;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
      }
      
      .range-separator {
        font-size: 28rpx;
        color: #999999;
      }
    }
  }
}

.actions-content {
  .action-item {
    width: 100%;
    height: 100rpx;
    background: transparent;
    border: none;
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    margin-bottom: 10rpx;
    border-radius: 8rpx;
    
    .action-icon {
      font-size: 32rpx;
      margin-right: 20rpx;
      width: 40rpx;
    }
    
    .action-text {
      font-size: 32rpx;
      color: #333333;
    }
    
    &.danger {
      .action-icon,
      .action-text {
        color: #F44336;
      }
    }
    
    &:hover {
      background: #f5f5f5;
    }
    
    &::after {
      border: none;
    }
  }
}
</style>