index.vue 19.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 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
<!--
 * @Date: 2026-02-27
 * @Description: 文章列表页 - 改造版(原文章列表页)
 * @改造说明: 将文章列表改造为文章列表,使用文章API
-->
<template>
  <view class="h-screen overflow-hidden bg-[#F9FAFB]">
    <LoadMoreList
      :list="currentList"
      :page="currentPage"
      :page-size="pageSize"
      :has-more="hasMore"
      :loading="loading"
      :loading-more="loadingMore"
      key-field="meta_id"
      :has-footer="false"
      @load-more="handleLoadMore"
    >
      <!-- 头部:导航 + 搜索 + Tabs -->
      <template #header>
        <view class="sticky top-0 z-10 bg-[#F9FAFB]">
          <NavHeader :title="pageTitle" />

          <view class="px-[32rpx] mt-[32rpx] mb-[24rpx]">
            <SearchBar
              v-model="searchValue"
              placeholder="搜索文章..."
              @search="onSearch"
              @clear="onClear"
              variant="rounded"
              :show-border="true"
              :show-clear="true"
            />
          </view>

          <!-- 动态显示 Tabs(仅在有分类时显示) -->
          <nut-tabs v-if="hasCategories" v-model="activeTabId">
            <!-- 自定义标签栏 -->
            <template #titles>
              <view class="filter-tabs-wrapper">
                <view
                  v-for="item in tabsData"
                  :key="item.id"
                  :class="[
                    'filter-tab-item',
                    activeTabId === item.id ? 'filter-tab-active' : 'filter-tab-inactive'
                  ]"
                  @tap="onTabClick(item.id)"
                >
                  <text class="filter-tab-text">{{ item.name }}</text>
                </view>
              </view>
            </template>
          </nut-tabs>
        </view>
      </template>

      <!-- 列表项:文章卡片 -->
      <template #item="{ item }">
        <ArticleCard
          :id="item.id"
          :title="item.title"
          :excerpt="item.excerpt"
          :cover-url="item.coverUrl"
          :date="item.date"
          :collected="item.collected"
          @viewed="onView(item)"
          @collect-changed="handleCollectChanged(item, $event)"
        />
      </template>

      <!-- 空状态 -->
      <template #empty>
        <nut-empty description="暂无相关文章" image="empty" />
      </template>
    </LoadMoreList>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useLoad } from '@tarojs/taro'
import NavHeader from '@/components/navigation/NavHeader.vue'
import SearchBar from '@/components/forms/SearchBar.vue'
import LoadMoreList from '@/components/list/LoadMoreList'
import ArticleCard from '@/components/cards/ArticleCard.vue'
import { debounce } from '@/utils/debounce'
import { listAPI } from '@/api/article'
import { mockArticleListAPI } from '@/utils/mockData'
import Taro from '@tarojs/taro'
import { USE_MOCK_DATA } from '@/config/app'

// ⚠️ MOCK 数据开关 - 统一从 @/config/app 导入
// const USE_MOCK_DATA = process.env.NODE_ENV === 'development'

const searchValue = ref('')
const activeTabId = ref('all') // 默认选中"全部"

/**
 * 防抖搜索函数
 * @description 使用防抖优化搜索性能,避免频繁请求接口
 */
const debouncedSearch = debounce(async () => {
  console.log('[Article List] 防抖搜索触发')
  await onSearch()
}, 500)

/**
 * 加载状态
 */
const loading = ref(false)

/**
 * 加载更多状态
 * @description 区分首次加载和加载更多
 */
const loadingMore = ref(false)

/**
 * 每页数量
 */
const pageSize = 10

/**
 * 当前页码(从0开始)
 */
const currentPage = ref(0)

/**
 * 是否有更多数据
 */
const hasMore = ref(true)

/**
 * 各分类的分页状态缓存
 * @description Map<categoryId, { currentPage, hasMore }>
 */
const categoryPageCache = ref(new Map())

/**
 * API 返回的原始数据
 */
const data = ref(null)

/**
 * 初始分类ID(从页面参数获取)
 */
const initialCategoryId = ref(null)

/**
 * 是否有分类标签
 * @description 根据后端返回的 children 判断
 */
const hasCategories = computed(() => {
  return data.value?.children?.length > 0
})

/**
 * 页面标题
 */
const pageTitle = ref('文章列表')

/**
 * 文章数据源(从 API 获取)
 */
const allList = ref([])

/**
 * 各个分类的缓存列表数据
 * @description key: 分类ID,value: 该分类的列表数据
 */
const categoryListCache = ref(new Map()) // 使用 Map 缓存各分类的列表数据

/**
 * 当前显示的列表数据
 * @description 根据当前选中的 tab 和搜索关键词动态计算
 */
const currentList = ref([])

/**
 * 文章分类数据
 * @description 根据 API 返回的 children 构建 tabs,始终包含"全部"选项
 */
const tabsData = computed(() => {
  // 始终包含"全部" tab
  const tabs = [
    { id: 'all', name: '全部' }
  ]

  // 如果有子分类,添加到 tabs
  const children = data.value?.children || []
  if (children.length > 0) {
    children.forEach(child => {
      tabs.push({
        id: String(child.id),
        name: child.category_name
      })
    })
  }

  return tabs
})

/**
 * 转换文章数据格式
 * @description 将 API 返回的文章数据转换为 ArticleCard 组件需要的格式
 * @param {Object} article - API 返回的文章对象
 * @returns {Object} 转换后的文章对象
 */
const transformDocItem = (article) => {
  return {
    id: article.id,
    title: article.post_title || '未命名文章',
    excerpt: article.post_excerpt || '',
    coverUrl: article.file_list?.icon?.value || '',
    date: article.post_date || '',
    collected: article.is_favorite === 1 || article.is_favorite === '1'
  }
}

/**
 * 获取文章列表
 *
 * @param {Object} params - 请求参数
 * @param {string} params.cid - 分类ID(可选)
 * @param {string} params.child_id - 子分类ID(可选)
 * @param {string} params.keyword - 搜索关键词(可选)
 * @param {number} params.page - 页码(从0开始)
 * @param {number} params.limit - 每页数量
 * @param {boolean} isLoadMore - 是否为加载更多
 * @returns {Promise<void>}
 */
const fetchMaterialList = async (params = {}, isLoadMore = false) => {
  try {
    // 如果是加载更多,使用 loadingMore 状态,否则使用 loading 状态
    if (isLoadMore) {
      loadingMore.value = true
    } else {
      loading.value = true
    }

    console.log('[Article List] 请求参数:', params)
    console.log('[Article List] 使用 Mock 数据:', USE_MOCK_DATA)

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

    if (res.code === 1 && res.data) {
      // 如果是初始请求(没有 child_id),保存完整的分类信息
      if (!params.child_id && !params.keyword) {
        data.value = res.data

        // 处理并缓存"全部"列表
        if (res.data.list?.length) {
          const allListData = res.data.list.map(transformDocItem)

          if (isLoadMore) {
            // 加载更多:追加数据
            allList.value = [...allList.value, ...allListData]
            categoryListCache.value.set('all', allList.value)
            // ✅ 同步更新 currentList(如果当前显示的是"全部")
            if (activeTabId.value === 'all') {
              currentList.value = allList.value
            }
          } else {
            // 首次加载:替换数据
            allList.value = allListData
            categoryListCache.value.set('all', allListData)
            // ✅ 同步更新 currentList(如果当前显示的是"全部")
            if (activeTabId.value === 'all') {
              currentList.value = allListData
            }
          }

          // 判断是否还有更多数据
          hasMore.value = allListData.length >= params.limit
        } else {
          if (isLoadMore) {
            hasMore.value = false
          } else {
            allList.value = []
          }
        }
      } else {
        // 是子分类请求或搜索请求
        const cacheKey = params.child_id || params.keyword || 'search'

        if (res.data.list?.length) {
          const listData = res.data.list.map(transformDocItem)

          if (isLoadMore) {
            // 加载更多:追加数据
            const existingData = categoryListCache.value.get(cacheKey) || []
            const newData = [...existingData, ...listData]
            categoryListCache.value.set(cacheKey, newData)
            // ✅ 同步更新 currentList(如果当前显示的是该缓存)
            const currentCacheKey = params.child_id || params.keyword || 'all'
            if (activeTabId.value === currentCacheKey) {
              currentList.value = newData
            }
          } else {
            // 首次加载:替换数据
            categoryListCache.value.set(cacheKey, listData)
            currentList.value = listData
          }

          // 判断是否还有更多数据
          hasMore.value = listData.length >= params.limit
        } else {
          if (isLoadMore) {
            hasMore.value = false
          } else {
            currentList.value = []
          }
        }
      }
    } else {
      Taro.showToast({
        title: res.msg || '获取文章列表失败',
        icon: 'none',
        duration: 2000
      })
    }
  } catch (error) {
    console.error('[Article List] 获取文章列表失败:', error)
    Taro.showToast({
      title: '加载失败',
      icon: 'error',
      duration: 2000
    })
  } finally {
    if (isLoadMore) {
      loadingMore.value = false
    } else {
      loading.value = false
    }
  }
}

/**
 * 页面加载时接收参数
 */
useLoad(async (options) => {
  console.log('[Article List] 页面参数:', options)

  // 保存初始分类ID
  if (options.id) {
    initialCategoryId.value = options.id
  }

  // 设置页面标题
  if (options.title) {
    pageTitle.value = options.title
  }

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

  // 获取文章列表(初始请求)
  await fetchMaterialList({
    cid: options.id,
    page: 0,
    limit: pageSize
  })

  // 初始化当前列表为"全部"列表(等待请求完成后)
  currentList.value = allList.value
})

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

  // 更新页码
  currentPage.value = page

  // 构建请求参数
  const params = {
    cid: initialCategoryId.value,
    page: page,
    limit: pageSize
  }

  // 判断当前状态:搜索、子分类、或全部
  const isSearching = searchValue.value.trim() !== ''

  if (isSearching) {
    // 搜索模式
    params.keyword = searchValue.value.trim()
    if (activeTabId.value !== 'all') {
      params.child_id = activeTabId.value
    }
  } else {
    // 非搜索模式:如果当前选中的是子分类,添加 child_id 参数
    if (activeTabId.value !== 'all') {
      params.child_id = activeTabId.value
    }
  }

  // 加载下一页数据
  await fetchMaterialList(params, true)  // true 表示加载更多

  // 保存更新后的分页状态
  let cacheKey
  if (isSearching) {
    cacheKey = params.keyword
  } else {
    cacheKey = activeTabId.value !== 'all' ? activeTabId.value : 'all'
  }
  categoryPageCache.value.set(cacheKey, {
    currentPage: currentPage.value,
    hasMore: hasMore.value
  })
}

/**
 * Tab 点击处理
 *
 * @param {string} id - Tab ID
 */
const onTabClick = async (id) => {
  if (activeTabId.value === id) return

  console.log('[Article List] 切换分类:', id)

  activeTabId.value = id

  // 恢复或初始化该分类的分页状态
  const pageState = categoryPageCache.value.get(id)
  if (pageState) {
    currentPage.value = pageState.currentPage
    hasMore.value = pageState.hasMore
  } else {
    currentPage.value = 0
    hasMore.value = true
  }

  // 判断是否是"全部" tab
  if (id === 'all') {
    // 显示"全部"列表(从缓存或 allList)
    const cachedList = categoryListCache.value.get('all')
    currentList.value = cachedList || allList.value || []
  } else {
    // 检查缓存中是否有该分类的数据
    if (categoryListCache.value.has(id)) {
      // 从缓存中获取
      currentList.value = categoryListCache.value.get(id)
    } else {
      // 调用接口获取该分类的列表(第一页)
      await fetchMaterialList({
        cid: initialCategoryId.value,
        child_id: id,
        page: 0,
        limit: pageSize
      })

      // 保存分页状态
      categoryPageCache.value.set(id, {
        currentPage: 0,
        hasMore: hasMore.value
      })
    }
  }
}

/**
 * 搜索处理函数
 * @description 根据 child_id 和 keyword 调用接口查询列表
 */
const onSearch = async () => {
  console.log('[Article List] 搜索产品:', searchValue.value)
  console.log('[Article List] 当前分类:', activeTabId.value)

  // 如果没有搜索关键词,清空搜索并恢复当前分类的列表
  if (!searchValue.value.trim()) {
    // 恢复当前分类的列表
    if (activeTabId.value === 'all') {
      const cachedList = categoryListCache.value.get('all')
      currentList.value = cachedList || allList.value || []
    } else {
      const cachedList = categoryListCache.value.get(activeTabId.value)
      if (cachedList) {
        currentList.value = cachedList
      } else {
        // 如果缓存中没有,调用接口获取
        await fetchMaterialList({
          cid: initialCategoryId.value,
          child_id: activeTabId.value,
          page: 0,
          limit: pageSize
        })
      }
    }

    // 恢复分页状态
    const pageState = categoryPageCache.value.get(activeTabId.value)
    if (pageState) {
      currentPage.value = pageState.currentPage
      hasMore.value = pageState.hasMore
    }
    return
  }

  // 构建请求参数
  const params = {
    cid: initialCategoryId.value,
    page: 0,
    limit: pageSize
  }

  // 如果当前选中的是子分类,添加 child_id 参数
  if (activeTabId.value !== 'all') {
    params.child_id = activeTabId.value
  }

  // 添加搜索关键词
  params.keyword = searchValue.value.trim()

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

  // 调用接口搜索
  try {
    loading.value = true
    console.log('[Article List] 搜索使用 Mock 数据:', USE_MOCK_DATA)

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

    if (res.code === 1 && res.data) {
      if (res.data.list?.length) {
        const listData = res.data.list.map(transformDocItem)
        currentList.value = listData

        // 缓存搜索结果
        categoryListCache.value.set(params.keyword, listData)

        // 判断是否还有更多数据
        hasMore.value = listData.length >= pageSize
      } else {
        currentList.value = []
        hasMore.value = false
      }
    } else {
      Taro.showToast({
        title: res.msg || '搜索失败',
        icon: 'none',
        duration: 2000
      })
    }
  } catch (error) {
    console.error('[Article List] 搜索失败:', error)
    Taro.showToast({
      title: '搜索失败',
      icon: 'error',
      duration: 2000
    })
  } finally {
    loading.value = false
  }
}

/**
 * 监听搜索关键字变化
 * @description 实现实时搜索:用户输入时自动触发搜索(带防抖)
 */
watch(searchValue, (newValue, oldValue) => {
  console.log('[Article List] searchValue 变化:', oldValue, '->', newValue)

  // 如果搜索关键字为空,立即清除搜索(不需要防抖)
  if (!newValue?.trim()) {
    console.log('[Article List] 搜索关键字为空,立即清除')
    onClear()
    return
  }

  // 有搜索关键字,使用防抖搜索
  console.log('[Article List] 触发防抖搜索')
  debouncedSearch()
})

/**
 * 清空搜索
 */
const onClear = async () => {
  console.log('[Article List] 清空搜索')
  console.log('[Article List] 当前分类:', activeTabId.value)

  // 构建请求参数(不带 keyword)
  const params = {
    cid: initialCategoryId.value,
    page: 0,
    limit: pageSize
  }

  // 如果当前选中的是子分类,添加 child_id 参数
  if (activeTabId.value !== 'all') {
    params.child_id = activeTabId.value
  }

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

  // 重新请求接口(不带 keyword,获取最新数据)
  await fetchMaterialList(params, false)

  // 更新当前显示的列表
  if (activeTabId.value === 'all') {
    // 全部列表:使用 allList
    currentList.value = allList.value
  } else {
    // 子分类列表:已经在 fetchMaterialList 中更新了 currentList
  }
}

/**
 * 查看文章
 * @description 点击查看按钮时,跳转到文章详情页
 * @param {Object} item - 文章对象
 *
 * @note 权限检查已在 ListItemActions 组件内部统一处理
 */
const onView = (item) => {
  console.log('[Article List] 查看文章:', item.title)
  // 跳转到文章详情页
  Taro.navigateTo({
    url: `/pages/article-detail/index?id=${item.id}`
  })
}

/**
 * 处理收藏状态改变
 *
 * @description 当用户点击收藏按钮时,更新本地列表中的收藏状态
 * @param {Object} item - 文章对象
 * @param {Object} newStatus - 新的状态 { collected: boolean }
 */
const handleCollectChanged = (item, newStatus) => {
  console.log('[Article List] 收藏状态改变:', item.title, newStatus.collected)

  // 更新 allList 中的收藏状态
  const article = allList.value.find(a => a.id === item.id)
  if (article) {
    article.collected = newStatus.collected
  }

  // 更新 currentList 中的收藏状态(如果存在)
  const currentArticle = currentList.value.find(a => a.id === item.id)
  if (currentArticle) {
    currentArticle.collected = newStatus.collected
  }

  // 更新所有缓存中的收藏状态
  categoryListCache.value.forEach((list, key) => {
    const cachedArticle = list.find(a => a.id === item.id)
    if (cachedArticle) {
      cachedArticle.collected = newStatus.collected
    }
  })
}
</script>

<style lang="less">
// FilterTabs 风格的标签栏
.filter-tabs-wrapper {
  display: flex;
  overflow-x: auto;
  padding: 24rpx 32rpx;
  gap: 24rpx;
  transition: all 0.3s ease;
  background-color: #F9FAFB;
  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;
}

/* 多行文本省略 */
.line-clamp-1 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  overflow: hidden;
  word-break: break-all;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
  word-break: break-all;
}
</style>