import { defineStore } from 'pinia' import { ref } from 'vue' import { ElMessage } from 'element-plus' import type { PageResult } from '@/types/api' import type { Message, MessageQuery } from '@/types/business/message' import { getMessageDetail, getMessageList, getTabCounts, getUnreadCount, markAllRead as markAllReadApi, markRead as markReadApi, } from '@/api/message' /** tab 计数结构 */ export interface MessageTabCounts { all: number 在线客服: number 状态通知: number 系统通知: number } function createDefaultQuery(): MessageQuery { return { keyword: '', type: 'all', page: 1, pageSize: 10, } } /** 消息中心数据(列表 / 筛选 / 分页 / 已读) */ export const useMessageStore = defineStore('message', () => { const query = ref(createDefaultQuery()) const list = ref([]) const total = ref(0) const current = ref(null) const unreadCount = ref(0) const tabCounts = ref({ all: 0, 在线客服: 0, 状态通知: 0, 系统通知: 0 }) async function fetchList(): Promise { const result: PageResult = await getMessageList(query.value) list.value = result.list total.value = result.total } async function fetchDetail(id: string): Promise { const detail = await getMessageDetail(id) current.value = detail if (detail && !detail.isRead) { await markReadApi(id) detail.isRead = true if (unreadCount.value > 0) unreadCount.value -= 1 await fetchTabCounts() } } function setQuery(next: MessageQuery): void { query.value = next } /** 确定搜索(重置页码后取数) */ async function search(): Promise { query.value = { ...query.value, page: 1 } await fetchList() } /** 重置全部条件 */ async function resetQuery(): Promise { query.value = createDefaultQuery() await fetchList() } async function changePage(page: number): Promise { query.value = { ...query.value, page } await fetchList() } /** 全部标记已读 */ async function markAllRead(): Promise { await markAllReadApi() ElMessage.success('已全部标记为已读') await Promise.all([fetchList(), fetchUnreadCount(), fetchTabCounts()]) if (current.value) current.value.isRead = true } async function fetchUnreadCount(): Promise { unreadCount.value = await getUnreadCount() } async function fetchTabCounts(): Promise { tabCounts.value = await getTabCounts() } return { query, list, total, current, unreadCount, tabCounts, fetchList, fetchDetail, setQuery, search, resetQuery, changePage, markAllRead, fetchUnreadCount, fetchTabCounts, } })