'use client' import { useEffect, useRef, useState } from 'react' import { BellIcon as BellIconOutline } from '@heroicons/react/24/outline' import { BellIcon as BellIconSolid } from '@heroicons/react/24/solid' import useSWR from 'swr' import classNames from '@/utils/classnames' import { useAppContext } from '@/context/app-context' import { fetchUnreadCount } from '@/service/notifications' import NotificationPanel from './notification-panel' type NotificationsNavProps = { className?: string } const NotificationsNav = ({ className }: NotificationsNavProps) => { const [isOpen, setIsOpen] = useState(false) const panelRef = useRef(null) const buttonRef = useRef(null) const { userProfile } = useAppContext() // 调试:输出当前用户信息 useEffect(() => { if (userProfile?.id) { console.log('[NOTIFY] Current user:', { id: userProfile.id, name: userProfile.name, email: userProfile.email, }) } }, [userProfile]) // 获取未读通知数量 const { data: unreadData, mutate: mutateUnreadCount } = useSWR( '/datasets/notifications/unread-count', fetchUnreadCount, { refreshInterval: 30000, // 每30秒刷新一次 onSuccess: (data) => { console.log('[NOTIFY] Unread count data:', data) }, onError: (error) => { console.error('[NOTIFY] Failed to fetch unread count:', error) }, }, ) const unreadCount = unreadData?.unread_count || 0 // 点击外部关闭面板 useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if ( panelRef.current && !panelRef.current.contains(event.target as Node) && buttonRef.current && !buttonRef.current.contains(event.target as Node) ) setIsOpen(false) } if (isOpen) { document.addEventListener('mousedown', handleClickOutside) return () => { document.removeEventListener('mousedown', handleClickOutside) } } }, [isOpen]) const handleToggle = () => { setIsOpen(!isOpen) } const handleNotificationRead = () => { // 重新获取未读数量 mutateUnreadCount() } return (
{/* 未读数量徽章 */} {unreadCount > 0 && (
{unreadCount > 99 ? '99+' : unreadCount}
)} {/* 铃铛图标 */} {isOpen ? : }
{/* 通知面板 */} {isOpen && (
setIsOpen(false)} onNotificationRead={handleNotificationRead} />
)}
) } export default NotificationsNav