<template>
  <view class="search-page">
    <!-- 搜索输入框 -->
    <u-input placeholder="请输入搜索的服务" prefixIcon="search" v-model="value" class="rounded-input" @confirm="handleSearch"
      clearable @clear="handleClear"></u-input>
    <!-- 历史记录 -->
    <view class="history-search" v-if="historyList.length > 0">
      <view class="history-search-title">历史搜索</view>
      <view @click="clearHistory">
        <image src="@/static/img/delete-bin-6-fill@1x.png" mode="widthFix" class="delete-icon"></image>
        清空
      </view>
    </view>
    <!-- 历史搜索列表 -->
    <view class="history-list" v-if="historyList.length > 0">
      <view class="history-item" v-for="(item, index) in historyList" :key="index" @click="searchByHistory(item)">
        {{ item.businessTierName || item }}
      </view>
    </view>
    <!-- 无历史记录提示 -->
    <view class="no-history" v-if="historyList.length === 0">
      <text>暂无搜索历史记录</text>
    </view>

    <!-- tab -->
    <view>
      <up-tabs 
        :list="list2" 
        @change="handleTabChange">
      </up-tabs>
    </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, volBusinessTypeList, searchHistoryBusinessTireNameHistory } 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 list2 = reactive([]);
// 历史搜索列表
const historyList = ref([]);

// 用户类型
const userType = uni.getStorageSync('userType') || 1; //读取本地存储
// 添加搜索定时器引用
const searchTimer = ref(null);

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

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

/**
 * 获取历史搜索记录
 */
const getHistoryList = async () => {
  try {
    console.log('开始获取历史搜索记录')
    const res = await searchHistoryBusinessTireNameHistory({})
    console.log('历史搜索API响应:', res)
    if (res && res.data) {
      // 检查返回的数据类型并适当处理
      if (Array.isArray(res.data)) {
        // 如果是简单字符串数组，转换为对象数组
        if (typeof res.data[0] === 'string') {
          historyList.value = res.data.map(item => ({ businessTierName: item }))
        } else {
          historyList.value = res.data
        }
      } else {
        historyList.value = []
      }
      console.log('设置历史记录列表:', historyList.value)
    } else {
      console.log('API返回数据为空或没有data字段')
      historyList.value = []
    }
  } catch (error) {
    console.error('获取历史搜索记录失败:', error)
    historyList.value = []
  }
}

/**
 * 清空历史搜索记录
 */
const clearHistory = async () => {
  try {
    // 这里假设接口支持清空历史记录，如果没有专门的清空接口，可能需要另外实现
    await searchHistoryBusinessTireNameHistory({ clear: true })
    historyList.value = []
    uni.showToast({
      title: '历史记录已清空',
      icon: 'none'
    })
  } catch (error) {
    console.error('清空历史记录失败:', error)
    uni.showToast({
      title: '清空历史记录失败',
      icon: 'none'
    })
  }
}

/**
 * 点击历史记录进行搜索
 */
const searchByHistory = (item) => {
  // 处理不同的数据格式
  value.value = typeof item === 'string' ? item : item.businessTierName
  handleSearch()
}

/**
 * 处理搜索确认事件
 */
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'
  }
}

/**
 * 处理Tab切换事件
 * @param {Object} e - 事件对象，包含选中tab的索引
 */
const handleTabChange = (e) => {
  // 安全地获取索引
  const index = typeof e === 'object' && e !== null ? (e.index !== undefined ? e.index : 0) : (typeof e === 'number' ? e : 0);
  
  console.log('切换到Tab:', e, '索引:', index)
  
  // 重置页码
  pages.value.current = 1
  
  // 设置businessManagementId
  if (index === 0) {
    // 如果是"全部"选项，设置为0
    pages.value.businessManagementId = 0
  } else if (index > 0 && index < list2.length) {
    const selectedTab = list2[index]
    console.log('选中的Tab数据:', selectedTab)
    
    // 从businessManagementId字段获取，其次id字段获取
    if (selectedTab && selectedTab.businessManagementId !== undefined) {
      pages.value.businessManagementId = selectedTab.businessManagementId
    } else if (selectedTab && selectedTab.id !== undefined) {
      pages.value.businessManagementId = selectedTab.id
    } else {
      pages.value.businessManagementId = 0
    }
    
    // 如果有children中的id，设置到请求参数中
    if (selectedTab && selectedTab.children && Array.isArray(selectedTab.children) && selectedTab.children.length > 0) {
      // 查找第一个有id的child
      const firstChildWithId = selectedTab.children.find(child => child && child.id !== undefined);
      if (firstChildWithId && firstChildWithId.id !== undefined) {
        console.log('使用children中的ID:', firstChildWithId.id);
        pages.value.businessManagementId = firstChildWithId.id;
      }
    }
  } else {
    // 默认为0
    pages.value.businessManagementId = 0
  }
  
  console.log('设置businessManagementId:', pages.value.businessManagementId)
  
  // 执行搜索
  getList()
}

/**
 * 获取列表数据
 * 支持分页和关键词搜索
 */
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: pages.value.businessManagementId,
      // 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,
    }

    const paramstyle = {
      businessTierName: value.value, // 名称搜索参数
      businessManagementId: pages.value.businessManagementId,
    }
    console.log('businessManagementId 类型:', typeof params.businessManagementId);
    console.log('businessManagementId 值:', params.businessManagementId);
    console.log('paramstyle 对象:', paramstyle);
    console.log('paramstyle中的businessManagementId:', paramstyle.businessManagementId);
    // 调用API前的最终参数检查
    console.log('发送前的最终参数(JSON):', JSON.stringify(params));
    console.log('发送前的style参数(JSON):', JSON.stringify(paramstyle));

    // 调用API获取数据
    const res = await volTierName(params)
    
    // 如果用户输入了搜索关键词，始终更新标签列表以显示相关标签
    // 如果没有关键词，且标签列表为空，则获取所有标签
    if (value.value || list2.length === 0) {
      const res1 = await volBusinessTypeList(paramstyle)
      
      // 搜索成功后更新历史记录
      if (value.value) {
        getHistoryList() // 刷新历史记录
      }
      
      if (res1 && res1.data) {
        // 打印原始数据以检查id字段
        console.log('原始API返回的Tabs数据:', JSON.stringify(res1.data))
        
        // 记住当前选中的标签名称，以便在重新生成列表后恢复选择
        let selectedTabName = '';
        if (list2.length > 0 && pages.value && pages.value.businessManagementId !== undefined) {
          const currentIndex = Math.min(Math.max(0, pages.value.businessManagementId === 0 ? 0 : 1), list2.length - 1);
          selectedTabName = list2[currentIndex]?.name || '';
        }
        
        // 清空原有数据
        list2.splice(0, list2.length)

        // 添加全部选项
        list2.push({
          name: '全部',
          value: '0',
          businessManagementId: 0,
          id: 0
        })

        // 转换API返回的数据为up-tabs需要的格式
        res1.data.forEach(item => {
          // 检查是否有children数组
          let childrenIds = [];
          if (item.children && Array.isArray(item.children)) {
            // 收集所有children的ID
            childrenIds = item.children.map(child => child.id).filter(id => id !== undefined);
            console.log('项目children IDs:', childrenIds);
          }
          
          list2.push({
            name: item.businessTierName,
            // 尝试获取正确的ID字段 - 优先使用businessManagementId，其次使用id
            businessManagementId: item.businessManagementId || item.id || 0,
            id: item.id || item.businessManagementId || 0,
            // 保存children的id数组
            childrenIds: childrenIds,
            // 保存完整的children数据
            children: item.children || []
          })
        })
        
        // 尝试恢复选中的标签
        if (selectedTabName) {
          // 查找具有相同名称的标签
          const matchingIndex = list2.findIndex(item => item.name === selectedTabName);
          if (matchingIndex !== -1 && pages.value) {
            // 设置businessManagementId为找到的匹配项的ID
            pages.value.businessManagementId = list2[matchingIndex].businessManagementId || list2[matchingIndex].id || 0;
          }
        }

        console.log('转换后的Tabs数据:', JSON.stringify(list2))
      }
    }

    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()
  // 获取历史搜索记录
  getHistoryList()
})

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

/**
 * 处理清除搜索内容
 */
const handleClear = () => {
  value.value = ''
  // 重置页码
  pages.value.current = 1
  // 清空后显示全部数据
  getList()
}
</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: 24rpx;
    margin-left: 44rpx;
    margin-right: 44rpx;
    padding-bottom: 6rpx;
    border-bottom: 2rpx solid #f0f0f0;

    .history-search-title {
      width: 140rpx;
      height: 40rpx;
      font-family: PingFang SC;
      font-size: 32rpx;
      font-weight: 600;
      line-height: 40rpx;
      letter-spacing: normal;
      color: #313131;
    }

    .delete-icon {
      width: 28rpx;
      height: 28rpx;
      margin-right: 6rpx;
    }
  }

  /* 历史搜索列表样式 */
  .history-list {
    display: flex;
    flex-wrap: wrap;
    margin: 20rpx 44rpx;
    padding: 10rpx 0;
    background-color: #f9f9f9;
    border-radius: 16rpx;

    .history-item {
      padding: 14rpx 28rpx;
      margin: 12rpx;
      background-color: #EAEAEA;
      border-radius: 30rpx;
      font-size: 28rpx;
      color: #000;
      font-weight: 500;
      box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
    }
  }

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