<template>
	<view class="sales-container">
		<!-- 顶部Tab标签页 -->
		<view class="tab-header">
			<view class="tab-list">
				<view class="tab-item" :class="{ active: activeTab === 'all' }" @click="switchTab('all')">
					<text class="tab-text">全部</text>
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'sale' }" @click="switchTab('sale')">
					<text class="tab-text">出售信息</text>
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'purchase' }" @click="switchTab('purchase')">
					<text class="tab-text">收购信息</text>
				</view>
			</view>
			<view class="tab-indicator" :style="{ left: getIndicatorPosition() }"></view>
		</view>

		<!-- 搜索筛选 -->
		<view class="search-section">
			<view class="search-box">
				<image class="search-icon" src="/static/icons/search.png" mode="aspectFit"></image>
				<input class="search-input" placeholder="搜索农产品信息" placeholder-style="color: #999;"
					v-model="searchKeyword" @confirm="handleSearch" />
			</view>
		</view>

		<!-- 全部农产品信息列表 -->
		<scroll-view v-if="allInfoList.length > 0" scroll-y style="height: 100vh;" @scrolltolower="loadMore">
			<view class="content-container">
				<view class="info-list">
					<view class="info-card" v-for="item in filteredAllInfo" :key="`${item.type}_${item.id}`"
						@click="navigateToDetail(item)">
						<view class="card-content">
							<!-- 封面图片 -->
							<view class="info-image">
								<image :src="getImageUrl(item.imageUrl)" mode="aspectFill"></image>
							</view>

							<!-- 信息内容 -->
							<view class="info-content">
								<!-- 类型标签和标题 -->
								<view class="info-header">
									<view class="type-tag" :class="item.type === 0 ? 'sale' : 'purchase'">
										{{ item.type === 0 ? '出售' : '收购' }}
									</view>
									<view class="info-title"> {{ item.title }}
										¥{{ item.price || 0 }}/{{ getUnitLabel(item.unit) }}</view>
								</view>

								<!-- 简要说明 -->
								<view class="info-desc">{{ item.description }}</view>

								<!-- 底部信息 -->
								<view class="info-footer">
									<view class="publish-info">
										<text class="publisher">{{ item.contactName }}</text>
										<text class="publish-time">{{ item.publishTime }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 没有更多数据提示 -->
				<view class="no-more-data" v-if="noMoreData">
					<text>没有更多数据了</text>
				</view>
			</view>
		</scroll-view>

		<!-- 浮动发布按钮 -->
		<view class="floating-btn" @click="navigateToMyPublish">
			<view class="btn-icon">+</view>
			<text class="btn-text">我的发布</text>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getProductInfoList } from '@/api/services/productInfo.js'
import { useDict } from '@/utils/composables/useDict'

// 使用字典
const { dictData } = useDict(['agricultural_unit'])

const activeTab = ref('all')
const searchKeyword = ref('')
const pageNum = ref(1)
const pageSize = ref(10)
const noMoreData = ref(false)
const isLoading = ref(false)
const isRefreshing = ref(false)
const allInfoList = ref([])

const filteredAllInfo = computed(() => {
  let list = allInfoList.value
  
  // 按类型筛选
  if (activeTab.value === 'sale') {
    list = list.filter(item => item.type === 0)
  } else if (activeTab.value === 'purchase') {
    list = list.filter(item => item.type === 1)
  }
  
  return list
})

// 页面加载时获取数据
onMounted(() => {
  loadProductInfo()
})

// 上拉加载更多
const loadMore = () => {
  if (!isLoading.value && !noMoreData.value) {
    pageNum.value++
    loadProductInfo()
  }
}

const getImageUrl = (item) => {
  if (item == null) return
  const imageUrls = item.split(',')
  return imageUrls[0]
}

const getUnitLabel = (value) => {
  const unit = dictData.agricultural_unit?.find(u => u.dictValue == value)
  return unit ? unit.dictLabel : ''
}

const loadProductInfo = (keyword) => {
  isLoading.value = true
  uni.showLoading({
    title: '加载中'
  })
  
  // 构建查询参数
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    status: 2 // 查询 已上架
  }
  
  if (keyword != null && keyword != '') {
    params.searchKeyword = keyword
  }
  
  // 分类逻辑
  if (activeTab.value !== 'all') {
    params.type = activeTab.value === 'sale' ? 0 : 1
  }
  
  getProductInfoList(params).then(res => {
    if (res.data.code === 200) {
      const { rows, total } = res.data
      if (pageNum.value === 1) {
        allInfoList.value = rows
      } else {
        allInfoList.value = [...allInfoList.value, ...rows]
      }
      // 判断是否还有更多数据
      noMoreData.value = allInfoList.value.length >= total
      uni.hideLoading()
    } else {
      uni.showToast({
        title: res.data.msg || '获取农品列表失败',
        icon: 'none'
      })
    }
  }).catch(err => {
    console.error('获取农品列表失败:', err)
    uni.showToast({
      title: '获取农品列表失败',
      icon: 'none'
    })
  }).finally(() => {
    isLoading.value = false
    isRefreshing.value = false
  })
}

// 切换Tab标签页
const switchTab = (tab) => {
  activeTab.value = tab
  allInfoList.value = [] // 切换时置空数据数组
  pageNum.value = 1 // 重置页码
  // 滚动到当前分类位置
  loadProductInfo(searchKeyword.value.trim())
}

// 获取指示器位置
const getIndicatorPosition = () => {
  const positions = {
    'all': '0%',
    'sale': '33.33%',
    'purchase': '66.66%'
  }
  return positions[activeTab.value] || '0%'
}

// 搜索处理
const handleSearch = () => {
  const keyword = searchKeyword.value.trim().toLowerCase()
  pageNum.value = 1 // 重置页码
  allInfoList.value = [] // 清空列表
  loadProductInfo(keyword)
}

// 导航到详情页
const navigateToDetail = (item) => {
  uni.navigateTo({
    url: `/pages/service/sales-detail?id=${item.id}&type=${item.type}&title=${encodeURIComponent(item.title)}`
  })
}

// 导航到我的发布页面
const navigateToMyPublish = () => {
  uni.navigateTo({
    url: '/pages/service/my-publish'
  })
}
</script>

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

	.tab-header {
		background-color: #fff;
		position: relative;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.tab-list {
		display: flex;
		align-items: center;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 32rpx 0;
		position: relative;

		.tab-text {
			font-size: 30rpx;
			color: #666;
			font-weight: 500;
			transition: color 0.3s ease;
		}

		&.active .tab-text {
			color: #4CAF50;
			font-weight: bold;
		}
	}

	.tab-indicator {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 33.33%;
		height: 4rpx;
		background-color: #4CAF50;
		transition: left 0.3s ease;
	}



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

	.search-box {
		flex: 1;
		display: flex;
		align-items: center;
		background-color: #f8f8f8;
		border-radius: 32rpx;
		padding: 16rpx 24rpx;
	}

	.search-icon {
		width: 32rpx;
		height: 32rpx;
		margin-right: 16rpx;
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		line-height: 1.5;
	}

	.filter-btn {
		display: flex;
		align-items: center;
		padding: 16rpx 24rpx;
		background-color: #f8f8f8;
		border-radius: 24rpx;
		font-size: 28rpx;
		color: #666;

		.filter-icon {
			margin-left: 8rpx;
			font-size: 20rpx;
		}
	}

	.category-tags {
		background-color: #fff;
		border-bottom: 1rpx solid #f0f0f0;
	}

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

	.tags-list {
		display: inline-flex;
		padding: 0 20rpx;
	}

	.tag-item {
		flex-shrink: 0;
		padding: 20rpx 32rpx;
		margin-right: 8rpx;
		font-size: 28rpx;
		color: #666;
		border-radius: 32rpx;
		transition: all 0.2s ease;

		&.active {
			color: #4CAF50;
			background-color: #f0fdf4;
			font-weight: bold;
		}
	}

	// 内容容器
	.content-container {
		padding: 20rpx;
	}

	.info-list {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	// 统一信息卡片样式
	.info-card {
		background-color: #fff;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		transition: transform 0.2s ease;

		&:active {
			transform: scale(0.98);
		}
	}

	.card-content {
		display: flex;
		padding: 20rpx;
		gap: 20rpx;
	}

	// 封面图片
	.info-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
		overflow: hidden;
		flex-shrink: 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	// 信息内容
	.info-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	// 信息头部
	.info-header {
		display: flex;
		align-items: flex-start;
		margin-bottom: 12rpx;
		gap: 12rpx;
	}

	.type-tag {
		padding: 6rpx 12rpx;
		border-radius: 12rpx;
		font-size: 20rpx;
		font-weight: bold;
		flex-shrink: 0;

		&.sale {
			background-color: #e8f5e8;
			color: #4CAF50;
		}

		&.purchase {
			background-color: #e6f7ff;
			color: #1890ff;
		}
	}

	.info-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		flex: 1;
		line-height: 1.4;
	}

	// 简要说明
	.info-desc {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 16rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		line-height: 1.4;
	}

	// 底部信息
	.info-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.publish-info {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.publisher {
		font-size: 24rpx;
		color: #4CAF50;
		font-weight: bold;
	}

	.publish-time {
		font-size: 24rpx;
		color: #999;
	}

	// 浮动发布按钮
	.floating-btn {
		position: fixed;
		bottom: 120rpx;
		right: 30rpx;
		width: 140rpx;
		height: 140rpx;
		background-color: #4CAF50;
		border-radius: 70rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		box-shadow: 0 8rpx 24rpx rgba(76, 175, 80, 0.3);
		z-index: 1000;
		transition: transform 0.2s ease;

		&:active {
			transform: scale(0.95);
		}

		.btn-icon {
			font-size: 56rpx;
			color: #fff;
			font-weight: 300;
			line-height: 1;
			margin-bottom: 2rpx;
		}

		.btn-text {
			font-size: 22rpx;
			color: #fff;
			font-weight: bold;
		}
	}
	.no-more-data{
		text-align: center;
		padding: 30rpx 0;
	}
	
	.no-more-data text {
	  font-size: 24rpx;
	  color: #999;
	  margin-left: 10rpx;
	}
</style>