import type { CultureCategoryKey, CultureItem } from '../../../data/culture-content' import { createCultureFilterOptions, createCultureFilters, findCultureCategory, getCultureList } from '../../../data/culture-content' import { getInheritCategories } from '../../../data/inherit-api' import { getNavBarLayout } from '../../../utils/nav-bar' import { runRefresh } from '../../../utils/refresh' import { getArticleDetailUrl } from '../../../utils/routes' const initialCategory = findCultureCategory(undefined) // 输入停顿后再搜索,避免每输入一个字就请求一次。 const SEARCH_DEBOUNCE = 400 Page({ data: { activeCategory: initialCategory.key, title: initialCategory.title, categoryIcon: initialCategory.icon, items: [] as CultureItem[], keyword: '', supportsFilters: false, filters: createCultureFilters(), filterOptions: createCultureFilterOptions(), failedImages: {} as Record, statusBarHeight: 20, navHeight: 44, navRightPadding: 100, scrollTop: 0, remoteCategory: '' as CultureCategoryKey | '', optionsLoaded: false, loading: false, loadError: '', hasMore: false, nextPage: 1, requestVersion: 0, searchTimer: 0, refreshing: false, }, onLoad(options) { const { statusBarHeight, navHeight, navRightPadding } = getNavBarLayout() const category = findCultureCategory(options.category) const remoteCategory = category.key this.setData({ statusBarHeight, navHeight, navRightPadding, activeCategory: category.key, title: category.title, categoryIcon: category.icon, items: [], supportsFilters: !!category.supportsFilters, remoteCategory, keyword: options.keyword || '', filters: category.supportsFilters ? { category: options.categoryId || '', level: options.levelId || '', district: options.districtId || '' } : createCultureFilters(), filterOptions: createCultureFilterOptions(), }) wx.setNavigationBarTitle({ title: category.title }) return this.loadItems() }, onUnload() { this.cancelPendingSearch() this.data.requestVersion++ }, cancelPendingSearch() { if (this.data.searchTimer) { clearTimeout(this.data.searchTimer) this.data.searchTimer = 0 } }, async onPullRefresh() { this.setData({ refreshing: true }) await runRefresh([this.loadItems(true, true)]) this.setData({ refreshing: false }) }, // refresh 为下拉刷新:保留当前列表直到新数据返回,已有内容时失败只提示不清空。 async loadItems(reset = true, refresh = false) { const { remoteCategory, keyword, filters, optionsLoaded, supportsFilters } = this.data if (!remoteCategory) { return } // 任何重新加载都已带上最新关键词,未触发的延迟搜索可以丢弃。 if (reset) { this.cancelPendingSearch() } const requestVersion = ++this.data.requestVersion const page = reset ? 1 : this.data.nextPage if (!refresh) { this.setData({ loading: true, loadError: '', ...(reset ? { items: [], hasMore: false, scrollTop: 0, failedImages: {} } : {}) }) } try { const [options, result] = await Promise.all([ !supportsFilters || optionsLoaded ? Promise.resolve(null) : getInheritCategories(), getCultureList(remoteCategory, { keyword, categoryId: filters.category, levelId: filters.level, districtId: filters.district }, page), ]) // 搜索或筛选改变后,丢弃旧请求及旧分页结果。 if (requestVersion !== this.data.requestVersion) { return } if (options) { const groups = { category: options.categories, level: options.levels, district: options.districts } this.setData({ optionsLoaded: true, filterOptions: createCultureFilterOptions().map((option) => { const values = groups[option.key] const ids = ['', ...values.map(item => item.id)] const names = [option.options[0], ...values.map(item => item.name)] const index = Math.max(0, ids.indexOf(filters[option.key])) return { ...option, ids, options: names, index, value: index ? names[index] : '' } }), }) } this.setData({ items: reset ? result.items : [...this.data.items, ...result.items], ...(refresh ? { failedImages: {} } : {}), loading: false, loadError: '', hasMore: result.hasMore, nextPage: page + 1, }) } catch (error) { if (requestVersion !== this.data.requestVersion) { return } // 刷新会作废进行中的加载更多,这里统一结束加载态。 if (refresh && this.data.items.length) { this.setData({ loading: false }) throw error } this.setData({ loading: false, loadError: error instanceof Error ? error.message : '数据加载失败,请稍后重试' }) } }, onLoadMore() { if (this.data.remoteCategory && this.data.hasMore && !this.data.loading && !this.data.loadError) { return this.loadItems(false) } }, onRetry() { return this.loadItems(!this.data.items.length) }, onSearchInput(e: WechatMiniprogram.Input) { const keyword = e.detail.value this.setData({ keyword }) this.cancelPendingSearch() this.data.searchTimer = setTimeout(() => { this.data.searchTimer = 0 this.loadItems() }, SEARCH_DEBOUNCE) }, onSearchConfirm() { // 点击键盘“搜索”时立即执行尚未触发的延迟搜索。 if (this.data.searchTimer) { return this.loadItems() } }, onClearSearch() { this.setData({ keyword: '' }) return this.loadItems() }, onFilterChange(e: WechatMiniprogram.PickerChange) { const key = e.currentTarget.dataset.key const option = this.data.filterOptions.find(option => option.key === key) const index = Number(e.detail.value) if (!this.data.supportsFilters || (this.data.remoteCategory && !this.data.optionsLoaded) || !option || !Number.isInteger(index) || !option.options[index]) { return } const value = option.ids ? option.ids[index] : index === 0 ? '' : option.options[index] const filters = { ...this.data.filters, [option.key]: value } // 三个筛选条件与搜索同时生效;清除搜索只清关键词,保留筛选选择。 this.setData({ filters, filterOptions: this.data.filterOptions.map(item => item.key === option.key ? { ...item, index, value: index ? item.options[index] : '' } : item), }) return this.loadItems() }, onResetFilters() { this.setData({ keyword: '', filters: createCultureFilters(), filterOptions: this.data.filterOptions.map(option => ({ ...option, index: 0, value: '' })), }) return this.loadItems() }, onItemTap(e: WechatMiniprogram.CustomEvent) { const id = e.currentTarget.dataset.id as string if (id) { wx.navigateTo({ url: getArticleDetailUrl(id) }) } }, onImageError(e: WechatMiniprogram.CustomEvent) { const id = e.currentTarget.dataset.id as string this.setData({ [`failedImages.${id}`]: true }) }, onListScroll(e: WechatMiniprogram.CustomEvent) { // 保存实际滚动位置,搜索时设为 0 才能触发滚动复位。 this.data.scrollTop = e.detail.scrollTop }, onBack() { if (getCurrentPages().length > 1) { wx.navigateBack() } else { wx.switchTab({ url: '/pages/home/home' }) } }, })