'use client' import { useState } from 'react' import { useTranslation } from 'react-i18next' import { RiCheckDoubleLine, RiCheckLine, RiTimeLine } from '@remixicon/react' import { BellIcon } from '@heroicons/react/24/outline' import useSWR from 'swr' import { useRouter } from 'next/navigation' import classNames from '@/utils/classnames' import { formatDistanceToNow } from '@/utils/time' import { fetchNotifications, markNotificationsAsRead } from '@/service/notifications' import type { Notification } from '@/service/notifications' type NotificationPanelProps = { onClose: () => void onNotificationRead: () => void } const NotificationPanel = ({ onClose, onNotificationRead }: NotificationPanelProps) => { const { t } = useTranslation() const router = useRouter() const [filter, setFilter] = useState<'all' | 'unread'>('all') // 构建 SWR key,确保 filter 变化时触发重新请求 const swrKey = filter === 'unread' ? '/datasets/notifications?is_read=false' : '/datasets/notifications' // 获取通知列表 const { data, mutate } = useSWR( swrKey, fetchNotifications, { dedupingInterval: 0, revalidateOnFocus: false, onSuccess: (data) => { console.log('[NOTIFY-PANEL] Notifications data:', data) console.log('[NOTIFY-PANEL] Number of notifications:', data?.notifications?.length || 0) console.log('[NOTIFY-PANEL] Current filter:', filter) }, onError: (error) => { console.error('[NOTIFY-PANEL] Failed to fetch notifications:', error) }, }, ) const notifications = data?.notifications || [] const unreadCount = data?.unread_count || 0 // 标记单个通知为已读 const markAsRead = async (notificationId: string) => { try { await markNotificationsAsRead({ notification_ids: [notificationId], }) mutate() onNotificationRead() } catch (error) { console.error('Failed to mark notification as read:', error) } } // 标记全部为已读 const markAllAsRead = async () => { try { await markNotificationsAsRead({ mark_all_as_read: true, }) mutate() onNotificationRead() } catch (error) { console.error('Failed to mark all notifications as read:', error) } } // 点击通知 const handleNotificationClick = async (notification: Notification) => { // 如果未读,先标记为已读 if (!notification.is_read) await markAsRead(notification.id) // 跳转到对应页面 if (notification.link_url) { router.push(notification.link_url) onClose() } } return (
{filter === 'unread' ? t('common.notifications.noUnread') : t('common.notifications.noNotifications')}