"use client" import { useState, useRef, useEffect } from "react" import { Card, CardContent } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Badge } from "@/components/ui/badge" import { Input } from "@/components/ui/input" import { ScrollArea } from "@/components/ui/scroll-area" import { Bot, Send, User, Sparkles, Database, Tags, FileText, Download, Copy, ThumbsUp, ThumbsDown, Loader2, Zap, Search, BarChart3, Table, RefreshCw, } from "lucide-react" // 第四部分:AI Agent智能系统 - 智能对话 export default function AIAgentChatPage() { const [messages, setMessages] = useState([ { id: "1", role: "assistant", content: "您好!我是神射手AI Agent,可以帮您完成以下任务:\n\n- **自然语言查询**:用自然语言查询用户数据\n- **智能打标**:AI自动为用户打标签\n- **数据清洗**:AI识别并清洗异常数据\n- **智能报告**:自动生成数据分析报告\n\n请问有什么可以帮您?", timestamp: new Date(), }, ]) const [inputValue, setInputValue] = useState("") const [isLoading, setIsLoading] = useState(false) const scrollRef = useRef(null) // 快捷指令 const quickCommands = [ { icon: Search, label: "查询高价值用户", command: "帮我找出最近30天内消费超过1万元的高价值用户" }, { icon: Tags, label: "AI打标签", command: "为最近7天未登录的用户打上流失风险标签" }, { icon: Zap, label: "数据清洗", command: "检查用户表中的手机号格式,清洗异常数据" }, { icon: FileText, label: "生成报告", command: "生成本月用户增长分析报告" }, ] // 支持的指令类型 const supportedTasks = [ { type: "NLQ", label: "自然语言查询", desc: "用自然语言查询数据库", icon: Search }, { type: "TAG", label: "AI打标", desc: "智能为用户打标签", icon: Tags }, { type: "CLEAN", label: "数据清洗", desc: "AI识别清洗异常数据", icon: Zap }, { type: "REPORT", label: "智能报告", desc: "自动生成分析报告", icon: FileText }, ] useEffect(() => { if (scrollRef.current) { scrollRef.current.scrollTop = scrollRef.current.scrollHeight } }, [messages]) const handleSend = async () => { if (!inputValue.trim() || isLoading) return const userMessage = { id: Date.now().toString(), role: "user", content: inputValue, timestamp: new Date(), } setMessages((prev) => [...prev, userMessage]) setInputValue("") setIsLoading(true) try { // 调用真实的AI Chat API const response = await fetch("/api/ai-chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: userMessage.content }) }) const data = await response.json() let aiResponse: any = { id: (Date.now() + 1).toString(), role: "assistant", timestamp: new Date(), } if (data.success && data.response) { aiResponse.content = data.response.content // 如果有数据结果,添加表格展示 if (data.response.data && data.response.data.length > 0) { aiResponse.taskType = "NLQ" aiResponse.result = { type: "table", title: "查询结果", data: data.response.data.slice(0, 5).map((item: any, idx: number) => ({ id: idx + 1, name: item.name || item.姓名 || "-", phone: item.phone_masked || item.phone || "-", level: item.user_level || item.traffic_pool?.pool_name || "-", score: item.user_evaluation_score || item.rfm_composite_score || "-", })), total: data.response.data.length, } } } else { aiResponse.content = `⚠️ ${data.error || "查询失败,请重试"}` } setMessages((prev) => [...prev, aiResponse]) } catch (error: any) { setMessages((prev) => [...prev, { id: (Date.now() + 1).toString(), role: "assistant", content: `⚠️ 网络错误: ${error.message}`, timestamp: new Date(), }]) } finally { setIsLoading(false) } } const handleQuickCommand = (command: string) => { setInputValue(command) } const renderMessageContent = (message: any) => { return (

{message.content}

{message.result?.type === "table" && (

{message.result.title}

共 {message.result.total} 条
{message.result.sql}
{message.result.data.map((row: any, index: number) => ( ))}
ID 姓名 手机 消费金额 最近活跃
{row.id} {row.name} {row.phone} {row.spending} {row.lastActive}
)} {message.result?.type === "confirmation" && (

{message.result.title}

{message.result.description}

影响用户数:{message.result.affectedCount.toLocaleString()} 置信度:{(message.result.confidence * 100).toFixed(0)}%
{message.result.needReview && (
)}
)} {message.result?.type === "cleaning" && (

{message.result.title}

{message.result.issues.map((issue: any, index: number) => (
{issue.field} {issue.issue}
{issue.example && (

示例:{issue.example}

)} {issue.suggestion && (

建议:{issue.suggestion}

)}
{issue.count} 条
))}
)} {message.result?.type === "report" && (

{message.result.title}

{message.result.summary}

核心发现:

{message.result.highlights.map((highlight: string, index: number) => (
{highlight}
))}
)}
) } return (
{/* 左侧:功能面板 */}

AI能力

{supportedTasks.map((task) => (

{task.label}

{task.desc}

))}

快捷指令

{quickCommands.map((cmd, index) => ( ))}
{/* 中间:对话区域 */}
{/* 消息列表 */}
{messages.map((message) => (
{message.role === "user" ? ( ) : ( )}
{message.role === "user" ? (

{message.content}

) : ( renderMessageContent(message) )}
{message.role === "assistant" && (
)}
))} {isLoading && (
AI正在思考...
)}
{/* 输入区域 */}
setInputValue(e.target.value)} onKeyDown={(e) => e.key === "Enter" && !e.shiftKey && handleSend()} placeholder="输入您的问题,例如:帮我找出最近30天的高价值用户..." className="pr-12 py-6 bg-white" />

AI生成的内容可能存在误差,重要操作请人工确认

) }