<template>
  <view class="farm-list-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input"
          type="text"
          placeholder="搜索养殖场名称"
          v-model="searchKeyword"
          @input="onSearchInput"
        />
        <text class="clear-icon" v-if="searchKeyword" @tap="clearSearch">×</text>
      </view>
      <button class="filter-button" @tap="showFilter">
        <text class="filter-icon">🔽</text>
        <text>筛选</text>
      </button>
    </view>
    
    <!-- 统计卡片 -->
    <view class="stats-cards">
      <view class="stat-card">
        <text class="stat-number">{{ stats.totalFarms }}</text>
        <text class="stat-label">总养殖场</text>
      </view>
      <view class="stat-card">
        <text class="stat-number">{{ stats.activeFarms }}</text>
        <text class="stat-label">运营中</text>
      </view>
      <view class="stat-card">
        <text class="stat-number">{{ stats.totalAnimals }}</text>
        <text class="stat-label">总牲畜</text>
      </view>
    </view>
    
    <!-- 养殖场列表 -->
    <view class="farm-list">
      <view 
        class="farm-item" 
        v-for="farm in filteredFarms" 
        :key="farm.id"
        @tap="goToFarmDetail(farm.id)"
      >
        <!-- 养殖场图片 -->
        <view class="farm-image">
          <image 
            :src="farm.coverImage || '/static/images/farm-default.jpg'" 
            mode="aspectFill"
            class="image"
          ></image>
          <view class="status-badge" :class="farm.status">
            {{ getStatusText(farm.status) }}
          </view>
        </view>
        
        <!-- 养殖场信息 -->
        <view class="farm-info">
          <view class="farm-header">
            <text class="farm-name">{{ farm.name }}</text>
            <text class="farm-type">{{ farm.type }}</text>
          </view>
          
          <view class="farm-details">
            <view class="detail-item">
              <text class="detail-icon">📍</text>
              <text class="detail-text">{{ farm.location }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-icon">🐄</text>
              <text class="detail-text">{{ farm.animalCount }}头牲畜</text>
            </view>
            <view class="detail-item">
              <text class="detail-icon">📏</text>
              <text class="detail-text">{{ farm.area }}亩</text>
            </view>
          </view>
          
          <view class="farm-footer">
            <text class="update-time">更新于 {{ formatTime(farm.updatedAt) }}</text>
            <view class="action-buttons">
              <button class="action-btn edit-btn" @tap.stop="editFarm(farm)">编辑</button>
              <button class="action-btn view-btn" @tap.stop="goToFarmDetail(farm.id)">查看</button>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <empty 
      v-if="!loading && filteredFarms.length === 0"
      title="暂无养殖场"
      description="点击右下角按钮添加第一个养殖场"
      :show-action="true"
      action-text="添加养殖场"
      @action="addFarm"
    ></empty>
    
    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && !loading">
      <button class="load-more-btn" @tap="loadMore">加载更多</button>
    </view>
    
    <!-- 添加按钮 -->
    <view class="add-button" @tap="addFarm">
      <text class="add-icon">+</text>
    </view>
    
    <!-- 筛选弹窗 -->
    <modal 
      :show="showFilterModal" 
      title="筛选条件"
      @close="showFilterModal = false"
      @confirm="applyFilter"
    >
      <view class="filter-content">
        <!-- 状态筛选 -->
        <view class="filter-group">
          <text class="filter-title">运营状态</text>
          <radio-group @change="onStatusChange">
            <label class="filter-option" v-for="status in statusOptions" :key="status.value">
              <radio :value="status.value" :checked="filterData.status === status.value" />
              <text class="option-text">{{ status.label }}</text>
            </label>
          </radio-group>
        </view>
        
        <!-- 类型筛选 -->
        <view class="filter-group">
          <text class="filter-title">养殖类型</text>
          <checkbox-group @change="onTypeChange">
            <label class="filter-option" v-for="type in typeOptions" :key="type.value">
              <checkbox :value="type.value" :checked="filterData.types.includes(type.value)" />
              <text class="option-text">{{ type.label }}</text>
            </label>
          </checkbox-group>
        </view>
        
        <!-- 规模筛选 -->
        <view class="filter-group">
          <text class="filter-title">养殖规模</text>
          <view class="scale-filter">
            <input 
              class="scale-input"
              type="number"
              placeholder="最小数量"
              v-model="filterData.minAnimals"
            />
            <text class="scale-separator">-</text>
            <input 
              class="scale-input"
              type="number"
              placeholder="最大数量"
              v-model="filterData.maxAnimals"
            />
          </view>
        </view>
      </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: 'FarmList',
  
  components: {
    Empty,
    Modal,
    Loading
  },
  
  data() {
    return {
      searchKeyword: '',
      loading: false,
      hasMore: true,
      currentPage: 1,
      pageSize: 10,
      
      // 统计数据
      stats: {
        totalFarms: 0,
        activeFarms: 0,
        totalAnimals: 0
      },
      
      // 养殖场列表
      farms: [],
      
      // 筛选相关
      showFilterModal: false,
      filterData: {
        status: '',
        types: [],
        minAnimals: '',
        maxAnimals: ''
      },
      
      // 筛选选项
      statusOptions: [
        { label: '全部', value: '' },
        { label: '运营中', value: 'active' },
        { label: '暂停', value: 'paused' },
        { label: '维护中', value: 'maintenance' }
      ],
      
      typeOptions: [
        { label: '肉牛养殖', value: 'beef_cattle' },
        { label: '奶牛养殖', value: 'dairy_cattle' },
        { label: '羊养殖', value: 'sheep' },
        { label: '猪养殖', value: 'pig' },
        { label: '鸡养殖', value: 'chicken' }
      ]
    }
  },
  
  computed: {
    // 过滤后的养殖场列表
    filteredFarms() {
      let result = this.farms
      
      // 搜索过滤
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        result = result.filter(farm => 
          farm.name.toLowerCase().includes(keyword) ||
          farm.location.toLowerCase().includes(keyword)
        )
      }
      
      return result
    }
  },
  
  onLoad() {
    this.loadFarms()
    this.loadStats()
  },
  
  onPullDownRefresh() {
    this.refreshData()
  },
  
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  
  methods: {
    // 加载养殖场列表
    async loadFarms(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/farms',
          method: 'GET',
          data: params,
          loading: false
        })
        
        if (refresh) {
          this.farms = res.data.list
          this.currentPage = 1
        } else {
          this.farms = [...this.farms, ...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/stats',
          method: 'GET',
          loading: false
        })
        
        this.stats = res.data
        
      } catch (error) {
        console.error('加载统计数据失败：', error)
      }
    },
    
    // 刷新数据
    refreshData() {
      this.loadFarms(true)
      this.loadStats()
    },
    
    // 加载更多
    loadMore() {
      this.loadFarms()
    },
    
    // 搜索输入
    onSearchInput() {
      // 防抖处理
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.refreshData()
      }, 500)
    },
    
    // 清除搜索
    clearSearch() {
      this.searchKeyword = ''
      this.refreshData()
    },
    
    // 显示筛选
    showFilter() {
      this.showFilterModal = true
    },
    
    // 状态变更
    onStatusChange(e) {
      this.filterData.status = e.detail.value
    },
    
    // 类型变更
    onTypeChange(e) {
      this.filterData.types = e.detail.value
    },
    
    // 应用筛选
    applyFilter() {
      this.showFilterModal = false
      this.refreshData()
    },
    
    // 跳转到养殖场详情
    goToFarmDetail(farmId) {
      uni.navigateTo({
        url: `/pages/farm/detail?id=${farmId}`
      })
    },
    
    // 编辑养殖场
    editFarm(farm) {
      uni.navigateTo({
        url: `/pages/farm/edit?id=${farm.id}`
      })
    },
    
    // 添加养殖场
    addFarm() {
      uni.navigateTo({
        url: '/pages/farm/add'
      })
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        active: '运营中',
        paused: '暂停',
        maintenance: '维护中'
      }
      return statusMap[status] || '未知'
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return `${date.getMonth() + 1}月${date.getDate()}日`
      }
    }
  }
}
</script>

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

.search-bar {
  background: #ffffff;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  
  .search-input-wrapper {
    flex: 1;
    position: relative;
    background: #f8f8f8;
    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;
    }
    
    .clear-icon {
      font-size: 32rpx;
      color: #999999;
      padding: 10rpx;
    }
  }
  
  .filter-button {
    background: #2E8B57;
    color: #ffffff;
    border: none;
    border-radius: 12rpx;
    padding: 0 24rpx;
    height: 70rpx;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    gap: 8rpx;
    
    .filter-icon {
      font-size: 24rpx;
    }
    
    &::after {
      border: none;
    }
  }
}

.stats-cards {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
  
  .stat-card {
    flex: 1;
    background: #ffffff;
    border-radius: 16rpx;
    padding: 30rpx 20rpx;
    text-align: center;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    
    .stat-number {
      display: block;
      font-size: 48rpx;
      font-weight: bold;
      color: #2E8B57;
      margin-bottom: 8rpx;
    }
    
    .stat-label {
      font-size: 24rpx;
      color: #666666;
    }
  }
}

.farm-list {
  padding: 0 30rpx;
  
  .farm-item {
    background: #ffffff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    
    .farm-image {
      position: relative;
      height: 300rpx;
      
      .image {
        width: 100%;
        height: 100%;
      }
      
      .status-badge {
        position: absolute;
        top: 20rpx;
        right: 20rpx;
        padding: 8rpx 16rpx;
        border-radius: 20rpx;
        font-size: 24rpx;
        color: #ffffff;
        
        &.active {
          background: #4CAF50;
        }
        
        &.paused {
          background: #FF9800;
        }
        
        &.maintenance {
          background: #F44336;
        }
      }
    }
    
    .farm-info {
      padding: 30rpx;
      
      .farm-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        
        .farm-name {
          font-size: 36rpx;
          font-weight: 600;
          color: #333333;
        }
        
        .farm-type {
          font-size: 24rpx;
          color: #2E8B57;
          background: rgba(46, 139, 87, 0.1);
          padding: 6rpx 12rpx;
          border-radius: 8rpx;
        }
      }
      
      .farm-details {
        margin-bottom: 20rpx;
        
        .detail-item {
          display: flex;
          align-items: center;
          margin-bottom: 12rpx;
          
          .detail-icon {
            font-size: 24rpx;
            margin-right: 12rpx;
            width: 32rpx;
          }
          
          .detail-text {
            font-size: 28rpx;
            color: #666666;
          }
        }
      }
      
      .farm-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .update-time {
          font-size: 24rpx;
          color: #999999;
        }
        
        .action-buttons {
          display: flex;
          gap: 16rpx;
          
          .action-btn {
            border: none;
            border-radius: 8rpx;
            padding: 12rpx 20rpx;
            font-size: 24rpx;
            
            &.edit-btn {
              background: #f0f0f0;
              color: #666666;
            }
            
            &.view-btn {
              background: #2E8B57;
              color: #ffffff;
            }
            
            &::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;
    }
  }
}

.add-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;
  
  .add-icon {
    font-size: 60rpx;
    color: #ffffff;
    font-weight: 300;
  }
}

.filter-content {
  .filter-group {
    margin-bottom: 40rpx;
    
    .filter-title {
      display: block;
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
      margin-bottom: 20rpx;
    }
    
    .filter-option {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;
      
      .option-text {
        font-size: 28rpx;
        color: #666666;
        margin-left: 16rpx;
      }
    }
    
    .scale-filter {
      display: flex;
      align-items: center;
      gap: 20rpx;
      
      .scale-input {
        flex: 1;
        height: 80rpx;
        border: 2rpx solid #e0e0e0;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
      }
      
      .scale-separator {
        font-size: 28rpx;
        color: #999999;
      }
    }
  }
}
</style>