import { request, redirectToLogin } from '../../utils/request' import * as auth from '../../utils/auth' import { PagedResult, NotificationItem } from '../../types/models' import { STORAGE_KEYS } from '../../utils/config' import { formatRelativeTime } from '../../utils/format' import { normalizePaged, mergePaged, hasMorePaged } from '../../utils/paged' import { getTabBarInstance } from '../../utils/tabbar' const FILTERS = [ { name: '全部', value: 0 }, { name: '点赞', value: 1 }, { name: '订单', value: 2 }, { name: '系统', value: 3 }, ] Page({ data: { filters: FILTERS, activeFilter: 0, list: [] as NotificationItem[], loading: true, loadingMore: false, page: 1, pageSize: 20, hasMore: true, }, onShow() { // 未登录直接回登录页(幂等跳转),不再发出必然 401 的请求 if (!auth.isLoggedIn()) { redirectToLogin() return } this.refresh() this.fetchUnread() }, fetchUnread() { request<{ unread_count: number }>({ url: '/notification/unread', showError: false, silentAuth: true, }) .then((res) => { const unread = res.unread_count || 0 wx.setStorageSync(STORAGE_KEYS.UNREAD, unread) // 本页不是 tab 页,getTabBar() 恒为 undefined,需从页面栈里取 tab 页的 tabBar const tabBar = getTabBarInstance() // 直接更新红点,避免 tabBar 内部再发一次请求 if (tabBar && tabBar.setUnread) tabBar.setUnread(unread) }) .catch(() => {}) }, refresh() { this.setData({ page: 1, hasMore: true, loading: this.data.list.length === 0 }) this.fetchList(1) }, onReachBottom() { if (!this.data.hasMore || this.data.loading || this.data.loadingMore) return this.fetchList(this.data.page + 1) }, fetchList(page: number) { const params: Record = { page, page_size: this.data.pageSize } const filter = this.data.activeFilter if (filter > 0) params.msg_type = filter // 请求序号:切换筛选时旧响应可能后到,序号不匹配直接丢弃 const seq = ((this as any).reqSeq || 0) + 1 ;(this as any).reqSeq = seq if (page > 1) this.setData({ loadingMore: true }) request>({ url: '/notification', data: params }) .then((res) => { if ((this as any).reqSeq !== seq) return const { list: raw, total } = normalizePaged(res) const list = raw.map((it) => ({ ...it, _time: formatRelativeTime(it.created_at) })) const merged = mergePaged(this.data.list, list, page === 1) this.setData({ list: merged, hasMore: hasMorePaged(merged, total, this.data.pageSize), loading: false, loadingMore: false, page, }) }) .catch(() => { if ((this as any).reqSeq !== seq) return this.setData({ loading: false, loadingMore: false }) }) }, onFilterTap(e: WechatMiniprogram.TouchEvent) { const index = Number(e.currentTarget.dataset.index) if (index === this.data.activeFilter) return this.setData({ activeFilter: index, list: [], loading: true }) this.refresh() }, onItemTap(e: WechatMiniprogram.TouchEvent) { const uuid = e.currentTarget.dataset.uuid as string wx.navigateTo({ url: `/pages/notification-detail/notification-detail?uuid=${uuid}` }) }, })