<template>
  <view class="search-page">
    <!-- 搜索输入框 -->
    <u-input placeholder="请输入搜索的服务" prefixIcon="search" v-model="value" class="rounded-input"
      @confirm="handleSearch"></u-input>
    <!-- 历史记录 -->
    <view class="history-search">
      <view class="history-search-title">历史搜索</view>
      <view>
        <image src="@/static/img/delete-bin-6-fill@1x.png" mode="widthFix" class="delete-icon"></image>
        清空
      </view>
    </view>
    <!-- 瀑布流展示区域 -->
    <view class="home-ranking">
      <ServIces :leftList="leftList" :rightList="rightList" :ValueZoneSwiper="ValueZoneSwiper" v-if="userType == 1">
      </ServIces>
    </view>

    <!-- 加载更多组件 -->
    <up-loadmore style="margin-top: 40rpx" :status="loadmoreInfo.status" :loadmoreText="loadmoreInfo.loadingText"
      :loadingText="loadmoreInfo.loadmoreText" :nomoreText="loadmoreInfo.nomoreText" @loadmore="handleLoadmore"
      v-if="userType == 1" />
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { onShow, onReachBottom } from '@dcloudio/uni-app'
import { volTierName } from '@/api/volunteerDetailsApi/details.js'
import RankingList from '@/pages/common/rankingList/index.vue'
import ServIces from '@/components/Services/services.vue'
import store from '@/store'

// 搜索关键词
const value = ref('')
// 瀑布流左右列表数据
const rightList = ref([])
const leftList = ref([])
const ValueZoneSwiper = ref([''])
// 用户类型
const userType = uni.getStorageSync('userType') || 1; //读取本地存储
// 添加搜索定时器引用
const searchTimer = ref(null);

// 分页参数配置
const pages = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  serviceCategory: '',
  businessTierName: '' // 添加搜索关键词参数
})

// 加载更多状态配置
const loadmoreInfo = ref({
  status: 'loadmore',
  loadingText: '努力加载中...',
  loadmoreText: '点击加载更多~',
  nomoreText: '已经到底啦～',
})

/**
 * 处理搜索确认事件
 */
const handleSearch = () => {
  console.log('触发搜索:', value.value); // 添加日志
  // 重置页码
  pages.value.current = 1
  // 执行搜索
  getList()
}

/**
 * 加载更多数据
 */
async function handleLoadmore(e) {
  if (
    pages.value.current < Math.ceil(pages.value.total / pages.value.pageSize)
  ) {
    pages.value.current += 1
    loadmoreInfo.value.status = 'loading'
    await getList()
  } else {
    loadmoreInfo.value.status = 'nomore'
  }
}

/**
 * 获取列表数据
 * 支持分页和关键词搜索
 */
const getList = async () => {
  try {
    loadmoreInfo.value.status = 'loading'

    // 获取地址信息
    const address = store.state.user.addressInfo
    const { cityCode, latitude, longitude } = address

    // 构建请求参数 - 根据API接口定义调整参数
    const params = {
      pageNum: pages.value.current,
      pageSize: pages.value.pageSize,
      serviceCategory: pages.value.serviceCategory || '',
      businessManagementId: 0,
      // API接口使用的模糊搜索参数
      businessTierName: value.value, // 业务名称搜索参数

      // 地址相关参数
      provinceName: cityCode.data[0], // 省
      provinceCode: cityCode.code[0],
      cityName: cityCode.data[1], // 市
      cityCode: cityCode.code[1],
      districtName: cityCode.data[2],
      districtCode: cityCode.code[2],
      latitude,
      longitude,
    }

    console.log('搜索参数:', params); // 添加日志查看参数

    // 调用API获取数据
    const res = await volTierName(params)

    if (!res || !res.rows) {
      return
    }

    // 如果是第一页，先清空数据
    if (pages.value.current === 1) {
      leftList.value = []
      rightList.value = []
    }

    // 每次都追加新数据 - 左右瀑布流交替分配
    res.rows.forEach((item, index) => {
      index % 2 !== 0 ? rightList.value.push(item) : leftList.value.push(item)
    })

    // 更新分页和加载状态
    pages.value.total = res.total
    if (pages.value.current >= Math.ceil(res.total / pages.value.pageSize)) {
      loadmoreInfo.value.status = 'nomore'
    } else {
      loadmoreInfo.value.status = 'loadmore'
    }
  } catch (error) {
    // 错误处理
    leftList.value = []
    rightList.value = []
    loadmoreInfo.value.status = 'loadmore'
    pages.value.total = 0
    console.error('Error fetching data:', error)
  }
}

/**
 * 页面滚动到底部触发加载更多
 */
onReachBottom(() => {
  if (
    pages.value.current < Math.ceil(pages.value.total / pages.value.pageSize)
  ) {
    pages.value.current = pages.value.current + 1
    loadmoreInfo.value.status = 'nomore'
    getList()
  }
})

/**
 * 组件挂载时获取初始数据
 */
onMounted(() => {
  // 获取路由参数
  const query = uni.getLaunchOptionsSync().query || {}
  if (query && query.businessTierName) {
    value.value = query.businessTierName
  }

  // 加载数据
  getList()
})

/**
 * 监听搜索输入变化，自动触发搜索
 */
watch(value, (newVal) => {
  console.log('输入变化:', newVal); // 添加日志
  // 重置页码
  pages.value.current = 1
  // 延迟搜索，避免频繁请求
  clearTimeout(searchTimer.value);
  searchTimer.value = setTimeout(() => {
    getList()
  }, 500)
})
</script>

<style scoped lang="scss">
.search-page {

  /* 搜索输入框样式 */
  .rounded-input {
    width: 682rpx;
    height: 64rpx;
    overflow: hidden;
    border-radius: 36rpx;
    background: #F4F4F4;
    margin-top: 18rpx;
    margin-left: 36rpx;
    margin-right: 32rpx;
  }

  .history-search {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 18rpx;
    margin-left: 44rpx;
    margin-right: 44rpx;

    .history-search-title {
      width: 120rpx;
      height: 36rpx;
      font-family: PingFang SC;
      font-size: 30rpx;
      font-weight: 500;
      line-height: 36rpx;
      letter-spacing: normal;
      color: #313131;
    }

    .delete-icon {
      /* 自动布局子元素 */
      width: 24rpx;
      height: 24rpx;
      font-family: PingFang SC;
      font-size: 24rpx;
      font-weight: normal;
      line-height: 48rpx;
      text-align: right;
      letter-spacing: normal;
      color: #7B7B7B;
    }
  }

  /* 瀑布流容器样式 */
  .home-ranking {
    margin-top: 30rpx;
    margin-left: 11rpx;
    margin-right: 17rpx;
    margin-bottom: 120rpx;
  }
}
</style>