serviceCenterNoticeService.js 2.5 KB
/**
 * 服务中心公告:角标拉取(TTL + in-flight)与首条未读(status:0,无本地门禁)
 */
import { noticeSort } from './enum/serviceCenter.js'

const CACHE_TTL_MS = 60 * 1000
let unreadCache = { value: null, ts: 0, pending: null }
let popupProbeCache = { value: null, ts: 0, pending: null }
let listApiOverride = null

function getListApi() {
	if (listApiOverride) return listApiOverride
	const mod = require('~/api/serviceCenter/index')
	return mod.getCompanyNoticeList
}

function readCacheEntry(entry) {
	if (entry.value === null) return null
	if (Date.now() - entry.ts > CACHE_TTL_MS) {
		entry.value = null
		entry.ts = 0
		return null
	}
	return entry.value
}

async function probeNoticeLists() {
	const cached = readCacheEntry(popupProbeCache)
	if (cached) return cached

	if (popupProbeCache.pending) return popupProbeCache.pending

	const getCompanyNoticeList = getListApi()
	popupProbeCache.pending = (async () => {
		const probes = []
		for (const moduleType of noticeSort) {
			const { data } = await getCompanyNoticeList({
				pageNum: 1,
				pageSize: 3,
				createdTimeSortType: 0,
				moduleType,
				status: 0
			})
			const list = data?.list || []
			probes.push({ moduleType, list, unreadCount: list.length })
		}
		popupProbeCache.value = probes
		popupProbeCache.ts = Date.now()
		return probes
	})()

	try {
		return await popupProbeCache.pending
	} finally {
		popupProbeCache.pending = null
	}
}

export async function fetchServiceCenterUnread() {
	const cached = readCacheEntry(unreadCache)
	if (cached !== null) return cached

	if (unreadCache.pending) return unreadCache.pending

	unreadCache.pending = (async () => {
		const probes = await probeNoticeLists()
		let count = 0
		for (const p of probes) {
			if (p.unreadCount > 0) {
				count = p.unreadCount
				break
			}
		}
		unreadCache.value = count
		unreadCache.ts = Date.now()
		return count
	})()

	try {
		return await unreadCache.pending
	} finally {
		unreadCache.pending = null
	}
}

/** 按 noticeSort 返回首条未读公告(V5.8.1:有未读即弹,依赖服务端 status) */
export async function resolveFirstUnreadNotice() {
	const probes = await probeNoticeLists()
	for (const { moduleType, list } of probes) {
		if (!list?.length) continue
		return { moduleType, noticeItem: list[0] }
	}
	return null
}

export function clearServiceCenterNoticeCache() {
	unreadCache = { value: null, ts: 0, pending: null }
	popupProbeCache = { value: null, ts: 0, pending: null }
}

export function __setListApiForTest(fn) {
	listApiOverride = fn
}