<template>
  <view class="mall-container">
    <!-- 顶部搜索框 -->
    <view class="search-header">
      <view class="search-box">
        <view class="search-input">
          <image class="search-icon" src="/static/icons/search.png" mode="aspectFit"></image>
          <input 
            class="input" 
            placeholder="搜索农资商品（如：化肥、除草剂）" 
            placeholder-style="color: #999;"
            v-model="searchKeyword"
            @confirm="handleSearch"
          />
        </view>
      </view>
    </view>

    <!-- 分类导航 -->
    <view class="category-nav">
      <scroll-view 
        class="nav-scroll" 
        scroll-x="true" 
        :show-scrollbar="false"
        :enhanced="true"
        :bounces="false"
        :scroll-with-animation="true"
        :scroll-left="scrollLeft"
      >
        <view class="nav-list">
          <view 
            class="nav-item"
            :class="{ active: activeCategory == item.dictValue }"
            v-for="item in dictData.mall_product_category" 
            :key="item.dictValue"
            @click="switchCategory(item.dictValue)"
          >
            {{ item.dictLabel }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 商品展示区 -->
	
<!--    <view class="goods-container">
		<scroll-view
			scroll-y 
			v-if="goodsList.length > 0"
		    style="height: 100vh;" 
		    @scrolltolower="loadMore">
			<view class="goods-grid">
			  <view 
			    class="goods-card"
			    v-for="item in filteredGoods" 
			    :key="item.id"
			    @click="navigateToDetail(item)"
			  >
			    <view class="goods-image">
			      <image :src="getImageUrl(item.swiperImages)" mode="aspectFill"></image>
			    </view>
			    <view class="goods-info">
			      <text class="goods-title">{{ item.title }}</text>
			      <text class="goods-desc">{{ item.description }}</text>
			      <view class="goods-price">
			        <text class="price">¥{{ item.price }}</text>
			        <!-- <text class="unit">/{{ item.unit }}</text> 
			      </view>
			      <view class="action-btn">了解更多</view>
			    </view>
			  </view>
			</view>
		</scroll-view>
        <view class="no-more-data" v-if="noMoreData && goodsList.length > 0">
          <text>没有更多数据了</text>
        </view>
    </view> -->
	<view class="container">
	  <!-- 有数据 -->
	  <scroll-view
	    v-if="goodsList.length > 0"
	    scroll-y
	    style="height: 100vh;"
	    @scrolltolower="loadMore"
	  >
	    <view class="goods-grid">
	      <view
	        class="goods-card"
	        v-for="item in filteredGoods"
	        :key="item.id"
	        @click="navigateToDetail(item)"
	      >
	        <view class="goods-image">
	          <image :src="getImageUrl(item.swiperImages)" mode="aspectFill"></image>
	        </view>
	        <view class="goods-info">
	          <text class="goods-title">{{ item.title }}</text>
	          <text class="goods-desc">{{ item.description }}</text>
	          <view class="goods-price">
	            <text class="price">¥{{ item.price }}</text>
				<text class="unit">{{ item.unit }}</text>
	          </view>
	          <view class="action-btn">了解更多</view>
	        </view>
	      </view>
	    </view>
	
	    
	  </scroll-view>
	<!-- 没有更多数据提示 -->
	<view class="no-more-data" v-if="noMoreData">
	  <text>没有更多数据了</text>
	</view>
	  <!-- 无数据 -->
	 <!-- <view v-else class="empty">
	    暂无数据
	  </view> -->
	</view>

  </view>
</template>

<script>
	import { getMallList } from '@/api/services/mall.js';
	import dictMixin from '@/utils/mixins/dictMixin';
	import api from "@/config/api.js";
export default {
  mixins: [dictMixin],
  data() {
    return {
	  dictTypeList: ['mall_product_category'],
      searchKeyword: '',
      activeCategory: -1,
      scrollLeft: 0,
      
      // 商品列表
      goodsList: [],
	  pageNum: 1,
	  pageSize: 10,
	  noMoreData: false,
	  isLoading: false,
	  isRefreshing: false,
    }
  },
  
  computed: {
    filteredGoods() {
      let goods = this.goodsList;
      
      // 按分类筛选
      if (this.activeCategory != -1) {
        goods = goods.filter(item => item.productCategory == this.activeCategory);
      }else{
		  goods = goods.filter(item => item.isRecommended == 1);
	  }
      
      // // 按搜索关键词筛选
      // if (this.searchKeyword.trim()) {
      //   const keyword = this.searchKeyword.trim().toLowerCase();
      //   goods = goods.filter(item => 
      //     item.title.toLowerCase().includes(keyword) || 
      //     item.description.toLowerCase().includes(keyword)
      //   );
      // }
      return goods;
    }
  },
  
  methods: {
	getImageUrl(item) {
	  	// 默认返回url或path
		if(item == null) return
		const imageUrls = item.split(',');
		console.log("imageUrls",imageUrls);
	    return  imageUrls[0];
	},
	loadMallData(keyword){
		this.isLoading = true;
		uni.showLoading({
			title: '加载中'
		});
		// 构建查询参数
		const params = {
		  pageNum: this.pageNum,
		  pageSize: this.pageSize,
		  // productCategory: this.activeCategory,
		  // recommend:1 // 查询推荐商品
		};
		if(keyword != null && keyword != ''){
			params.searchKeyword = keyword
		}
		
		// 分类逻辑
		  if (this.activeCategory == -1) {
			  // 默认场景：推荐查询
			  params.isRecommended = 1;
		    
		  } else {
		    // 分类查询：只带 productCategory
		    params.productCategory = this.activeCategory;
		  }
		
		getMallList(params).then(res => {
		  if (res.data.code === 200) {
		    const { rows, total } = res.data;
		    if (this.pageNum === 1) {
		      this.goodsList = rows;
		    } else {
		      this.goodsList = [...this.goodsList, ...rows];
		    }
		    console.log("this.goodsList.length >= total",this.goodsList.length);
		    console.log("this.goodsList.length >= total",this.goodsList.length >= total);
		    // 判断是否还有更多数据
		    this.noMoreData = this.goodsList.length >= total;
		    uni.hideLoading();
		    // 统计待完成商品数量
		    // this.countPendingTasks();
		  } else {
		    uni.showToast({
		      title: res.data.msg || '获取商品列表失败',
		      icon: 'none'
		    });
		  }
		}).catch(err => {
		  console.error('获取商品列表失败:', err);
		  uni.showToast({
		    title: '获取商品列表失败',
		    icon: 'none'
		  });
		}).finally(() => {
		  this.isLoading = false;
		  this.isRefreshing = false;
		});
	},
    // 上拉加载更多
    loadMore() {
      if (!this.isLoading && !this.noMoreData) {
        this.pageNum++;
        this.loadMallData();
      }
    },
	// 切换分类
    switchCategory(categoryId) {
		console.log("dfdssdf",categoryId);
      this.activeCategory = categoryId;
	  this.goodsList = [] // 切换时置空数据数组
      // 滚动到当前分类位置
	  this.loadMallData(this.searchKeyword.trim())
      this.$nextTick(() => {
        this.scrollToActiveCategory(categoryId);
      });
    },
    
    // 滚动到激活的分类  
    scrollToActiveCategory(categoryId) {
      const index = this.dictData.mall_product_category.findIndex(item => item.id == categoryId);
	  console.log("index",index);
      if (index > -1) {
        // 计算滚动位置，让当前分类居中显示
        const itemWidth = 120; // 每个分类项大约120rpx宽度
        const containerWidth = 750; // 屏幕宽度
        const scrollLeft = Math.max(0, index * itemWidth - containerWidth / 2 + itemWidth / 2);
        
        // 设置scroll-view的scrollLeft
        this.scrollLeft = scrollLeft;
      }
    },
    
    // 搜索处理
    handleSearch() {
      // if (!this.searchKeyword.trim()) {
      //   uni.showToast({
      //     title: '请输入搜索关键词',
      //     icon: 'none'
      //   });
      //   return;
      // }
	  const keyword = this.searchKeyword.trim().toLowerCase();
	  this.loadMallData(keyword)
    },
    
    // 导航到商品详情
    navigateToDetail(goods) {
      uni.navigateTo({
        url: `/pages/service/mall-detail?id=${goods.id}&title=${encodeURIComponent(goods.title)}`
      });
    }
  },
  // 页面加载时获取数据
  onLoad() {
    this.loadMallData();
  },
  
  onNavigationBarTitleText() {
    return '农资商城';
  }
}
</script>

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

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

.search-box {
  position: relative;
}

.search-input {
  display: flex;
  align-items: center;
  background-color: #f8f8f8;
  border-radius: 32rpx;
  padding: 16rpx 24rpx;
  
  .search-icon {
    width: 32rpx;
    height: 32rpx;
    margin-right: 16rpx;
  }
  
  .input {
    flex: 1;
    font-size: 28rpx;
    line-height: 1.5;
  }
}

.category-nav {
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-scroll {
  white-space: nowrap;
  height: 88rpx;
  width: 100%;
  overflow: hidden;
  -webkit-overflow-scrolling: touch; /* iOS滑动优化 */
  scroll-behavior: smooth; /* 平滑滚动 */
}

.nav-list {
  display: inline-flex;
  padding: 0 20rpx;
  height: 100%;
  align-items: center;
  min-width: 100%;
}

.nav-item {
  flex-shrink: 0;
  padding: 24rpx 32rpx;
  margin-right: 8rpx;
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
  position: relative;
  white-space: nowrap;
  transition: all 0.2s ease;
  border-radius: 8rpx;
  
  &:active {
    background-color: #f0f0f0;
    transform: scale(0.95);
  }
  
  &.active {
    color: #4CAF50;
    font-weight: bold;
    background-color: #f8fdf8;
  }
  
  &.active::after {
    content: '';
    position: absolute;
    bottom: 8rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 40rpx;
    height: 4rpx;
    background-color: #4CAF50;
    border-radius: 2rpx;
  }
}

.goods-container {
  padding: 20rpx;
}
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.goods-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.goods-card {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease;
  
  &:active {
    transform: scale(0.98);
  }
}

.goods-image {
  width: 100%;
  height: 240rpx;
  
  image {
    width: 100%;
    height: 100%;
  }
}

.goods-info {
  padding: 24rpx;
}

.goods-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.4;
  display: block;
  margin-bottom: 8rpx;
}

.goods-desc {
  font-size: 24rpx;
  color: #666;
  line-height: 1.4;
  display: block;
  margin-bottom: 16rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-price {
  display: flex;
  align-items: baseline;
  margin-bottom: 20rpx;
  
  .price {
    font-size: 32rpx;
    font-weight: bold;
    color: #4CAF50;
  }
  
  .unit {
    font-size: 24rpx;
    color: #999;
    margin-left: 4rpx;
  }
}

.action-btn {
  background-color: #4CAF50;
  color: #fff;
  text-align: center;
  padding: 16rpx 0;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: 500;
}
.no-more-data{
	text-align: center;
	padding: 30rpx 0;
}

.no-more-data text {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}
</style> 