'use client'; import { useCallback, useEffect, useState } from 'react'; interface AIComment { id: string; userName: string; userAvatar: string; rating: number | null; content: string; time: string; votes: number; isAiGenerated: true; } interface AICommentsProps { movieName: string; movieInfo?: string; } export default function AIComments({ movieName, movieInfo }: AICommentsProps) { const [comments, setComments] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [hasStartedLoading, setHasStartedLoading] = useState(false); const fetchComments = useCallback(async () => { try { console.log('正在生成AI评论...'); setLoading(true); setError(null); const params = new URLSearchParams({ name: movieName, count: '10', _t: Date.now().toString(), // 添加时间戳防止缓存 }); if (movieInfo) { params.append('info', movieInfo); } const response = await fetch(`/api/ai-comments?${params.toString()}`, { cache: 'no-store', // 禁用缓存 }); if (!response.ok) { const data = await response.json(); throw new Error(data.error || '生成AI评论失败'); } const data = await response.json(); console.log('AI评论生成成功:', data.comments.length); setComments(data.comments); } catch (err) { console.error('生成AI评论失败:', err); setError(err instanceof Error ? err.message : '生成AI评论失败'); } finally { setLoading(false); } }, [movieName, movieInfo]); useEffect(() => { // 重置状态当 movieName 变化时 setHasStartedLoading(false); setComments([]); setLoading(false); setError(null); }, [movieName]); const startLoading = () => { console.log('开始生成AI评论'); setHasStartedLoading(true); fetchComments(); }; const regenerate = () => { console.log('重新生成AI评论'); fetchComments(); }; // 星级渲染 const renderStars = (rating: number | null) => { if (rating === null) return null; return (
{[1, 2, 3, 4, 5].map((star) => ( ))}
); }; // 初始状态:显示生成按钮 if (!hasStartedLoading) { return (

点击生成AI评论

基于影片信息和网络资料生成

); } if (loading && comments.length === 0) { return (
AI正在生成评论... 这可能需要几秒钟
); } if (error && comments.length === 0) { return (

{error}

请检查管理面板的AI配置是否正确

); } return (
{/* 头部统计和操作 */}
已生成 {comments.length} 条AI评论
{/* 评论列表 */}
{comments.map((comment) => (
{/* 用户信息 */}
{/* 头像 */}
{comment.userName}
{/* 用户名和评分 */}
{comment.userName} {renderStars(comment.rating)} {/* AI标识 */} AI生成
{/* 时间 */}
{comment.time}
{/* 有用数 */} {comment.votes > 0 && (
{comment.votes}
)}
{/* 评论内容 */}
{comment.content}
))}
{/* 提示信息 */}
以上评论由AI基于影片信息和网络资料生成,仅供参考
); }