import React, { useState, useEffect, useCallback } from 'react' import { getComments, addComment, replyComment, deleteComment as apiDeleteComment, type CommentOut, } from '../api' import { useToast } from './Toast' import { useTranslation } from '../i18n' import { useDateFormatter } from '../utils/dateUtils' interface CommentSectionProps { consultationId: string } export default function CommentSection({ consultationId }: CommentSectionProps) { const toast = useToast() const { t } = useTranslation() const { formatDateTime } = useDateFormatter() const [comments, setComments] = useState([]) const [total, setTotal] = useState(0) const [loading, setLoading] = useState(true) const [newComment, setNewComment] = useState('') const [submitting, setSubmitting] = useState(false) const [replyingTo, setReplyingTo] = useState(null) const [replyContent, setReplyContent] = useState('') const [replySubmitting, setReplySubmitting] = useState(false) const [deletingId, setDeletingId] = useState(null) const loadComments = useCallback(async () => { try { const data = await getComments(consultationId) setComments(data.comments) setTotal(data.total) } catch { // 静默失败 } finally { setLoading(false) } }, [consultationId]) useEffect(() => { loadComments() }, [loadComments]) const handleAddComment = async () => { const trimmed = newComment.trim() if (!trimmed || submitting) return setSubmitting(true) try { await addComment(consultationId, trimmed) setNewComment('') toast.success(t('components.comment.posted')) await loadComments() } catch (e: any) { toast.error(e?.message || t('components.comment.postFailed')) } finally { setSubmitting(false) } } const handleReply = async (commentId: string) => { const trimmed = replyContent.trim() if (!trimmed || replySubmitting) return setReplySubmitting(true) try { await replyComment(consultationId, commentId, trimmed) setReplyContent('') setReplyingTo(null) toast.success(t('components.comment.replyPosted')) await loadComments() } catch (e: any) { toast.error(e?.message || t('components.comment.replyFailed')) } finally { setReplySubmitting(false) } } const handleDelete = async (commentId: string) => { if (!window.confirm(t('components.comment.confirmDelete'))) return setDeletingId(commentId) try { await apiDeleteComment(consultationId, commentId) toast.success(t('components.comment.deleted')) await loadComments() } catch (e: any) { toast.error(e?.message || t('components.comment.deleteFailed')) } finally { setDeletingId(null) } } const formatTime = (iso: string) => { try { return formatDateTime(iso) } catch { return iso } } if (loading) { return (
{t('components.comment.loading')}
) } return (

{t('components.comment.title')} ({total})

{/* 新增评论 */}