index.vue 15.6 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
<!--
 * @Date: 2026-01-31
 * @Description: 资料列表页 - 已改造为 NutTabs 版本
-->
<template>
  <view class="h-screen bg-[#F9FAFB] flex flex-col">
    <view class="bg-[#F9FAFB] z-10">
      <NavHeader :title="pageTitle" />

      <view class="px-[32rpx] mt-[32rpx] mb-[24rpx]">
        <SearchBar
          v-model="searchValue"
          placeholder="搜索资料..."
          @search="onSearch"
        />
      </view>
    </view>

    <!-- Tabs Container -->
    <view class="flex-1 min-h-0 flex flex-col">
      <!-- 动态显示 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>

      <!-- 列表容器(独立于 nut-tab-pane) -->
      <view
        v-if="listVisible"
        :key="listRenderKey"
        class="flex-1 min-h-0 overflow-y-auto px-[32rpx] pb-[calc(160rpx+env(safe-area-inset-bottom))] box-border"
      >
        <view class="flex flex-col gap-[24rpx]">
          <view v-for="(item, index) in currentList" :key="index"
            class="material-item bg-white rounded-[24rpx] p-[24rpx] shadow-sm transition-all duration-200 border border-gray-50 flex flex-row"
            :style="{ animationDelay: `${index * 50}ms` }">

            <view
              class="w-[88rpx] h-[88rpx] mr-[24rpx] flex-shrink-0 flex items-center justify-center bg-gradient-to-br from-blue-50 to-blue-100 rounded-[20rpx] shadow-inner self-start">
              <image
                :src="getDocumentIcon(item.extension ? `file.${item.extension}` : item.fileName)"
                class="w-[48rpx] h-[48rpx]"
                mode="aspectFit"
              />
            </view>

            <view class="flex-1 min-w-0">
              <h3 class="text-[#1F2937] text-[30rpx] font-bold leading-[1.4] line-clamp-2 mb-[8rpx]">
                {{ item.title }}
              </h3>
              <p class="text-[#6B7280] text-[24rpx] leading-[1.4] line-clamp-1 mb-[16rpx]">
                {{ item.desc }}
              </p>

              <view class="flex items-center gap-[12rpx] mb-[20rpx]">
                <view
                  class="inline-flex items-center justify-center px-[12rpx] py-[4rpx] bg-gray-100 text-gray-500 text-[20rpx] font-medium rounded-[8rpx]">
                  {{ getDocumentLabel(item.extension ? `file.${item.extension}` : item.fileName) }}
                </view>
                <view class="text-[#9CA3AF] text-[22rpx]">
                  {{ item.size }}
                </view>
              </view>

              <view class="h-[1rpx] bg-gray-100 my-[20rpx]"></view>

              <ListItemActions
                :viewable="true"
                :collectable="true"
                :collected="item.collected"
                :item-id="String(item.meta_id || item.id)"
                @view="onView(item)"
                @collect="toggleCollect(item)"
                @delete="onDelete(item)"
              />
            </view>
          </view>

          <!-- 空状态 -->
          <view v-if="currentList.length === 0">
            <nut-empty description="暂无相关资料" image="empty" />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { useLoad } from '@tarojs/taro'
import NavHeader from '@/components/NavHeader.vue'
import SearchBar from '@/components/SearchBar.vue'
import ListItemActions from '@/components/ListItemActions/index.vue'
import { useListItemClick, ListType } from '@/composables/useListItemClick'
import { getDocumentIcon, getDocumentLabel } from '@/utils/documentIcons'
import { fileListAPI } from '@/api/file'
import { useCollectOperation } from '@/composables/useCollectOperation'
import Taro from '@tarojs/taro'

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

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

/**
 * 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 返回的文档数据转换为组件需要的格式
 * @param {Object} doc - API 返回的文档对象
 * @returns {Object} 转换后的文档对象
 */
const transformDocItem = (doc) => {
  // 处理文件名为空的情况
  const fileName = doc.name || '未命名文件'
  // 如果没有扩展名,从文件名中提取(如果有)
  const extension = doc.extension || fileName.split('.').pop()?.toLowerCase() || ''

  return {
    id: doc.id || doc.meta_id,  // 兼容 id 和 meta_id
    meta_id: doc.meta_id || doc.id,  // 保存 meta_id 用于收藏 API
    title: fileName,
    desc: doc.post_date || '',
    size: doc.size || '',
    fileName: fileName,
    downloadUrl: doc.value,
    extension: extension,
    collected: doc.is_favorite === '1' || doc.is_favorite === 1  // 从 API 返回的收藏状态
  }
}

/**
 * 获取文档分类列表
 * @param {Object} params - 请求参数
 * @param {string} params.cid - 分类ID(可选)
 * @param {string} params.child_id - 子分类ID(可选)
 * @param {string} params.keyword - 搜索关键词(可选)
 */
const fetchMaterialList = async (params = {}) => {
  try {
    loading.value = true

    console.log('[Material List] 请求参数:', params)

    // 调用接口(直接调用,不使用 fn() 包装)
    const res = await fileListAPI(params)

    if (res.code === 1 && res.data) {
      // 如果是初始请求(没有 child_id),保存完整的分类信息
      if (!params.child_id) {
        data.value = res.data
        console.log('[Material List] 数据:', res.data)
        console.log('[Material List] 分类数量:', res.data.children?.length)
        console.log('[Material List] 文档数量:', res.data.list?.length)

        // 处理并缓存"全部"列表
        if (res.data.list?.length) {
          const allListData = res.data.list.map(transformDocItem)
          allList.value = allListData
          categoryListCache.value.set('all', allListData)
        }
      } else {
        // 是子分类请求,缓存该分类的列表数据
        const childId = params.child_id
        if (res.data.list?.length) {
          const listData = res.data.list.map(transformDocItem)
          categoryListCache.value.set(childId, listData)
          // 更新当前显示的列表
          currentList.value = listData
        } else {
          // 该分类没有数据
          currentList.value = []
        }
      }
    } else {
      Taro.showToast({
        title: res.msg || '获取资料列表失败',
        icon: 'none',
        duration: 2000
      })
    }
  } catch (error) {
    console.error('[Material List] 获取资料列表失败:', error)
    Taro.showToast({
      title: '加载失败',
      icon: 'error',
      duration: 2000
    })
  } finally {
    loading.value = false
  }
}

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

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

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

  // 获取资料列表(初始请求)
  await fetchMaterialList({ cid: options.id })

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

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

  // 判断是否是"全部" 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
      })
    }
  }

  nextTick(() => {
    listRenderKey.value += 1
    listVisible.value = true
  })
}

/**
 * 搜索处理函数
 * @description 根据 child_id 和 keyword 调用接口查询列表
 */
const onSearch = async () => {
  console.log('Searching for:', searchValue.value)
  console.log('当前分类:', 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
        })
      }
    }
    return
  }

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

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

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

  // 调用接口搜索
  try {
    loading.value = true
    const res = await fileListAPI(params)

    if (res.code === 1 && res.data) {
      if (res.data.list?.length) {
        const listData = res.data.list.map(transformDocItem)
        currentList.value = listData
      } else {
        currentList.value = []
      }
    } else {
      Taro.showToast({
        title: res.msg || '搜索失败',
        icon: 'none',
        duration: 2000
      })
    }
  } catch (error) {
    console.error('[Material List] 搜索失败:', error)
    Taro.showToast({
      title: '搜索失败',
      icon: 'error',
      duration: 2000
    })
  } finally {
    loading.value = false
  }
}

/**
 * 使用文件列表点击处理器
 * @description 添加图片预览功能,点击图片文件时使用 Taro.previewImage
 */
const { handleClick: onView } = useListItemClick({
  listType: ListType.FILE,
  onBeforeClick: async (item) => {
    /**
     * 检查文件类型并使用对应的预览方式
     * - 图片文件:使用 Taro.previewImage 预览
     * - 其他文件:继续默认的文件打开流程
     */
    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg']
    const extension = item.extension?.toLowerCase() || ''

    console.log('[Material List] 文件类型:', extension, '文件名:', item.title)

    if (imageExtensions.includes(extension)) {
      // 图片文件:使用 Taro 预览
      console.log('[Material List] 检测到图片文件,使用图片预览')

      // 构建图片列表(当前图片)
      const urls = [item.downloadUrl]

      try {
        // 预览前提示用户可以长按保存
        Taro.showToast({
          title: '点击图片预览,长按可保存到相册',
          icon: 'none',
          duration: 2000
        })

        // 短暂延迟后打开预览(让用户看到提示)
        await new Promise(resolve => setTimeout(resolve, 300))

        await Taro.previewImage({
          current: item.downloadUrl,  // 当前显示图片的 http 链接
          urls: urls                    // 需要预览的图片 http 链接列表
        })

        // 预览成功,阻止默认的文件打开行为
        return false
      } catch (err) {
        console.error('[Material List] 图片预览失败:', err)
        Taro.showToast({
          title: '图片预览失败',
          icon: 'none',
          duration: 2000
        })
        // 预览失败,返回 true 继续默认行为
        return true
      }
    }

    // 非图片文件:继续默认的文件打开流程
    console.log('[Material List] 非图片文件,使用默认打开方式')
    return true
  },
  onAfterClick: (item) => {
    console.log('用户打开了资料:', item.title)
  }
})

/**
 * 切换收藏状态
 * @description 使用 useCollectOperation composable 处理收藏操作
 */
const { toggleCollect } = useCollectOperation()

/**
 * 删除资料
 */
const onDelete = (item) => {
  Taro.showModal({
    title: '提示',
    content: '确定要删除该资料吗?',
    success: (res) => {
      if (res.confirm) {
        // 从 allList 中删除
        const index = allList.value.findIndex(i => i.id === item.id)
        if (index !== -1) {
          allList.value.splice(index, 1)
          // 重新渲染列表
          listRenderKey.value += 1
          Taro.showToast({ title: '已删除', icon: 'success' })
        }
      }
    }
  })
}
</script>

<style lang="less">
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.material-item {
  animation: slideIn 0.5s cubic-bezier(0.2, 0.8, 0.2, 1) backwards;
}

// 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;
}
</style>