import { http } from '@/common/service/service.js' import { ACCESS_TOKEN } from '@/common/util/constants.js' /** 消息 tab 在 tabBar.list 中的下标 */ export const MSG_TAB_INDEX = 2 /** 是否未读:status === '0' */ export function isUnreadNotice(item) { return item && String(item.status) === '0' } /** * 设置消息 tab 角标(仅未读;已读不显示) * @param {number|string} count 未读数 */ export function setMsgTabBadge(count) { const n = Number(count) || 0 if (n > 0) { uni.setTabBarBadge({ index: MSG_TAB_INDEX, text: n > 99 ? '99+' : String(n), fail: () => {} }) } else { uni.removeTabBarBadge({ index: MSG_TAB_INDEX, fail: () => {} }) uni.hideTabBarRedDot({ index: MSG_TAB_INDEX, fail: () => {} }) } } /** * 从分类列表统计未读数(不含已读) */ function countUnreadFromList(list) { const unread = (list || []).filter(isUnreadNotice) if (!unread.length) return 0 const hasCount = unread.some( (i) => i.unreadCount != null || i.unReadCount != null ) if (hasCount) { return unread.reduce( (sum, i) => sum + Number(i.unreadCount || i.unReadCount || 0), 0 ) } return unread.length } /** * 拉取未读消息数并更新消息 tab 角标(只统计没看过的) */ export function updateMsgTabBadge() { const token = uni.getStorageSync(ACCESS_TOKEN) if (!token) { setMsgTabBadge(0) return Promise.resolve(0) } // 先按未读拉分页,客户端再过滤一次,避免拿到已读/总数据 return http .post('/localUserNotice/localUserNotice/getPageListNew', { pageNo: 1, pageSize: 200, userType: 1, status: '0' }) .then((res) => { const result = (res.data && res.data.result) || {} const records = Array.isArray(result.records) ? result.records : result.page && Array.isArray(result.page.records) ? result.page.records : [] const unreadRecords = records.filter(isUnreadNotice) // 若返回记录全是未读,且接口给了 total,可用 total;否则只用未读条数 const allUnread = records.length > 0 && unreadRecords.length === records.length const apiTotal = result.total != null ? result.total : result.page && result.page.total != null ? result.page.total : null let count = unreadRecords.length if (allUnread && apiTotal != null && Number(apiTotal) >= count) { count = Number(apiTotal) } setMsgTabBadge(count) return count }) .catch(() => { return http .get('/localUserNotice/localUserNotice/getListNew', { params: { userType: 1 } }) .then((res) => { const count = countUnreadFromList( (res.data && res.data.result) || [] ) setMsgTabBadge(count) return count }) .catch(() => { setMsgTabBadge(0) return 0 }) }) }