import { getItemSync, setItemSync } from '@/utils/kvStore'; import * as Notifications from 'expo-notifications'; const CLEANUP_KEY = 'medication_notifications_cleaned_v1'; /** * 清理所有旧的药品本地通知 * 这个函数会在应用启动时执行一次,用于清理从本地通知迁移到服务端推送之前注册的所有药品通知 */ export async function cleanupLegacyMedicationNotifications(): Promise { try { // 检查是否已经执行过清理 const alreadyCleaned = getItemSync(CLEANUP_KEY); if (alreadyCleaned === 'true') { console.log('[药品通知清理] 已执行过清理,跳过'); return; } console.log('[药品通知清理] 开始清理旧的药品本地通知...'); // 获取所有已安排的通知 const scheduledNotifications = await Notifications.getAllScheduledNotificationsAsync(); if (scheduledNotifications.length === 0) { console.log('[药品通知清理] 没有待清理的通知'); setItemSync(CLEANUP_KEY, 'true'); return; } console.log(`[药品通知清理] 发现 ${scheduledNotifications.length} 个已安排的通知,开始筛选药品通知...`); // 筛选出药品相关的通知并取消 let cleanedCount = 0; for (const notification of scheduledNotifications) { const data = notification.content.data; // 识别药品通知的特征: // 1. data.type === 'medication_reminder' // 2. data.medicationId 存在 // 3. identifier 包含 'medication' 关键字 const isMedicationNotification = data?.type === 'medication_reminder' || data?.medicationId || notification.identifier?.includes('medication'); if (isMedicationNotification) { try { await Notifications.cancelScheduledNotificationAsync(notification.identifier); cleanedCount++; console.log(`[药品通知清理] 已取消通知: ${notification.identifier}`); } catch (error) { console.error(`[药品通知清理] 取消通知失败: ${notification.identifier}`, error); } } } console.log(`[药品通知清理] ✅ 清理完成,共取消 ${cleanedCount} 个药品通知`); // 标记清理已完成 setItemSync(CLEANUP_KEY, 'true'); } catch (error) { console.error('[药品通知清理] ❌ 清理过程出错:', error); // 即使出错也标记为已清理,避免每次启动都尝试 setItemSync(CLEANUP_KEY, 'true'); } }