<template>
  <view class="container">
    <!-- 顶部搜索和筛选 -->
    <view class="header-section">
      <view class="search-bar">
        <view class="search-input">
          <uni-icons type="search" size="20" color="#999"></uni-icons>
          <input 
            type="text" 
            placeholder="搜索牛只品种、价格等" 
            v-model="searchKeyword"
            @confirm="handleSearch"
          />
        </view>
      </view>
      
      <view class="filter-bar">
        <view class="filter-item" @click="showSortPopup = true">
          <text class="filter-text">{{ sortText }}</text>
          <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
        </view>
        <view class="filter-item" @click="showFilterPopup = true">
          <text class="filter-text">筛选</text>
          <uni-icons type="tune" size="16" color="#666"></uni-icons>
        </view>
        <view class="filter-item" @click="toggleViewMode">
          <uni-icons :type="viewMode === 'grid' ? 'list' : 'grid'" size="16" color="#666"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 牛只列表 -->
    <view class="cattle-list" :class="viewMode">
      <view 
        class="cattle-item" 
        v-for="cattle in cattleList" 
        :key="cattle.id"
        @click="navigateToDetail(cattle.id)"
      >
        <image :src="cattle.image" class="cattle-image" mode="aspectFill"></image>
        <view class="cattle-info">
          <view class="cattle-header">
            <text class="cattle-breed">{{ cattle.breed }}</text>
            <view class="cattle-status" :class="cattle.status">
              {{ getStatusText(cattle.status) }}
            </view>
          </view>
          
          <view class="cattle-details">
            <view class="detail-row">
              <text class="detail-label">年龄：</text>
              <text class="detail-value">{{ cattle.age }}月龄</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">重量：</text>
              <text class="detail-value">{{ cattle.weight }}kg</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">性别：</text>
              <text class="detail-value">{{ cattle.gender }}</text>
            </view>
          </view>
          
          <view class="cattle-price">
            <text class="price-label">价格：</text>
            <text class="price-value">¥{{ cattle.price }}</text>
          </view>
          
          <view class="cattle-footer">
            <view class="location-info">
              <uni-icons type="location" size="12" color="#999"></uni-icons>
              <text class="location-text">{{ cattle.location }}</text>
            </view>
            <text class="publish-time">{{ formatTime(cattle.publishTime) }}</text>
          </view>
          
          <view class="cattle-actions" v-if="viewMode === 'list'">
            <button class="action-btn contact" @click.stop="contactSeller(cattle)">
              联系卖家
            </button>
            <button class="action-btn favorite" @click.stop="toggleFavorite(cattle)">
              {{ cattle.isFavorite ? '已收藏' : '收藏' }}
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <uni-load-more :status="loadStatus" :content-text="loadText"></uni-load-more>

    <!-- 排序弹窗 -->
    <uni-popup ref="sortPopup" type="bottom" :mask-click="true">
      <view class="sort-popup">
        <view class="popup-header">
          <text class="popup-title">排序方式</text>
        </view>
        <view class="sort-options">
          <view 
            class="sort-option" 
            :class="{ active: currentSort === option.value }"
            v-for="option in sortOptions" 
            :key="option.value"
            @click="selectSort(option.value)"
          >
            <text class="option-text">{{ option.label }}</text>
            <uni-icons 
              v-if="currentSort === option.value" 
              type="checkmarkempty" 
              size="20" 
              color="#007AFF"
            ></uni-icons>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 筛选弹窗 -->
    <uni-popup ref="filterPopup" type="bottom" :mask-click="false">
      <view class="filter-popup">
        <view class="popup-header">
          <text class="popup-title">筛选条件</text>
          <text class="popup-close" @click="showFilterPopup = false">关闭</text>
        </view>
        <scroll-view class="filter-content" scroll-y="true">
          <!-- 品种筛选 -->
          <view class="filter-group">
            <text class="filter-label">品种</text>
            <view class="filter-options">
              <text 
                class="filter-option" 
                :class="{ active: filterParams.breed === breed }"
                v-for="breed in breedOptions" 
                :key="breed"
                @click="selectBreed(breed)"
              >
                {{ breed }}
              </text>
            </view>
          </view>
          
          <!-- 价格筛选 -->
          <view class="filter-group">
            <text class="filter-label">价格范围</text>
            <view class="price-range">
              <input 
                type="number" 
                placeholder="最低价" 
                v-model="filterParams.priceMin"
                class="price-input"
              />
              <text class="price-separator">-</text>
              <input 
                type="number" 
                placeholder="最高价" 
                v-model="filterParams.priceMax"
                class="price-input"
              />
            </view>
          </view>
          
          <!-- 年龄筛选 -->
          <view class="filter-group">
            <text class="filter-label">年龄</text>
            <view class="filter-options">
              <text 
                class="filter-option" 
                :class="{ active: filterParams.age === age }"
                v-for="age in ageOptions" 
                :key="age"
                @click="selectAge(age)"
              >
                {{ age }}
              </text>
            </view>
          </view>
          
          <!-- 重量筛选 -->
          <view class="filter-group">
            <text class="filter-label">重量</text>
            <view class="filter-options">
              <text 
                class="filter-option" 
                :class="{ active: filterParams.weight === weight }"
                v-for="weight in weightOptions" 
                :key="weight"
                @click="selectWeight(weight)"
              >
                {{ weight }}
              </text>
            </view>
          </view>
          
          <!-- 地区筛选 -->
          <view class="filter-group">
            <text class="filter-label">地区</text>
            <view class="filter-options">
              <text 
                class="filter-option" 
                :class="{ active: filterParams.location === location }"
                v-for="location in locationOptions" 
                :key="location"
                @click="selectLocation(location)"
              >
                {{ location }}
              </text>
            </view>
          </view>
        </scroll-view>
        <view class="popup-footer">
          <button class="reset-btn" @click="resetFilter">重置</button>
          <button class="confirm-btn" @click="applyFilter">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRequest } from '@/common/utils/request'
import { showToast, showLoading, hideLoading } from '@/common/utils/uni-helper'

export default {
  name: 'MarketPage',
  setup() {
    const request = useRequest()
    
    // 响应式数据
    const searchKeyword = ref('')
    const activeCategory = ref(0)
    const productList = ref([])
    const loading = ref(false)
    const refreshing = ref(false)
    const hasMore = ref(true)
    const currentPage = ref(1)
    const showFilter = ref(false)
    
    // 分类数据
    const categories = ref([
      { id: 0, name: '全部' },
      { id: 1, name: '肉牛' },
      { id: 2, name: '奶牛' },
      { id: 3, name: '种牛' },
      { id: 4, name: '小牛' }
    ])
    
    // 筛选数据
    const filterData = reactive({
      minPrice: '',
      maxPrice: '',
      breeds: [],
      region: null
    })
    
    // 品种选项
    const breedOptions = ref([
      { id: 1, name: '西门塔尔' },
      { id: 2, name: '安格斯' },
      { id: 3, name: '夏洛莱' },
      { id: 4, name: '利木赞' },
      { id: 5, name: '荷斯坦' }
    ])
    
    // 地区选项
    const regionOptions = ref([
      { id: 1, name: '北京市' },
      { id: 2, name: '上海市' },
      { id: 3, name: '广东省' },
      { id: 4, name: '山东省' },
      { id: 5, name: '河南省' }
    ])
    
    // 获取商品列表
    const getProductList = async (isRefresh = false) => {
      if (loading.value && !isRefresh) return
      
      try {
        loading.value = true
        
        const params = {
          page: isRefresh ? 1 : currentPage.value,
          pageSize: 10,
          keyword: searchKeyword.value,
          category: activeCategory.value,
          ...filterData
        }
        
        const response = await request.get('/api/cattle/list', params)
        
        if (isRefresh) {
          productList.value = response.data.list
          currentPage.value = 1
        } else {
          productList.value.push(...response.data.list)
        }
        
        hasMore.value = response.data.hasMore
        currentPage.value++
        
      } catch (error) {
        showToast('获取数据失败')
      } finally {
        loading.value = false
        refreshing.value = false
      }
    }
    
    // 搜索
    const onSearch = () => {
      currentPage.value = 1
      getProductList(true)
    }
    
    // 选择分类
    const selectCategory = (categoryId) => {
      activeCategory.value = categoryId
      currentPage.value = 1
      getProductList(true)
    }
    
    // 下拉刷新
    const onRefresh = () => {
      refreshing.value = true
      getProductList(true)
    }
    
    // 加载更多
    const loadMore = () => {
      if (hasMore.value && !loading.value) {
        getProductList()
      }
    }
    
    // 切换品种选择
    const toggleBreed = (breedId) => {
      const index = filterData.breeds.indexOf(breedId)
      if (index > -1) {
        filterData.breeds.splice(index, 1)
      } else {
        filterData.breeds.push(breedId)
      }
    }
    
    // 地区选择
    const onRegionChange = (e) => {
      filterData.region = e.detail.value
    }
    
    // 重置筛选
    const resetFilter = () => {
      filterData.minPrice = ''
      filterData.maxPrice = ''
      filterData.breeds = []
      filterData.region = null
    }
    
    // 应用筛选
    const applyFilter = () => {
      showFilter.value = false
      currentPage.value = 1
      getProductList(true)
    }
    
    // 跳转到详情页
    const goToDetail = (productId) => {
      uni.navigateTo({
        url: `/pages/detail/detail?id=${productId}`
      })
    }
    
    // 跳转到发布页
    const goToPublish = () => {
      uni.navigateTo({
        url: '/pages/publish/publish'
      })
    }
    
    // 页面加载
    onMounted(() => {
      getProductList(true)
    })
    
    return {
      searchKeyword,
      activeCategory,
      productList,
      loading,
      refreshing,
      hasMore,
      showFilter,
      categories,
      filterData,
      breedOptions,
      regionOptions,
      onSearch,
      selectCategory,
      onRefresh,
      loadMore,
      toggleBreed,
      onRegionChange,
      resetFilter,
      applyFilter,
      goToDetail,
      goToPublish
    }
  }
}
</script>

<style lang="scss" scoped>
.market-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $bg-secondary;
}

.search-bar {
  display: flex;
  align-items: center;
  padding: $spacing-md;
  background-color: $white;
  gap: $spacing-sm;
  
  .search-input {
    flex: 1;
    display: flex;
    align-items: center;
    background-color: $bg-light;
    border-radius: $border-radius-lg;
    padding: $spacing-sm $spacing-md;
    gap: $spacing-sm;
    
    input {
      flex: 1;
      font-size: $font-size-base;
    }
  }
  
  .filter-btn {
    padding: $spacing-sm;
    background-color: $primary-color;
    border-radius: $border-radius-md;
    color: $white;
  }
}

.category-tabs {
  background-color: $white;
  white-space: nowrap;
  padding: $spacing-sm $spacing-md;
  
  .category-item {
    display: inline-block;
    padding: $spacing-sm $spacing-md;
    margin-right: $spacing-sm;
    background-color: $bg-light;
    border-radius: $border-radius-full;
    font-size: $font-size-sm;
    color: $text-secondary;
    
    &.active {
      background-color: $primary-color;
      color: $white;
    }
  }
}

.product-list {
  flex: 1;
  padding: $spacing-md;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: $spacing-md;
}

.product-card {
  background-color: $white;
  border-radius: $border-radius-lg;
  overflow: hidden;
  box-shadow: $shadow-sm;
  
  .product-image {
    position: relative;
    height: 120px;
    
    image {
      width: 100%;
      height: 100%;
    }
    
    .hot-tag {
      position: absolute;
      top: $spacing-sm;
      left: $spacing-sm;
      background-color: $error-color;
      color: $white;
      padding: 2px $spacing-sm;
      border-radius: $border-radius-sm;
      font-size: $font-size-xs;
    }
  }
  
  .product-info {
    padding: $spacing-md;
    
    .product-title {
      font-size: $font-size-base;
      font-weight: $font-weight-medium;
      color: $text-primary;
      @include text-ellipsis(1);
      margin-bottom: $spacing-xs;
    }
    
    .product-desc {
      font-size: $font-size-sm;
      color: $text-secondary;
      @include text-ellipsis(2);
      margin-bottom: $spacing-sm;
    }
    
    .product-tags {
      margin-bottom: $spacing-sm;
      
      .tag {
        display: inline-block;
        background-color: $bg-light;
        color: $text-muted;
        padding: 2px $spacing-xs;
        border-radius: $border-radius-sm;
        font-size: $font-size-xs;
        margin-right: $spacing-xs;
      }
    }
    
    .product-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .price {
        .currency {
          font-size: $font-size-sm;
          color: $error-color;
        }
        
        .amount {
          font-size: $font-size-lg;
          font-weight: $font-weight-bold;
          color: $error-color;
        }
        
        .unit {
          font-size: $font-size-sm;
          color: $text-muted;
        }
      }
      
      .location {
        display: flex;
        align-items: center;
        gap: 2px;
        font-size: $font-size-xs;
        color: $text-muted;
      }
    }
  }
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: $spacing-lg;
  gap: $spacing-sm;
  color: $text-muted;
  font-size: $font-size-sm;
}

.no-more {
  text-align: center;
  padding: $spacing-lg;
  color: $text-muted;
  font-size: $font-size-sm;
}

.filter-popup {
  background-color: $white;
  border-radius: $border-radius-lg $border-radius-lg 0 0;
  max-height: 70vh;
  
  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: $spacing-lg;
    border-bottom: 1px solid $border-color;
    
    .filter-actions {
      display: flex;
      gap: $spacing-lg;
      
      text {
        color: $primary-color;
        font-size: $font-size-base;
      }
    }
  }
  
  .filter-content {
    padding: $spacing-lg;
    max-height: 50vh;
    overflow-y: auto;
  }
  
  .filter-section {
    margin-bottom: $spacing-xl;
    
    .section-title {
      font-size: $font-size-base;
      font-weight: $font-weight-medium;
      color: $text-primary;
      margin-bottom: $spacing-md;
    }
    
    .price-range {
      display: flex;
      align-items: center;
      gap: $spacing-sm;
      
      .price-input {
        flex: 1;
        padding: $spacing-sm;
        border: 1px solid $border-color;
        border-radius: $border-radius-md;
        text-align: center;
      }
      
      .separator {
        color: $text-muted;
      }
    }
    
    .breed-options {
      display: flex;
      flex-wrap: wrap;
      gap: $spacing-sm;
      
      .breed-item {
        padding: $spacing-sm $spacing-md;
        background-color: $bg-light;
        border-radius: $border-radius-full;
        font-size: $font-size-sm;
        color: $text-secondary;
        
        &.active {
          background-color: $primary-color;
          color: $white;
        }
      }
    }
    
    .picker-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: $spacing-md;
      background-color: $bg-light;
      border-radius: $border-radius-md;
      color: $text-primary;
    }
  }
}

.fab-button {
  position: fixed;
  right: $spacing-lg;
  bottom: 100px;
  width: 56px;
  height: 56px;
  background-color: $primary-color;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: $shadow-lg;
  z-index: 999;
}
</style>