File size: 11,113 Bytes
793e953
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
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<CommentOut[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(true)
  const [newComment, setNewComment] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [replyingTo, setReplyingTo] = useState<string | null>(null)
  const [replyContent, setReplyContent] = useState('')
  const [replySubmitting, setReplySubmitting] = useState(false)
  const [deletingId, setDeletingId] = useState<string | null>(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 (
      <div className="card p-4 md:p-6 max-w-3xl mx-auto mt-6">
        <div className="text-center text-gray-400 text-sm py-4">{t('components.comment.loading')}</div>
      </div>
    )
  }

  return (
    <div className="card p-4 md:p-6 max-w-3xl mx-auto mt-6">
      <h4 className="text-sm font-bold text-gray-700 mb-4 flex items-center gap-2">
        <svg className="w-5 h-5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
        </svg>
        {t('components.comment.title')} ({total})
      </h4>

      {/* 新增评论 */}
      <div className="mb-4">
        <div className="flex gap-2">
          <textarea
            className="flex-1 text-sm border border-gray-200 rounded-lg px-3 py-2 focus:ring-2 focus:ring-medical-500 focus:border-medical-500 outline-none resize-none min-h-[44px]"
            placeholder={t('components.comment.placeholder')}
            value={newComment}
            onChange={(e) => setNewComment(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault()
                handleAddComment()
              }
            }}
            rows={2}
          />
          <button
            onClick={handleAddComment}
            disabled={submitting || !newComment.trim()}
            className="btn-primary text-xs px-4 py-2 min-h-[44px] disabled:opacity-50 shrink-0"
          >
            {submitting ? t('components.comment.sending') : t('components.comment.send')}
          </button>
        </div>
      </div>

      {/* 评论列表 */}
      {comments.length === 0 ? (
        <div className="text-center text-gray-400 text-sm py-6">{t('components.comment.noComments')}</div>
      ) : (
        <div className="space-y-3">
          {comments.map((comment) => (
            <CommentItem
              key={comment.id}
              comment={comment}
              consultationId={consultationId}
              replyingTo={replyingTo}
              replyContent={replyContent}
              replySubmitting={replySubmitting}
              deletingId={deletingId}
              onReplyClick={(id) => {
                setReplyingTo(id)
                setReplyContent('')
              }}
              onReplyCancel={() => setReplyingTo(null)}
              onReplyChange={setReplyContent}
              onReplySubmit={handleReply}
              onDelete={handleDelete}
              formatTime={formatTime}
              depth={0}
            />
          ))}
        </div>
      )}
    </div>
  )
}

// ================================================================
// 单个评论(递归渲染回复)
// ================================================================

function CommentItem({
  comment,
  consultationId,
  replyingTo,
  replyContent,
  replySubmitting,
  deletingId,
  onReplyClick,
  onReplyCancel,
  onReplyChange,
  onReplySubmit,
  onDelete,
  formatTime,
  depth,
}: {
  comment: CommentOut
  consultationId: string
  replyingTo: string | null
  replyContent: string
  replySubmitting: boolean
  deletingId: string | null
  onReplyClick: (id: string) => void
  onReplyCancel: () => void
  onReplyChange: (v: string) => void
  onReplySubmit: (id: string) => void
  onDelete: (id: string) => void
  formatTime: (iso: string) => string
  depth: number
}) {
  const { t } = useTranslation()
  const isDeleting = deletingId === comment.id
  const maxDepth = 4 // 最大嵌套层级

  return (
    <div className={`${depth > 0 ? 'ml-6 border-l-2 border-gray-100 pl-3' : ''}`}>
      <div className={`rounded-lg p-3 ${comment.is_deleted ? 'bg-gray-50' : 'bg-gray-50/50'}`}>
        {/* 头像 + 信息 + 时间 */}
        <div className="flex items-start gap-2 mb-1">
          {/* 头像 */}
          <div className="w-7 h-7 rounded-full bg-medical-100 text-medical-700 flex items-center justify-center text-xs font-bold shrink-0">
            {comment.user?.nickname?.charAt(0) || '?'}
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="text-xs font-medium text-gray-700">
                {comment.is_deleted ? t('components.comment.deleted') : comment.user?.nickname || t('components.comment.anonymous')}
              </span>
              <span className="text-[10px] text-gray-400">
                {formatTime(comment.created_at)}
              </span>
              {comment.is_deleted && (
                <span className="text-[10px] text-gray-400 italic">{t('components.comment.deletedByAuthor')}</span>
              )}
            </div>
            {/* 内容 */}
            <p className="text-sm text-gray-700 mt-1 whitespace-pre-wrap break-words">
              {comment.content}
            </p>
          </div>
        </div>

        {/* 操作按钮 */}
        {!comment.is_deleted && (
          <div className="flex gap-3 ml-9">
            {depth < maxDepth && (
              <button
                onClick={() => onReplyClick(comment.id)}
                className="text-[11px] text-gray-400 hover:text-medical-600 transition-colors"
              >
                {t('components.comment.reply')}
              </button>
            )}
            <button
              onClick={() => onDelete(comment.id)}
              disabled={isDeleting}
              className="text-[11px] text-gray-400 hover:text-red-500 transition-colors disabled:opacity-50"
            >
              {isDeleting ? t('components.comment.deleting') : t('components.comment.delete')}
            </button>
          </div>
        )}

        {/* 回复输入框 */}
        {replyingTo === comment.id && (
          <div className="ml-9 mt-2 flex gap-2">
            <textarea
              className="flex-1 text-xs border border-gray-200 rounded-lg px-3 py-1.5 focus:ring-2 focus:ring-medical-500 focus:border-medical-500 outline-none resize-none min-h-[32px]"
              placeholder={t('components.comment.replyPlaceholder')}
              value={replyContent}
              onChange={(e) => onReplyChange(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault()
                  onReplySubmit(comment.id)
                }
              }}
              rows={2}
              autoFocus
            />
            <div className="flex flex-col gap-1">
              <button
                onClick={() => onReplySubmit(comment.id)}
                disabled={replySubmitting || !replyContent.trim()}
                className="btn-primary text-[10px] px-2 py-1 min-h-[28px] disabled:opacity-50"
              >
                {t('components.comment.reply')}
              </button>
              <button
                onClick={onReplyCancel}
                className="text-[10px] text-gray-400 hover:text-gray-600 min-h-[24px]"
              >
                {t('components.comment.cancel')}
              </button>
            </div>
          </div>
        )}
      </div>

      {/* 递归渲染子回复 */}
      {comment.replies && comment.replies.length > 0 && (
        <div className="mt-1">
          {comment.replies.map((reply) => (
            <CommentItem
              key={reply.id}
              comment={reply}
              consultationId={consultationId}
              replyingTo={replyingTo}
              replyContent={replyContent}
              replySubmitting={replySubmitting}
              deletingId={deletingId}
              onReplyClick={onReplyClick}
              onReplyCancel={onReplyCancel}
              onReplyChange={onReplyChange}
              onReplySubmit={onReplySubmit}
              onDelete={onDelete}
              formatTime={formatTime}
              depth={depth + 1}
            />
          ))}
        </div>
      )}
    </div>
  )
}