index.vue 15.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
<!--
 * @Date: 2026-02-08
 * @Description: 搜索页面 - 使用 LoadMoreList 组件重构版本
 * @description 支持产品和资料搜索,实时查询API,自动切换分类
-->
<template>
  <view class="bg-[#FFF] search-page-container">
    <LoadMoreList
      :list="currentList"
      :page="currentPage"
      :page-size="pageSize"
      :has-more="hasMore"
      :loading="loading"
      :loading-more="loadingMore"
      :show-header="true"
      :enable-scroll-load="shouldEnableScrollLoad"
      :has-footer="false"
      key-field="id"
      @load-more="handleLoadMore"
    >
      <!-- 固定顶部:导航栏 + 搜索栏 + Tabs + 结果计数 -->
      <template #header>
        <view class="bg-[#FFF] sticky top-0 z-10">
          <NavHeader title="搜索" />

          <!-- Search Input -->
          <view class="px-[40rpx] mt-[32rpx]">
            <SearchBar
              v-model="searchKeyword"
              placeholder="搜索培训资料、案例、产品..."
              variant="rounded"
              :show-border="true"
              :show-clear="true"
              @search="handleSearch"
              @clear="clearSearch"
            />
          </view>

          <!-- Tabs Container -->
          <nut-tabs v-model="activeTab">
            <!-- 自定义标签栏 -->
            <template #titles>
              <view class="filter-tabs-wrapper">
                <view
                  v-for="item in tabsData"
                  :key="item.id"
                  :class="[
                    'filter-tab-item',
                    activeTab === item.id ? 'filter-tab-active' : 'filter-tab-inactive',
                    !activeTab ? 'filter-tab-inactive' : '' // 初始状态不高亮任何tab
                  ]"
                  @tap="onTabClick(item.id)"
                >
                  <text class="filter-tab-text">{{ item.name }}</text>
                </view>
              </view>
            </template>
          </nut-tabs>

          <!-- Result Count -->
          <view v-if="currentList.length > 0" class="px-[60rpx] text-[#6B7280] text-[24rpx] pb-[24rpx]">
            找到 {{ currentTotal }} 个相关结果
          </view>
        </view>
      </template>

      <!-- 列表项:根据 activeTab 动态渲染 -->
      <template #item="{ item }">
        <!-- Product Results -->
        <ProductCard
          v-if="activeTab === 'product'"
          :product-id="item.id"
          :product-name="item.product_name || item.name"
          :tags="item.tags || []"
          class="search-result-item"
          @detail="goToProductDetail"
          @plan="openPlanPopup"
        />

        <!-- File Results -->
        <MaterialCard
          v-else-if="activeTab === 'file'"
          :id="item.id"
          :title="item.title"
          :file-name="item.fileName"
          :file-size="item.fileSize"
          :learners="item.learners"
          :read-people-percent="item.readPeoplePercent"
          :collected="item.collected"
          :extension="item.extension"
          :download-url="item.downloadUrl"
          class="search-result-item"
          @collect-changed="handleCollectChanged(item, $event)"
        />
      </template>

      <!-- 自定义空状态:处理三种状态 -->
      <template #empty>
        <!-- Initial State (从未搜索过) -->
        <view v-if="!hasSearched" class="flex flex-col items-center justify-center py-[120rpx]">
          <IconFont name="search" class="text-gray-300 mb-[24rpx]" size="64" />
          <view class="text-[#6B7280] text-[28rpx]">搜索产品或资料</view>
          <view class="text-[#9CA3AF] text-[24rpx] mt-[12rpx]">输入关键词开始搜索,自动切换分类</view>
        </view>

        <!-- Empty State (已搜索但无结果) -->
        <view v-else class="flex flex-col items-center justify-center py-[40rpx]">
          <nut-empty description="暂无搜索结果" image="empty">
            <view class="text-[#9CA3AF] text-[24rpx] mt-[12rpx]">试试其他关键词吧</view>
          </nut-empty>
        </view>
      </template>
    </LoadMoreList>

    <!-- Plan Form Container -->
    <!-- 仅当 selectedProduct 不为 null 时才渲染组件,避免 product prop required 警告 -->
    <PlanFormContainer
      v-if="selectedProduct"
      v-model:visible="showPlanPopup"
      :product="selectedProduct"
      @close="handlePlanClose"
      @submit="handlePlanSubmit"
    />
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import Taro from '@tarojs/taro'
import { useGo } from '@/hooks/useGo'
import LoadMoreList from '@/components/list/LoadMoreList'
import NavHeader from '@/components/navigation/NavHeader.vue'
import IconFont from '@/components/icons/IconFont.vue'
import SearchBar from '@/components/forms/SearchBar.vue'
import ProductCard from '@/components/cards/ProductCard.vue'
import MaterialCard from '@/components/cards/MaterialCard.vue'
import PlanFormContainer from '@/components/plan/PlanFormContainer.vue'
import { searchAPI } from '@/api/search'
import { mockSearchAPI } from '@/utils/mockData'
import { usePlanSubmit } from '@/composables/usePlanSubmit'

// ⚠️ MOCK 数据开关 - 开发环境使用 mock 数据,生产环境使用真实 API
const USE_MOCK_DATA = process.env.NODE_ENV === 'development'

const go = useGo()

/**
 * 搜索页面状态管理
 * @description 支持双类型(产品/资料)搜索,自动切换分类
 */

// Plan Popup State
const showPlanPopup = ref(false)
const selectedProduct = ref(null)

// State
const searchKeyword = ref('')
const activeTab = ref('')          // 当前选中的 tab(初始为空,不选中任何tab)
const hasSearched = ref(false)     // 是否已经搜索过

// 数据状态 - 双列表系统
const products = ref([])           // 产品列表
const files = ref([])               // 资料列表
const productsTotal = ref(0)       // 产品总数
const filesTotal = ref(0)           // 资料总数

// 分页状态
const loading = ref(false)          // 首次加载状态
const loadingMore = ref(false)      // 加载更多状态
const hasMore = ref(true)           // 是否还有更多数据
const currentPage = ref(0)          // 当前页码(从0开始)
const pageSize = 20                 // 每页数量

/**
 * Tab 数据源(只保留产品和资料)
 */
const tabsData = ref([
  { id: 'product', name: '产品' },
  { id: 'file', name: '资料' },
])

/**
 * 当前显示的列表
 * @description 根据 activeTab 动态返回对应的列表数据
 */
const currentList = computed(() => {
  // 如果没有选中任何tab,返回空数组
  if (!activeTab.value) return []

  if (activeTab.value === 'product') {
    return products.value
  } else {
    return files.value
  }
})

/**
 * 当前列表总数
 */
const currentTotal = computed(() => {
  // 如果没有选中任何tab,返回0
  if (!activeTab.value) return 0

  if (activeTab.value === 'product') {
    return productsTotal.value
  } else {
    return filesTotal.value
  }
})

/**
 * 是否启用滚动加载更多
 * @description 只要有数据就可以滚动加载
 */
const shouldEnableScrollLoad = computed(() => {
  // 只要有数据就可以滚动
  return currentList.value.length > 0
})

/**
 * 执行搜索
 *
 * @param {string} keyword - 搜索关键字
 * @param {string} type - 可选,'product' | 'file' | undefined
 * @param {number} page - 页码(从0开始)
 * @param {number} limit - 每页数量
 * @param {boolean} isLoadMore - 是否为加载更多
 * @returns {Promise<void>}
 */
const performSearch = async (keyword, type, page = 0, limit = pageSize, isLoadMore = false) => {
  try {
    // 如果是加载更多,使用 loadingMore 状态;否则使用 loading 状态
    if (isLoadMore) {
      loadingMore.value = true
    } else {
      loading.value = true
    }

    const params = { keyword, page, limit }
    if (type) params.type = type

    console.log('[Search] 使用 Mock 数据:', USE_MOCK_DATA)

    // 根据开关选择使用真实 API 或 Mock 数据
    const res = USE_MOCK_DATA
      ? await mockSearchAPI(params)
      : await searchAPI(params)

    if (res.code === 1) {
      // 映射产品列表
      const newProducts = res.data.products.list || []

      // 映射资料列表(进行字段映射,与首页保持一致)
      const newFiles = (res.data.files.list || []).map(item => {
        // 提取文件扩展名
        const fileName = item.name || '未命名文件'
        const extension = item.extension || fileName.split('.').pop()?.toLowerCase() || ''

        return {
          id: item.meta_id || item.id,
          title: item.name,
          fileName: fileName,
          fileSize: item.size || item.file_size,
          downloadUrl: item.src || item.value,
          extension: extension,
          learners: item.read_people_count ? `${item.read_people_count }人学习` : '',
          readPeoplePercent: item.read_people_percent,
          is_favorite: item.is_favorite,  // 保留原始字段
          collected: Boolean(item.is_favorite)  // 转换为 Boolean 供 MaterialCard 使用
        }
      })

      // 根据是否为加载更多来处理数据
      if (isLoadMore) {
        // 加载更多:追加数据
        products.value = [...products.value, ...newProducts]
        files.value = [...files.value, ...newFiles]
      } else {
        // 首次加载或刷新:替换数据
        products.value = newProducts
        files.value = newFiles
      }

      productsTotal.value = res.data.products.total || 0
      filesTotal.value = res.data.files.total || 0

      // ⚠️ 重要:必须先自动选择 tab,然后再计算 hasMore
      // 如果不传 type,自动选择有数据的 tab(仅首次搜索时)
      if (!type && !isLoadMore) {
        if (productsTotal.value > 0) {
          activeTab.value = 'product'
        } else if (filesTotal.value > 0) {
          activeTab.value = 'file'
        }
        // 如果都为 0,默认 product
      }

      // 判断是否还有更多数据
      // 使用当前列表长度与总数比较
      // 注意:需要根据实际选择的tab来判断
      const actualTab = type || activeTab.value
      if (actualTab === 'product') {
        hasMore.value = products.value.length < productsTotal.value
      } else if (actualTab === 'file') {
        hasMore.value = files.value.length < filesTotal.value
      } else {
        // 如果都没有选中,保守设置为false
        hasMore.value = false
      }

      hasSearched.value = true

      console.log('[Search] 搜索成功', {
        productsTotal: productsTotal.value,
        filesTotal: filesTotal.value,
        activeTab: activeTab.value,
        isLoadMore,
        hasMore: hasMore.value
      })
    } else {
      Taro.showToast({
        title: res.msg || '搜索失败',
        icon: 'none'
      })
    }
  } catch (err) {
    console.error('[Search] 搜索失败:', err)
    Taro.showToast({
      title: '搜索失败,请重试',
      icon: 'none'
    })
  } finally {
    if (isLoadMore) {
      loadingMore.value = false
    } else {
      loading.value = false
    }
  }
}

/**
 * 处理加载更多事件
 *
 * @param {number} page - 下一页页码
 * @returns {Promise<void>}
 */
const handleLoadMore = async (page) => {
  console.log('[Search] 加载更多,页码:', page)

  // 更新页码
  currentPage.value = page

  // 如果没有搜索过或没有选中 tab,不执行
  if (!hasSearched.value || !activeTab.value || !searchKeyword.value.trim()) {
    return
  }

  // 加载下一页数据
  await performSearch(
    searchKeyword.value.trim(),
    activeTab.value,
    page,
    pageSize,
    true  // 标记为加载更多
  )
}

/**
 * Tab 点击处理(实时查询)
 *
 * @param {string} tabId - Tab ID
 */
const onTabClick = async (tabId) => {
  if (activeTab.value === tabId) return

  // 立即切换 tab(响应更快)
  activeTab.value = tabId

  // 重置分页状态
  currentPage.value = 0
  hasMore.value = true

  // 如果已经搜索过,实时查询对应类型的数据
  if (hasSearched.value && searchKeyword.value.trim()) {
    console.log('[Search] 切换 tab,实时查询:', tabId)
    await performSearch(searchKeyword.value.trim(), tabId, 0, pageSize, false)
  }
}

/**
 * 提交搜索
 */
const handleSearch = async () => {
  const keyword = searchKeyword.value.trim()
  if (!keyword) {
    Taro.showToast({
      title: '请输入搜索关键词',
      icon: 'none'
    })
    return
  }

  console.log('[Search] 提交搜索:', keyword)

  // 重置分页状态
  currentPage.value = 0
  hasMore.value = true

  // 不传 type,让后端返回两种数据,前端自动选择 tab
  await performSearch(keyword, undefined, 0, pageSize, false)
}

/**
 * 清空搜索
 */
const clearSearch = () => {
  console.log('[Search] 清空搜索')
  searchKeyword.value = ''
  hasSearched.value = false
  products.value = []
  files.value = []
  productsTotal.value = 0
  filesTotal.value = 0
  activeTab.value = ''  // 重置为空,不选中任何tab
  currentPage.value = 0
  hasMore.value = true
}

/**
 * 跳转到产品详情页
 *
 * @param {number} productId - 产品ID
 */
const goToProductDetail = (productId) => {
  go('/pages/product-detail/index', { id: productId })
}

/**
 * 打开计划书弹窗
 *
 * @param {number} productId - 产品ID
 */
const openPlanPopup = (productId) => {
  // 从产品列表中找到对应的产品
  const product = products.value.find(p => p.id === productId)

  if (!product) {
    Taro.showToast({
      title: '产品不存在',
      icon: 'none',
      duration: 2000
    })
    return
  }

  // 设置选中的产品
  selectedProduct.value = product
  showPlanPopup.value = true
}

// 使用 composable 统一处理计划书提交后逻辑
const { handlePlanSubmit } = usePlanSubmit({
  getPopupState: () => showPlanPopup.value,
  setPopupState: (state) => { showPlanPopup.value = state },
  clearSelectedProduct: () => { selectedProduct.value = null },
  useGoUtil: true,
  pageName: 'Search Page'
})

/**
 * 处理收藏状态改变
 *
 * @param {Object} item - 资料对象
 * @param {Object} newStatus - 新的状态 { collected: boolean }
 */
const handleCollectChanged = (item, newStatus) => {
  console.log('[Search] 收藏状态改变:', item.title, newStatus.collected)
  // 找到对应的项并更新状态
  const file = files.value.find(f => f.id === item.id)
  if (file) {
    file.collected = newStatus.collected
  }
}
</script>

<style lang="less">
// FilterTabs 风格的标签栏
.filter-tabs-wrapper {
  display: flex;
  overflow-x: auto;
  padding: 24rpx 60rpx;
  gap: 24rpx;
  transition: all 0.3s ease;
  background-color: #FFF;
  width: 100%;

  // 隐藏滚动条
  &::-webkit-scrollbar {
    display: none;
    width: 0;
    height: 0;
  }

  -ms-overflow-style: none;
  scrollbar-width: none;
}

.filter-tab-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 32rpx;
  border-radius: 9999rpx;
  white-space: nowrap;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.filter-tab-active {
  background-color: #2563EB; // 蓝色背景
  color: #fff;
}

.filter-tab-inactive {
  background-color: #F3F4F6; // 灰色背景
  color: #6B7280;
}

.filter-tab-text {
  font-size: 28rpx;
  font-weight: 500;
}

// 覆盖 NutUI Tabs 默认样式
:deep(.nut-tabs__titles) {
  display: none;
}

:deep(.nut-tabs__content) {
  display: none;
}

/* LoadMoreList 组件已内置动画和加载状态,此处无需额外样式 */

/* 页面容器 - 固定高度,禁止页面级滚动 */
.search-page-container {
  height: 100vh;
  overflow: hidden;
}
</style>