Files
zt-closet-wxmini-frontend/miniprogram/pages/notification/notification.ts
T

92 lines
2.7 KiB
TypeScript

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'
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,
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)
const tabBar = (this as any).getTabBar && (this as any).getTabBar()
// 直接更新红点,避免 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) return
this.fetchList(this.data.page + 1)
},
fetchList(page: number) {
const params: Record<string, any> = { page, page_size: this.data.pageSize }
const filter = this.data.activeFilter
if (filter > 0) params.msg_type = filter
request<PagedResult<NotificationItem>>({ url: '/notification', data: params })
.then((res) => {
const list = res.list.map((it) => ({ ...it, _time: formatRelativeTime(it.created_at) }))
const merged = page === 1 ? list : this.data.list.concat(list)
this.setData({
list: merged,
hasMore: merged.length < res.total,
loading: false,
page,
})
})
.catch(() => this.setData({ loading: 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}` })
},
})