<template>
  <view class="container">
    <!-- 顶部搜索栏 -->
    <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 class="filter-btn" @click="showFilter = true">
        <uni-icons type="tune" size="20" color="#007AFF"></uni-icons>
      </view>
    </view>

    <!-- 分类导航 -->
    <view class="category-nav">
      <scroll-view scroll-x="true" class="category-scroll">
        <view class="category-list">
          <view 
            class="category-item" 
            :class="{ active: activeCategory === item.id }"
            v-for="item in categories" 
            :key="item.id"
            @click="selectCategory(item.id)"
          >
            {{ item.name }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 轮播图 -->
    <view class="banner-section">
      <swiper 
        class="banner-swiper" 
        indicator-dots="true" 
        autoplay="true" 
        interval="3000"
        duration="500"
      >
        <swiper-item v-for="(banner, index) in banners" :key="index">
          <image :src="banner.image" class="banner-image" mode="aspectFill"></image>
        </swiper-item>
      </swiper>
    </view>

    <!-- 快捷功能 -->
    <view class="quick-actions">
      <view class="action-item" @click="navigateTo('/pages/publish/publish')">
        <view class="action-icon publish">
          <uni-icons type="plus" size="24" color="#fff"></uni-icons>
        </view>
        <text class="action-text">发布交易</text>
      </view>
      <view class="action-item" @click="navigateTo('/pages/market/market')">
        <view class="action-icon market">
          <uni-icons type="shop" size="24" color="#fff"></uni-icons>
        </view>
        <text class="action-text">交易市场</text>
      </view>
      <view class="action-item" @click="navigateTo('/pages/orders/orders')">
        <view class="action-icon orders">
          <uni-icons type="list" size="24" color="#fff"></uni-icons>
        </view>
        <text class="action-text">我的订单</text>
      </view>
      <view class="action-item" @click="navigateTo('/pages/profile/profile')">
        <view class="action-icon profile">
          <uni-icons type="person" size="24" color="#fff"></uni-icons>
        </view>
        <text class="action-text">个人中心</text>
      </view>
    </view>

    <!-- 推荐交易 -->
    <view class="recommended-section">
      <view class="section-header">
        <text class="section-title">推荐交易</text>
        <text class="more-btn" @click="navigateTo('/pages/market/market')">更多 ></text>
      </view>
      <view class="cattle-list">
        <view 
          class="cattle-item" 
          v-for="cattle in recommendedCattle" 
          :key="cattle.id"
          @click="navigateTo(`/pages/detail/detail?id=${cattle.id}`)"
        >
          <image :src="cattle.image" class="cattle-image" mode="aspectFill"></image>
          <view class="cattle-info">
            <text class="cattle-breed">{{ cattle.breed }}</text>
            <text class="cattle-age">{{ cattle.age }}月龄</text>
            <text class="cattle-weight">{{ cattle.weight }}kg</text>
            <view class="cattle-price">
              <text class="price-label">价格：</text>
              <text class="price-value">¥{{ cattle.price }}</text>
            </view>
            <view class="cattle-location">
              <uni-icons type="location" size="12" color="#999"></uni-icons>
              <text class="location-text">{{ cattle.location }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 筛选弹窗 -->
    <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="showFilter = false">关闭</text>
        </view>
        <view class="filter-content">
          <!-- 品种筛选 -->
          <view class="filter-group">
            <text class="filter-label">品种</text>
            <view class="filter-options">
              <text 
                class="filter-option" 
                :class="{ active: selectedBreed === breed }"
                v-for="breed in breeds" 
                :key="breed"
                @click="selectedBreed = breed"
              >
                {{ breed }}
              </text>
            </view>
          </view>
          
          <!-- 价格筛选 -->
          <view class="filter-group">
            <text class="filter-label">价格范围</text>
            <view class="price-range">
              <input 
                type="number" 
                placeholder="最低价" 
                v-model="priceRange.min"
                class="price-input"
              />
              <text class="price-separator">-</text>
              <input 
                type="number" 
                placeholder="最高价" 
                v-model="priceRange.max"
                class="price-input"
              />
            </view>
          </view>
          
          <!-- 年龄筛选 -->
          <view class="filter-group">
            <text class="filter-label">年龄</text>
            <view class="filter-options">
              <text 
                class="filter-option" 
                :class="{ active: selectedAge === age }"
                v-for="age in ageRanges" 
                :key="age"
                @click="selectedAge = age"
              >
                {{ age }}
              </text>
            </view>
          </view>
        </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>
export default {
  name: 'Index',
  
  data() {
    return {
      bannerList: [
        {
          id: 1,
          title: '优质肉牛交易',
          description: '精选优质肉牛，品质保证',
          image: '/static/images/banner1.jpg',
          url: '/pages/market/list?category=meat'
        },
        {
          id: 2,
          title: '奶牛专区',
          description: '高产奶牛，产奶量高',
          image: '/static/images/banner2.jpg',
          url: '/pages/market/list?category=dairy'
        },
        {
          id: 3,
          title: '种牛繁育',
          description: '优良种牛，繁育首选',
          image: '/static/images/banner3.jpg',
          url: '/pages/market/list?category=breeding'
        }
      ],
      categoryList: [
        {
          id: 1,
          name: '肉牛',
          icon: '/static/images/category-meat.png',
          type: 'meat'
        },
        {
          id: 2,
          name: '奶牛',
          icon: '/static/images/category-dairy.png',
          type: 'dairy'
        },
        {
          id: 3,
          name: '种牛',
          icon: '/static/images/category-breeding.png',
          type: 'breeding'
        },
        {
          id: 4,
          name: '小牛',
          icon: '/static/images/category-calf.png',
          type: 'calf'
        }
      ],
      hotList: [],
      latestList: [],
      loadStatus: 'loading',
      loadText: {
        contentdown: '上拉显示更多',
        contentrefresh: '正在加载...',
        contentnomore: '没有更多数据了'
      }
    }
  },
  
  onLoad() {
    this.initPage()
  },
  
  onShow() {
    this.refreshData()
  },
  
  onPullDownRefresh() {
    this.refreshData().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  
  methods: {
    // 初始化页面
    async initPage() {
      try {
        await this.loadData()
      } catch (error) {
        console.error('初始化页面失败：', error)
      }
    },
    
    // 加载数据
    async loadData() {
      this.loadStatus = 'loading'
      
      try {
        await Promise.all([
          this.loadHotProducts(),
          this.loadLatestProducts()
        ])
        
        this.loadStatus = 'noMore'
      } catch (error) {
        console.error('加载数据失败：', error)
        this.loadStatus = 'noMore'
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        })
      }
    },
    
    // 刷新数据
    async refreshData() {
      return this.loadData()
    },
    
    // 加载热门商品
    async loadHotProducts() {
      try {
        const res = await this.$request({
          url: '/products/hot',
          method: 'GET',
          data: {
            limit: 10
          }
        })
        
        if (res.data && res.data.list) {
          this.hotList = res.data.list
        }
      } catch (error) {
        console.error('加载热门商品失败：', error)
      }
    },
    
    // 加载最新商品
    async loadLatestProducts() {
      try {
        const res = await this.$request({
          url: '/products/latest',
          method: 'GET',
          data: {
            limit: 10
          }
        })
        
        if (res.data && res.data.list) {
          this.latestList = res.data.list
        }
      } catch (error) {
        console.error('加载最新商品失败：', error)
      }
    },
    
    // 轮播图点击
    onBannerClick(banner) {
      if (banner.url) {
        uni.navigateTo({
          url: banner.url
        })
      }
    },
    
    // 分类点击
    onCategoryClick(category) {
      uni.navigateTo({
        url: `/pages/market/list?category=${category.type}`
      })
    },
    
    // 搜索点击
    onSearchClick() {
      uni.navigateTo({
        url: '/pages/search/index'
      })
    },
    
    // 商品点击
    onProductClick(product) {
      uni.navigateTo({
        url: `/pages/market/detail?id=${product.id}`
      })
    },
    
    // 查看更多
    onViewMore(type) {
      let url = '/pages/market/list'
      if (type === 'hot') {
        url += '?sort=hot'
      } else if (type === 'latest') {
        url += '?sort=latest'
      }
      
      uni.switchTab({
        url: '/pages/market/list'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 轮播图 */
.banner-section {
  margin-bottom: 30rpx;
}

.banner-swiper {
  height: 400rpx;
  border-radius: 0 0 20rpx 20rpx;
  overflow: hidden;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.banner-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.6));
  padding: 40rpx 30rpx 30rpx;
  
  .banner-title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #ffffff;
    margin-bottom: 10rpx;
  }
  
  .banner-desc {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.9);
  }
}

/* 分类导航 */
.category-section {
  margin: 0 30rpx 30rpx;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
}

.category-item {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  
  .category-icon {
    width: 60rpx;
    height: 60rpx;
    margin-bottom: 16rpx;
    
    .icon-image {
      width: 100%;
      height: 100%;
    }
  }
  
  .category-name {
    font-size: 28rpx;
    color: #333333;
    text-align: center;
  }
}

/* 搜索栏 */
.search-section {
  margin: 0 30rpx 30rpx;
}

.search-bar {
  background: #ffffff;
  border-radius: 50rpx;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  
  .search-icon {
    font-size: 32rpx;
    margin-right: 20rpx;
  }
  
  .search-placeholder {
    flex: 1;
    font-size: 28rpx;
    color: #999999;
  }
}

/* 推荐区域 */
.recommend-section {
  margin-bottom: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx 20rpx;
  
  .section-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
  }
  
  .more-text {
    font-size: 28rpx;
    color: #FF6B35;
  }
}

.recommend-scroll {
  white-space: nowrap;
}

.recommend-list {
  display: flex;
  padding: 0 30rpx;
  gap: 20rpx;
}

.recommend-item {
  width: 280rpx;
  background: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
  
  .product-image {
    width: 100%;
    height: 200rpx;
  }
  
  .product-info {
    padding: 20rpx;
    
    .product-title {
      display: block;
      font-size: 28rpx;
      font-weight: 500;
      color: #333333;
      margin-bottom: 10rpx;
      @extend .ellipsis;
    }
    
    .product-price {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #FF6B35;
      margin-bottom: 10rpx;
    }
    
    .product-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8rpx;
      
      .tag {
        background: #f0f0f0;
        color: #666666;
        font-size: 22rpx;
        padding: 4rpx 8rpx;
        border-radius: 8rpx;
      }
    }
  }
}

/* 最新发布 */
.latest-section {
  margin: 0 30rpx 30rpx;
}

.latest-list {
  background: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.latest-item {
  display: flex;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
  
  .item-image {
    width: 160rpx;
    height: 120rpx;
    border-radius: 12rpx;
    margin-right: 20rpx;
    flex-shrink: 0;
  }
  
  .item-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    
    .item-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333333;
      margin-bottom: 8rpx;
      @extend .ellipsis;
    }
    
    .item-desc {
      font-size: 28rpx;
      color: #666666;
      margin-bottom: 8rpx;
      @extend .ellipsis;
    }
    
    .item-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .item-price {
        font-size: 32rpx;
        font-weight: bold;
        color: #FF6B35;
      }
      
      .item-location {
        font-size: 24rpx;
        color: #999999;
      }
      
      .item-time {
        font-size: 24rpx;
        color: #999999;
      }
    }
  }
}
</style>