<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="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>
  </view>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getMallList } from '@/api/services/mall.js'
import { useDict } from '@/utils/composables/useDict'

const { dictData } = useDict(['mall_product_category'])

const searchKeyword = ref('')
const activeCategory = ref(-1)
const scrollLeft = ref(0)
const goodsList = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const noMoreData = ref(false)
const isLoading = ref(false)
const isRefreshing = ref(false)

const filteredGoods = computed(() => {
  let goods = goodsList.value
  
  if (activeCategory.value != -1) {
    goods = goods.filter(item => item.productCategory == activeCategory.value)
  } else {
    goods = goods.filter(item => item.isRecommended == 1)
  }
  
  return goods
})

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

const loadMallData = (keyword) => {
  isLoading.value = true
  uni.showLoading({
    title: '加载中'
  })
  
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    status: 1
  }
  
  if(keyword != null && keyword != ''){
    params.searchKeyword = keyword
  }
  
  if (activeCategory.value == -1) {
    params.isRecommended = 1
  } else {
    params.productCategory = activeCategory.value
  }
  
  getMallList(params).then(res => {
    if (res.data.code === 200) {
      const { rows, total } = res.data
      if (pageNum.value === 1) {
        goodsList.value = rows
      } else {
        goodsList.value = [...goodsList.value, ...rows]
      }
      
      noMoreData.value = goodsList.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
  })
}

const loadMore = () => {
  if (!isLoading.value && !noMoreData.value) {
    pageNum.value++
    loadMallData()
  }
}

const switchCategory = (categoryId) => {
  activeCategory.value = categoryId
  goodsList.value = []
  loadMallData(searchKeyword.value.trim())
  nextTick(() => {
    scrollToActiveCategory(categoryId)
  })
}

const scrollToActiveCategory = (categoryId) => {
  const index = dictData.value.mall_product_category.findIndex(item => item.id == categoryId)
  if (index > -1) {
    const itemWidth = 120
    const containerWidth = 750
    const scrollLeftValue = Math.max(0, index * itemWidth - containerWidth / 2 + itemWidth / 2)
    scrollLeft.value = scrollLeftValue
  }
}

const handleSearch = () => {
  const keyword = searchKeyword.value.trim().toLowerCase()
  loadMallData(keyword)
}

const navigateToDetail = (goods) => {
  uni.navigateTo({
    url: `/pages/service/mall-detail?id=${goods.id}&title=${encodeURIComponent(goods.title)}`
  })
}

onLoad(() => {
  loadMallData()
})
</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;
  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>
