This commit is contained in:
2026-06-30 10:39:29 +07:00
parent aaafa6ada9
commit d9c8e3930b
28 changed files with 3040 additions and 167 deletions

View File

@@ -0,0 +1,231 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { apiChat, type ChatConversation, type ChatMessage, type ChatStudent } from '../api';
import { useAuth } from '../auth/AuthContext';
export function ChatWidget() {
const { staff } = useAuth();
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
const [students, setStudents] = useState<ChatStudent[]>([]);
const [conversations, setConversations] = useState<ChatConversation[]>([]);
const [active, setActive] = useState<ChatStudent | null>(null);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [draft, setDraft] = useState('');
const [sending, setSending] = useState(false);
const [pickerOpen, setPickerOpen] = useState(false);
const listRef = useRef<HTMLDivElement>(null);
const activeRef = useRef<ChatStudent | null>(null);
useEffect(() => {
activeRef.current = active;
}, [active]);
const scrollBottom = () => {
requestAnimationFrame(() => {
if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
});
};
const totalUnread = conversations.reduce((n, c) => n + (c.unread || 0), 0);
const loadConversations = useCallback(async () => {
const res = await apiChat.listConversations();
setConversations(res.data);
}, []);
const loadMessages = useCallback(async (studentRkId: number) => {
const res = await apiChat.listMessages(studentRkId);
setMessages(res.data);
scrollBottom();
await loadConversations();
}, [loadConversations]);
const searchStudents = useCallback(async (q: string) => {
const res = await apiChat.searchStudents(q);
setStudents(res.data);
}, []);
const pickStudent = async (s: ChatStudent) => {
setActive(s);
setPickerOpen(false);
setQuery('');
await loadMessages(s.studentRkId);
};
const pickFromConversation = async (c: ChatConversation) => {
await pickStudent({
studentRkId: c.studentRkId,
fullName: c.fullName,
studentCode: c.studentCode,
email: '',
online: false,
});
};
useEffect(() => {
if (!open || !staff?.id) return;
loadConversations().catch(console.error);
searchStudents('').catch(console.error);
}, [open, staff?.id, loadConversations, searchStudents]);
useEffect(() => {
if (!staff?.id) return;
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.hostname}:8080/ws?role=teacher&staffId=${staff.id}`;
const ws = new WebSocket(wsUrl);
ws.onmessage = (ev) => {
try {
const payload = JSON.parse(ev.data);
if (payload.event !== 'chat:message') return;
const msg = payload.data as ChatMessage;
loadConversations().catch(console.error);
const current = activeRef.current;
if (current && msg.studentRkId === current.studentRkId) {
setMessages((prev) => {
if (prev.some((m) => m.id === msg.id)) return prev;
return [...prev, msg];
});
scrollBottom();
}
} catch {
/* ignore */
}
};
return () => ws.close();
}, [staff?.id, loadConversations]);
const send = async () => {
if (!active || !draft.trim()) return;
setSending(true);
try {
const res = await apiChat.sendMessage(active.studentRkId, draft.trim());
setMessages((prev) => [...prev, res.data]);
setDraft('');
scrollBottom();
await loadConversations();
} finally {
setSending(false);
}
};
if (!staff) return null;
const dock = (
<div className="chat-dock">
{!open ? (
<button type="button" className="chat-fab" onClick={() => setOpen(true)} title="Tin nhắn">
💬
{totalUnread > 0 && (
<span className="chat-fab-badge">{totalUnread > 9 ? '9+' : totalUnread}</span>
)}
</button>
) : (
<div className="chat-messenger">
<header className="chat-messenger-head">
<strong>Tin nhắn</strong>
<div className="chat-head-actions">
<button type="button" className="chat-icon-btn" onClick={() => setPickerOpen((v) => !v)} title="Tin mới">
</button>
<button type="button" className="chat-icon-btn" onClick={() => { setOpen(false); setActive(null); setPickerOpen(false); }} title="Đóng">
×
</button>
</div>
</header>
<div className="chat-messenger-body">
<aside className="chat-sidebar">
<div className="chat-sidebar-search">
<input
placeholder="Tìm sinh viên..."
value={query}
onChange={(e) => {
setQuery(e.target.value);
searchStudents(e.target.value).catch(console.error);
}}
onFocus={() => setPickerOpen(true)}
/>
</div>
{pickerOpen && (
<ul className="chat-picker-list">
{students.map((s) => (
<li key={s.studentRkId}>
<button type="button" onClick={() => pickStudent(s)}>
<span className="chat-conv-name">{s.fullName}</span>
<span className="chat-conv-meta">{s.studentCode}{s.online ? ' · online' : ''}</span>
</button>
</li>
))}
{students.length === 0 && <li className="chat-empty-hint">Không tìm thấy sinh viên</li>}
</ul>
)}
<ul className="chat-conv-list">
{conversations.map((c) => (
<li key={c.studentRkId}>
<button
type="button"
className={active?.studentRkId === c.studentRkId ? 'active' : ''}
onClick={() => pickFromConversation(c)}
>
<div className="chat-conv-row">
<span className="chat-conv-name">{c.fullName}</span>
{c.unread > 0 && <span className="chat-conv-unread">{c.unread}</span>}
</div>
<span className="chat-conv-preview">{c.lastMessage || '—'}</span>
<span className="chat-conv-meta">{c.studentCode}</span>
</button>
</li>
))}
{conversations.length === 0 && !pickerOpen && (
<li className="chat-empty-hint">Chưa hội thoại bấm đ nhắn sinh viên</li>
)}
</ul>
</aside>
<section className="chat-thread">
{!active ? (
<div className="chat-thread-empty">
<p>Chọn hội thoại bên trái hoặc tìm sinh viên đ bắt đu chat</p>
</div>
) : (
<>
<div className="chat-thread-head">
<div>
<strong>{active.fullName}</strong>
<div className="chat-sub">{active.studentCode}</div>
</div>
</div>
<div className="chat-messages" ref={listRef}>
{messages.map((m) => (
<div key={m.id} className={`chat-bubble chat-bubble--${m.senderRole}`}>
<div className="chat-bubble-body">{m.body}</div>
<div className="chat-bubble-time">
{new Date(m.createdAt).toLocaleString('vi-VN', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
</div>
</div>
))}
{messages.length === 0 && <div className="chat-empty-hint">Chưa tin nhắn</div>}
</div>
<div className="chat-compose">
<input
placeholder="Nhập tin nhắn..."
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
/>
<button type="button" className="btn btn-primary btn-sm" disabled={sending || !draft.trim()} onClick={send}>
Gửi
</button>
</div>
</>
)}
</section>
</div>
</div>
)}
</div>
);
return createPortal(dock, document.body);
}