notification.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { defineStore } from 'pinia';
  2. import { ref, computed } from 'vue';
  3. export interface Notification {
  4. id: string;
  5. type: 'audio_complete' | 'video_complete' | 'content_complete' | 'error';
  6. title: string;
  7. message: string;
  8. bookId?: string | number;
  9. timestamp: number;
  10. read: boolean;
  11. }
  12. const STORAGE_KEY = 'app_notifications';
  13. function loadFromStorage(): Notification[] {
  14. try {
  15. const data = uni.getStorageSync(STORAGE_KEY);
  16. return data ? JSON.parse(data) : [];
  17. } catch {
  18. return [];
  19. }
  20. }
  21. function saveToStorage(notifications: Notification[]) {
  22. try {
  23. uni.setStorageSync(STORAGE_KEY, JSON.stringify(notifications));
  24. } catch (e) {
  25. console.error('[Notification] 保存失败:', e);
  26. }
  27. }
  28. export const useNotificationStore = defineStore('notification', () => {
  29. const notifications = ref<Notification[]>(loadFromStorage());
  30. const unreadCount = computed(() => notifications.value.filter(n => !n.read).length);
  31. function add(notif: Omit<Notification, 'id' | 'timestamp' | 'read'>) {
  32. const id = `notif_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`;
  33. const notification: Notification = {
  34. ...notif,
  35. id,
  36. timestamp: Date.now(),
  37. read: false,
  38. };
  39. notifications.value.unshift(notification);
  40. // 最多保留 50 条
  41. if (notifications.value.length > 50) {
  42. notifications.value = notifications.value.slice(0, 50);
  43. }
  44. saveToStorage(notifications.value);
  45. }
  46. function markRead(id: string) {
  47. const n = notifications.value.find(item => item.id === id);
  48. if (n) {
  49. n.read = true;
  50. saveToStorage(notifications.value);
  51. }
  52. }
  53. function markAllRead() {
  54. notifications.value.forEach(n => { n.read = true; });
  55. saveToStorage(notifications.value);
  56. }
  57. function remove(id: string) {
  58. notifications.value = notifications.value.filter(n => n.id !== id);
  59. saveToStorage(notifications.value);
  60. }
  61. function clear() {
  62. notifications.value = [];
  63. saveToStorage(notifications.value);
  64. }
  65. return {
  66. notifications,
  67. unreadCount,
  68. add,
  69. markRead,
  70. markAllRead,
  71. remove,
  72. clear,
  73. };
  74. });