import React, { useEffect, useState } from 'react';
import { message, Modal, Form, Input, Button, Select } from 'antd';
import { useNavigate } from 'react-router-dom';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import useAuthStore from '../store/authStore';
import api from '../services/api';
import ChatAssistant from '../components/ChatAssistant';
import './AdminDashboard.css';

const { TextArea } = Input;

const AdminDashboard = () => {
  const navigate = useNavigate();
  const { user, logout, token } = useAuthStore();
  const [activeNav, setActiveNav] = useState('users');
  
  // 数据状态
  const [users, setUsers] = useState([]);
  const [chatLogs, setChatLogs] = useState([]);
  const [models, setModels] = useState([]);
  const [tools, setTools] = useState([]);
  const [employees, setEmployees] = useState([]);
  const [stats, setStats] = useState({});
  const [hourlyData, setHourlyData] = useState([]);
  const [riskData, setRiskData] = useState([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [chatSearchKeyword, setChatSearchKeyword] = useState('');
  const [chatSenderFilter, setChatSenderFilter] = useState('');
  const [chatStatusFilter, setChatStatusFilter] = useState('');
  const [analyzeProgress, setAnalyzeProgress] = useState(null);
  const [analyzingMessages, setAnalyzingMessages] = useState([]);
  const [aiToolProgress, setAiToolProgress] = useState(null);
  const [generatedTool, setGeneratedTool] = useState(null);
  const [toolCallLogs, setToolCallLogs] = useState([]);
  const [toolCallStats, setToolCallStats] = useState({});
  const [selectedTool, setSelectedTool] = useState(null);
  const [generatingPrompt, setGeneratingPrompt] = useState(false);
  const [selectedLogDetail, setSelectedLogDetail] = useState(null);
  const [isLogDetailModalVisible, setIsLogDetailModalVisible] = useState(false);
  
  // Modal 状态
  const [isUserModalVisible, setIsUserModalVisible] = useState(false);
  const [isUserEditModalVisible, setIsUserEditModalVisible] = useState(false);
  const [isModelModalVisible, setIsModelModalVisible] = useState(false);
  const [isToolModalVisible, setIsToolModalVisible] = useState(false);
  const [isAiToolModalVisible, setIsAiToolModalVisible] = useState(false);
  const [isEmployeeModalVisible, setIsEmployeeModalVisible] = useState(false);
  const [isUserDetailVisible, setIsUserDetailVisible] = useState(false);
  const [isAnalyzeModalVisible, setIsAnalyzeModalVisible] = useState(false);
  const [isToolLogsModalVisible, setIsToolLogsModalVisible] = useState(false);
  const [selectedUser, setSelectedUser] = useState(null);
  const [editingItem, setEditingItem] = useState(null);
  
  // Form 实例
  const [userForm] = Form.useForm();
  const [userEditForm] = Form.useForm();
  const [modelForm] = Form.useForm();
  const [toolForm] = Form.useForm();
  const [aiToolForm] = Form.useForm();
  const [employeeForm] = Form.useForm();
  const [analyzeForm] = Form.useForm();

  useEffect(() => {
    if (!token) { navigate('/login'); return; }
    fetchStats();
    fetchUsers();
  }, [token, navigate]);

  const fetchStats = async () => {
    try {
      const res = await api.get('/admin/dashboard-stats');
      setStats(res.data);
    } catch (e) { message.error('获取统计数据失败'); }
  };

  const fetchUsers = async (search = '') => {
    try {
      const params = search ? { search } : {};
      const res = await api.get('/admin/users', { params });
      setUsers(res.data);
    } catch (e) { message.error('获取用户列表失败'); }
  };

  const handleSearch = () => {
    fetchUsers(searchKeyword);
  };

  const handleSearchKeyDown = (e) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  const handleResetSearch = () => {
    setSearchKeyword('');
    fetchUsers('');
  };

  const fetchChatLogs = async (search = '', sender = '', status = '') => {
    try {
      const params = {};
      if (search) params.search = search;
      if (sender) params.sender_name = sender;
      if (status !== '') params.is_sensitive = status === 'sensitive';
      
      const res = await api.get('/admin/chat-logs', { params });
      setChatLogs(res.data);
    } catch (e) { message.error('获取聊天记录失败'); }
  };

  const handleChatSearch = () => {
    fetchChatLogs(chatSearchKeyword, chatSenderFilter, chatStatusFilter);
  };

  const handleChatReset = () => {
    setChatSearchKeyword('');
    setChatSenderFilter('');
    setChatStatusFilter('');
    fetchChatLogs('', '', '');
  };

  const fetchModels = async () => {
    try {
      const res = await api.get('/ai-agents/models');
      setModels(res.data);
    } catch (e) { message.error('获取模型列表失败'); }
  };

  const fetchTools = async () => {
    try {
      const res = await api.get('/ai-agents/tools');
      setTools(res.data);
    } catch (e) { message.error('获取工具列表失败'); }
  };

  const fetchEmployees = async () => {
    try {
      const res = await api.get('/ai-agents/employees');
      setEmployees(res.data);
    } catch (e) { message.error('获取数字员工列表失败'); }
  };

  const fetchAnalytics = async () => {
    try {
      const [hourlyRes, riskRes] = await Promise.all([
        api.get('/admin/analytics/hourly'),
        api.get('/admin/analytics/risk-distribution')
      ]);
      setHourlyData(hourlyRes.data);
      setRiskData(riskRes.data);
    } catch (e) { message.error('获取分析数据失败'); }
  };

  // 用户管理
  const handleCreateUser = async (values) => {
    try {
      await api.post('/admin/users', values);
      message.success('用户创建成功');
      setIsUserModalVisible(false);
      userForm.resetFields();
      fetchUsers();
      fetchStats();
    } catch (e) {
      message.error(e.response?.data?.detail || '创建用户失败');
    }
  };

  const handleToggleUserStatus = async (userId, currentStatus) => {
    try {
      await api.put(`/admin/users/${userId}/status?is_active=${!currentStatus}`);
      message.success('用户状态已更新');
      fetchUsers();
    } catch (e) {
      message.error(e.response?.data?.detail || '更新状态失败');
    }
  };

  const handleDeleteUser = async (userId) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个用户吗？此操作不可恢复。',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await api.delete(`/admin/users/${userId}`);
          message.success('用户已删除');
          fetchUsers();
          fetchStats();
        } catch (e) {
          message.error(e.response?.data?.detail || '删除用户失败');
        }
      }
    });
  };

  const handleViewUserDetail = async (userId) => {
    try {
      const res = await api.get(`/admin/users/${userId}`);
      setSelectedUser(res.data);
      setIsUserDetailVisible(true);
    } catch (e) {
      message.error('获取用户详情失败');
    }
  };

  const handleEditUser = async (user) => {
    setSelectedUser(user);
    userEditForm.setFieldsValue({
      email: user.email,
      password: ''
    });
    setIsUserEditModalVisible(true);
  };

  const handleUpdateUser = async (values) => {
    try {
      // 只发送有值的字段
      const updateData = {};
      if (values.email) updateData.email = values.email;
      if (values.password) updateData.password = values.password;

      await api.put(`/admin/users/${selectedUser.id}`, updateData);
      message.success('用户信息已更新');
      setIsUserEditModalVisible(false);
      userEditForm.resetFields();
      setSelectedUser(null);
      fetchUsers(searchKeyword);
    } catch (e) {
      message.error(e.response?.data?.detail || '更新用户失败');
    }
  };

  // 模型管理
  const handleSaveModel = async (values) => {
    try {
      if (editingItem) {
        await api.put(`/ai-agents/models/${editingItem.id}`, values);
        message.success('模型更新成功');
      } else {
        await api.post('/ai-agents/models', values);
        message.success('模型创建成功');
      }
      setIsModelModalVisible(false);
      modelForm.resetFields();
      setEditingItem(null);
      fetchModels();
      fetchStats();
    } catch (e) {
      message.error(e.response?.data?.detail || '操作失败');
    }
  };

  const handleDeleteModel = async (modelId) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个模型吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await api.delete(`/ai-agents/models/${modelId}`);
          message.success('模型已删除');
          fetchModels();
          fetchStats();
        } catch (e) {
          message.error('删除模型失败');
        }
      }
    });
  };

  const handleTestModel = async (modelId, modelName) => {
    const hide = message.loading(`正在测试模型 ${modelName}...`, 0);
    try {
      const res = await api.post(`/ai-agents/models/${modelId}/test`);
      hide();
      
      if (res.data.success) {
        Modal.success({
          title: '模型测试成功 ✓',
          content: (
            <div>
              <p><strong>模型名称:</strong> {res.data.model_name}</p>
              <p><strong>响应时间:</strong> {Math.round(res.data.latency_ms)}ms</p>
              <p><strong>模型回复:</strong></p>
              <div style={{ 
                background: '#f5f5f5', 
                padding: '12px', 
                borderRadius: '6px', 
                marginTop: '8px',
                maxHeight: '200px',
                overflow: 'auto'
              }}>
                {res.data.response}
              </div>
            </div>
          ),
          width: 500
        });
      } else {
        Modal.error({
          title: '模型测试失败 ✗',
          content: (
            <div>
              <p><strong>错误信息:</strong> {res.data.message}</p>
              {res.data.error && (
                <div style={{ 
                  background: '#fff2f0', 
                  padding: '12px', 
                  borderRadius: '6px', 
                  marginTop: '8px',
                  color: '#cf1322',
                  maxHeight: '200px',
                  overflow: 'auto',
                  fontSize: '12px'
                }}>
                  {res.data.error}
                </div>
              )}
            </div>
          ),
          width: 500
        });
      }
    } catch (e) {
      hide();
      message.error(e.response?.data?.detail || '测试请求失败');
    }
  };

  // 工具管理
  const handleSaveTool = async (values) => {
    try {
      // 解析 JSON schema
      const parsedValues = {
        ...values,
        parameters_schema: JSON.parse(values.parameters_schema || '{}'),
        is_code_tool: values.is_code_tool || false,
        function_code: values.function_code || null
      };
      
      if (editingItem) {
        await api.put(`/ai-agents/tools/${editingItem.id}`, parsedValues);
        message.success('工具更新成功');
      } else {
        await api.post('/ai-agents/tools', parsedValues);
        message.success('工具创建成功');
      }
      setIsToolModalVisible(false);
      toolForm.resetFields();
      setEditingItem(null);
      fetchTools();
      fetchStats();
    } catch (e) {
      message.error(e.response?.data?.detail || '操作失败');
    }
  };

  const handleTestTool = async (toolId, toolName) => {
    const hide = message.loading(`正在测试工具 ${toolName}...`, 0);
    try {
      const res = await api.post(`/ai-agents/tools/${toolId}/test`);
      hide();
      
      if (res.data.success) {
        Modal.success({
          title: '工具测试成功 ✓',
          content: (
            <div>
              <p><strong>工具名称:</strong> {toolName}</p>
              {res.data.is_code_tool && (
                <>
                  <p><strong>函数名称:</strong> {res.data.function_name}</p>
                  <p><strong>测试参数:</strong></p>
                  <pre style={{ 
                    background: '#f5f5f5', 
                    padding: '8px', 
                    borderRadius: '4px',
                    fontSize: '12px',
                    overflow: 'auto'
                  }}>
                    {JSON.stringify(res.data.test_parameters, null, 2)}
                  </pre>
                  <p><strong>执行结果:</strong></p>
                  <div style={{ 
                    background: '#f6ffed', 
                    padding: '12px', 
                    borderRadius: '6px', 
                    marginTop: '8px',
                    maxHeight: '200px',
                    overflow: 'auto'
                  }}>
                    {typeof res.data.result === 'object' 
                      ? JSON.stringify(res.data.result, null, 2)
                      : String(res.data.result)}
                  </div>
                </>
              )}
              {!res.data.is_code_tool && (
                <p>{res.data.message}</p>
              )}
            </div>
          ),
          width: 600
        });
      } else {
        Modal.error({
          title: '工具测试失败 ✗',
          content: (
            <div>
              {res.data.error && (
                <div style={{ 
                  background: '#fff2f0', 
                  padding: '12px', 
                  borderRadius: '6px', 
                  color: '#cf1322',
                  maxHeight: '200px',
                  overflow: 'auto',
                  fontSize: '12px'
                }}>
                  {res.data.error}
                </div>
              )}
            </div>
          ),
          width: 500
        });
      }
    } catch (e) {
      hide();
      message.error(e.response?.data?.detail || '测试请求失败');
    }
  };

  const handleDeleteTool = async (toolId) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个工具吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await api.delete(`/ai-agents/tools/${toolId}`);
          message.success('工具已删除');
          fetchTools();
          fetchStats();
        } catch (e) {
          message.error('删除工具失败');
        }
      }
    });
  };

  // 查看工具调用记录
  const handleViewToolLogs = async (tool) => {
    try {
      setSelectedTool(tool);
      
      // 获取调用记录
      const logsRes = await api.get(`/ai-agents/tool-call-logs?tool_id=${tool.id}&limit=50`);
      setToolCallLogs(logsRes.data);
      
      // 获取统计信息
      const statsRes = await api.get(`/ai-agents/tool-call-logs/stats?tool_id=${tool.id}`);
      setToolCallStats(statsRes.data);
      
      setIsToolLogsModalVisible(true);
    } catch (e) {
      message.error('获取调用记录失败');
      console.error(e);
    }
  };

  // AI生成工具
  const handleGenerateToolByAI = async (values) => {
    try {
      const params = new URLSearchParams();
      params.append('description', values.description);
      params.append('model_id', values.model_id);
      
      setAiToolProgress({ stage: 'start', message: '准备生成...' });
      setGeneratedTool(null);
      
      const token = useAuthStore.getState().token;
      const apiHost = import.meta.env.VITE_API_HOST || 'http://localhost:8000';
      
      const response = await fetch(
        `${apiHost}/api/admin/generate-tool?${params.toString()}`,
        {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Accept': 'text/event-stream',
          },
        }
      );
      
      if (!response.ok) {
        throw new Error('生成请求失败');
      }
      
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';
      
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n\n');
        buffer = lines.pop() || '';
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const data = JSON.parse(line.substring(6));
              
              if (data.error) {
                message.error(data.error);
                setAiToolProgress(null);
                return;
              }
              
              if (data.type === 'start' || data.type === 'thinking' || 
                  data.type === 'generating' || data.type === 'parsing' || 
                  data.type === 'validating' || data.type === 'validated') {
                setAiToolProgress({ stage: data.type, message: data.message });
              } else if (data.type === 'complete') {
                setAiToolProgress({ stage: 'complete', message: data.message });
                setGeneratedTool(data.data);
                message.success('工具配置生成成功！');
              }
            } catch (e) {
              console.error('解析数据失败:', e);
            }
          }
        }
      }
    } catch (e) {
      console.error('生成失败:', e);
      message.error(e.message || '生成失败');
      setAiToolProgress(null);
    }
  };

  const handleUseGeneratedTool = () => {
    if (generatedTool) {
      // 清除编辑状态，确保创建新工具而不是更新现有工具
      setEditingItem(null);
      
      toolForm.setFieldsValue({
        name: generatedTool.name,
        description: generatedTool.description,
        is_code_tool: generatedTool.is_code_tool || false,
        function_code: generatedTool.function_code || '',
        parameters_schema: JSON.stringify(generatedTool.parameters_schema, null, 2)
      });
      setIsAiToolModalVisible(false);
      setIsToolModalVisible(true);
      setAiToolProgress(null);
      setGeneratedTool(null);
      aiToolForm.resetFields();
    }
  };

  // 数字员工管理
  const handleGenerateSystemPrompt = async () => {
    const employeeName = employeeForm.getFieldValue('name');
    const modelId = employeeForm.getFieldValue('model_id');
    
    if (!employeeName) {
      message.warning('请先输入员工名称');
      return;
    }
    
    setGeneratingPrompt(true);
    try {
      const response = await api.post('/ai-agents/employees/generate-prompt', {
        employee_name: employeeName,
        model_id: modelId
      });
      
      if (response.data.success) {
        employeeForm.setFieldsValue({
          system_prompt: response.data.system_prompt
        });
        message.success('系统提示词生成成功！');
      }
    } catch (e) {
      message.error(e.response?.data?.detail || '生成失败');
    } finally {
      setGeneratingPrompt(false);
    }
  };
  
  const handleSaveEmployee = async (values) => {
    try {
      const parsedValues = {
        ...values,
        tool_ids: values.tool_ids || []
      };
      
      if (editingItem) {
        await api.put(`/ai-agents/employees/${editingItem.id}`, parsedValues);
        message.success('数字员工更新成功');
      } else {
        await api.post('/ai-agents/employees', parsedValues);
        message.success('数字员工创建成功');
      }
      setIsEmployeeModalVisible(false);
      employeeForm.resetFields();
      setEditingItem(null);
      fetchEmployees();
      fetchStats();
    } catch (e) {
      message.error(e.response?.data?.detail || '操作失败');
    }
  };

  const handleDeleteEmployee = async (empId) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个数字员工吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await api.delete(`/ai-agents/employees/${empId}`);
          message.success('数字员工已删除');
          fetchEmployees();
          fetchStats();
        } catch (e) {
          message.error('删除数字员工失败');
        }
      }
    });
  };

  const handleAnalyzeSensitive = async (values) => {
    try {
      const params = new URLSearchParams();
      if (values.start_date) params.append('start_date', values.start_date);
      if (values.end_date) params.append('end_date', values.end_date);
      if (values.model_id) params.append('model_id', values.model_id);
      
      // 重置进度状态
      setAnalyzeProgress({ total: 0, analyzed: 0, sensitive_found: 0 });
      setAnalyzingMessages([]);
      
      // 获取token
      const token = useAuthStore.getState().token;
      const apiHost = import.meta.env.VITE_API_HOST || 'http://localhost:8000';
      
      // 使用 fetch 的 EventSource polyfill 或直接使用 fetch with stream
      const response = await fetch(
        `${apiHost}/api/admin/analyze-sensitive?${params.toString()}`,
        {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Accept': 'text/event-stream',
          },
        }
      );
      
      if (!response.ok) {
        throw new Error('分析请求失败');
      }
      
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      
      let buffer = '';
      
      while (true) {
        const { done, value } = await reader.read();
        
        if (done) break;
        
        buffer += decoder.decode(value, { stream: true });
        
        // 处理完整的事件
        const lines = buffer.split('\n\n');
        buffer = lines.pop() || ''; // 保留不完整的部分
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const data = JSON.parse(line.substring(6));
              
              if (data.error) {
                message.error(data.error);
                return;
              }
              
              if (data.type === 'start') {
                setAnalyzeProgress({
                  total: data.total,
                  analyzed: 0,
                  sensitive_found: 0,
                  model: data.model
                });
              } else if (data.type === 'analyzing') {
                setAnalyzingMessages(prev => [
                  ...prev.slice(-9), // 只保留最近10条
                  { content: data.content, status: 'analyzing', index: data.index }
                ]);
              } else if (data.type === 'result') {
                setAnalyzeProgress({
                  total: data.total,
                  analyzed: data.analyzed,
                  sensitive_found: data.sensitive_found
                });
                setAnalyzingMessages(prev => {
                  const newMessages = [...prev];
                  const lastMsg = newMessages[newMessages.length - 1];
                  if (lastMsg && lastMsg.index === data.index) {
                    lastMsg.status = data.is_sensitive ? 'sensitive' : 'normal';
                    lastMsg.is_sensitive = data.is_sensitive;
                  }
                  return newMessages;
                });
              } else if (data.type === 'complete') {
                message.success(data.message);
                
                setTimeout(() => {
                  setIsAnalyzeModalVisible(false);
                  analyzeForm.resetFields();
                  setAnalyzeProgress(null);
                  setAnalyzingMessages([]);
                  fetchChatLogs(chatSearchKeyword, chatSenderFilter, chatStatusFilter);
                  fetchStats();
                }, 2000);
              }
            } catch (e) {
              console.error('解析数据失败:', e);
            }
          }
        }
      }
      
    } catch (e) {
      console.error('分析失败:', e);
      message.error(e.message || '分析失败');
      setAnalyzeProgress(null);
    }
  };

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  const navItems = [
    { key: 'users', label: '用户管理', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke="currentColor" strokeWidth="2"/><circle cx="9" cy="7" r="4" stroke="currentColor" strokeWidth="2"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" stroke="currentColor" strokeWidth="2"/></svg> },
    { key: 'chat', label: '聊天信息', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="currentColor" strokeWidth="2"/></svg> },
    { key: 'assistant', label: '对话助手', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" strokeWidth="2"/></svg> },
    { key: 'models', label: '大模型管理', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/><path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="currentColor" strokeWidth="2"/></svg> },
    { key: 'tools', label: '工具管理', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z" stroke="currentColor" strokeWidth="2"/></svg> },
    { key: 'agents', label: '数字员工管理', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" strokeWidth="2"/></svg> },
    { key: 'analytics', label: '数据分析', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><line x1="18" y1="20" x2="18" y2="10" stroke="currentColor" strokeWidth="2"/><line x1="12" y1="20" x2="12" y2="4" stroke="currentColor" strokeWidth="2"/><line x1="6" y1="20" x2="6" y2="14" stroke="currentColor" strokeWidth="2"/></svg> },
  ];

  const renderContent = () => {
    // 用户管理页面
    if (activeNav === 'users') {
      return (
        <div className="ad-content-wrap">
          <div className="ad-page-header">
            <div>
              <h2 className="ad-page-title">用户管理</h2>
              <p className="ad-page-sub">监控和管理平台的所有注册用户及权限与状态。</p>
            </div>
            <button className="ad-btn-primary" onClick={() => setIsUserModalVisible(true)}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M16 21v-2a4 4 0 00-4-4H6a4 4 0 00-4 4v2" stroke="currentColor" strokeWidth="2"/><circle cx="9" cy="7" r="4" stroke="currentColor" strokeWidth="2"/><line x1="19" y1="8" x2="19" y2="14" stroke="currentColor" strokeWidth="2"/><line x1="22" y1="11" x2="16" y2="11" stroke="currentColor" strokeWidth="2"/></svg>
              添加新用户
            </button>
          </div>

          <div className="ad-toolbar">
            <div className="ad-search-box">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="11" cy="11" r="8" stroke="#9ca3af" strokeWidth="2"/><path d="M21 21l-4.35-4.35" stroke="#9ca3af" strokeWidth="2"/></svg>
              <input 
                placeholder="搜索用户名、邮箱..." 
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                onKeyDown={handleSearchKeyDown}
              />
            </div>
            <button className="ad-btn-ghost" onClick={handleSearch}>搜索</button>
            <button className="ad-btn-ghost" onClick={handleResetSearch}>重置</button>
          </div>

          <div className="ad-table-wrap">
            <table className="ad-table">
              <thead>
                <tr>
                  <th>用户信息</th>
                  <th>邮箱地址</th>
                  <th>角色</th>
                  <th>账号状态</th>
                  <th>管理操作</th>
                </tr>
              </thead>
              <tbody>
                {users.map(u => (
                  <tr key={u.id}>
                    <td>
                      <div className="ad-user-cell">
                        <div className="ad-user-avatar">{u.username?.[0]?.toUpperCase() || 'U'}</div>
                        <div>
                          <div className="ad-user-name">{u.username}</div>
                          <div className="ad-user-id">ID: {u.id}</div>
                        </div>
                      </div>
                    </td>
                    <td>{u.email}</td>
                    <td>
                      <span className={`ad-role-tag ${u.is_admin ? 'ad-role-admin' : 'ad-role-user'}`}>
                        {u.is_admin ? '管理员' : '普通用户'}
                      </span>
                    </td>
                    <td>
                      <span className={`ad-status-tag ${u.is_active ? 'ad-status-active' : 'ad-status-inactive'}`}>
                        {u.is_active ? '正常' : '已封禁'}
                      </span>
                    </td>
                    <td>
                      <div className="ad-actions">
                        <button className="ad-icon-btn" title="查看详情" onClick={() => handleViewUserDetail(u.id)}>
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" stroke="currentColor" strokeWidth="2"/><circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/></svg>
                        </button>
                        <button className="ad-icon-btn" title="编辑" onClick={() => handleEditUser(u)}>
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" stroke="currentColor" strokeWidth="2"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" strokeWidth="2"/></svg>
                        </button>
                        <button className="ad-icon-btn" title={u.is_active ? '封禁' : '解封'} onClick={() => handleToggleUserStatus(u.id, u.is_active)}>
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07" stroke="currentColor" strokeWidth="2"/></svg>
                        </button>
                        <button className="ad-icon-btn ad-icon-btn-danger" title="删除" onClick={() => handleDeleteUser(u.id)}>
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><polyline points="3 6 5 6 21 6" stroke="currentColor" strokeWidth="2"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2" stroke="currentColor" strokeWidth="2"/></svg>
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      );
    }

    // 聊天信息管理页面
    if (activeNav === 'chat') {
      return (
        <div className="ad-content-wrap">
          <div className="ad-page-header">
            <div>
              <h2 className="ad-page-title">聊天信息管理</h2>
              <p className="ad-page-sub">实时监控对话内容，识别风险信息并进行AI分析。</p>
            </div>
            <button className="ad-btn-primary" onClick={() => { setIsAnalyzeModalVisible(true); fetchModels(); }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" strokeWidth="2"/></svg>
              AI 分析
            </button>
          </div>

          <div className="ad-chat-grid">
            <div className="ad-chat-main">
              <div className="ad-toolbar">
                <div className="ad-search-box">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="11" cy="11" r="8" stroke="#9ca3af" strokeWidth="2"/><path d="M21 21l-4.35-4.35" stroke="#9ca3af" strokeWidth="2"/></svg>
                  <input 
                    placeholder="搜索消息内容..." 
                    value={chatSearchKeyword}
                    onChange={(e) => setChatSearchKeyword(e.target.value)}
                    onKeyDown={(e) => e.key === 'Enter' && handleChatSearch()}
                  />
                </div>
                <input 
                  className="ad-filter" 
                  placeholder="发送者..."
                  value={chatSenderFilter}
                  onChange={(e) => setChatSenderFilter(e.target.value)}
                  style={{ width: '120px', padding: '0 12px', border: '1px solid #e5e7eb', borderRadius: '6px' }}
                />
                <select 
                  className="ad-filter"
                  value={chatStatusFilter}
                  onChange={(e) => setChatStatusFilter(e.target.value)}
                >
                  <option value="">所有状态</option>
                  <option value="normal">正常</option>
                  <option value="sensitive">敏感</option>
                </select>
                <button className="ad-btn-ghost" onClick={handleChatSearch}>搜索</button>
                <button className="ad-btn-ghost" onClick={handleChatReset}>重置</button>
              </div>

              <div className="ad-chat-list">
                {chatLogs.map(chat => (
                  <div key={chat.id} className="ad-chat-item">
                    <div className="ad-chat-item-header">
                      <div className="ad-chat-user">
                        <div className="ad-chat-avatar">{chat.sender_name?.[0]?.toUpperCase() || 'U'}</div>
                        <div>
                          <div className="ad-chat-username">{chat.sender_name}</div>
                          <div className="ad-chat-room">{chat.room_name}</div>
                        </div>
                      </div>
                      <span className={`ad-risk-tag ${chat.is_sensitive ? 'ad-risk-high' : 'ad-risk-low'}`}>
                        {chat.is_sensitive ? '敏感' : '正常'}
                      </span>
                    </div>
                    <div className="ad-chat-msg">{chat.content}</div>
                    <div className="ad-chat-footer">
                      <span className="ad-chat-time">
                        {chat.timestamp ? new Date(chat.timestamp).toLocaleString('zh-CN', {
                          year: 'numeric',
                          month: '2-digit',
                          day: '2-digit',
                          hour: '2-digit',
                          minute: '2-digit',
                          second: '2-digit',
                          hour12: false
                        }) : '未知时间'}
                      </span>
                    </div>
                  </div>
                ))}
                {chatLogs.length === 0 && (
                  <div className="ad-empty">暂无聊天记录</div>
                )}
              </div>
            </div>

            <div className="ad-chat-panel">
              <div className="ad-panel-card">
                <h3 className="ad-panel-title">实时监控</h3>
                <div className="ad-monitor-stats">
                  <div className="ad-monitor-item">
                    <div className="ad-monitor-label">今日消息</div>
                    <div className="ad-monitor-value">{stats.today_message_count || 0}</div>
                  </div>
                  <div className="ad-monitor-item">
                    <div className="ad-monitor-label">敏感消息</div>
                    <div className="ad-monitor-value ad-text-red">{stats.sensitive_count || 0}</div>
                  </div>
                  <div className="ad-monitor-item">
                    <div className="ad-monitor-label">活跃用户</div>
                    <div className="ad-monitor-value">{stats.active_user_count || 0}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      );
    }

    // 大模型管理页面 - 继续在下一部分

    // 大模型管理页面
    if (activeNav === 'models') {
      return (
        <div className="ad-content-wrap">
          <div className="ad-page-header">
            <div>
              <h2 className="ad-page-title">大模型管理</h2>
              <p className="ad-page-sub">配置和管理AI大模型，监控使用情况和性能指标。</p>
            </div>
            <button className="ad-btn-primary" onClick={() => { setEditingItem(null); modelForm.resetFields(); setIsModelModalVisible(true); }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" strokeWidth="2"/><line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" strokeWidth="2"/></svg>
              添加新模型
            </button>
          </div>

          <div className="ad-models-grid">
            {models.map((model) => (
              <div key={model.id} className="ad-model-card">
                <div className="ad-model-header">
                  <div className="ad-model-icon">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/><path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="currentColor" strokeWidth="2"/></svg>
                  </div>
                  {model.is_default ? (
                    <span className="ad-model-status" style={{ background: '#fef3c7', color: '#92400e' }}>
                      ⭐ 默认模型
                    </span>
                  ) : (
                    <span className="ad-model-status ad-status-active">运行中</span>
                  )}
                </div>
                <h3 className="ad-model-name">{model.name}</h3>
                <div className="ad-model-provider">{model.base_url}</div>
                <div className="ad-model-actions">
                  {!model.is_default && (
                    <button 
                      className="ad-btn-ghost" 
                      onClick={async () => {
                        try {
                          await api.post(`/ai-agents/models/${model.id}/set-default`);
                          message.success('默认模型设置成功');
                          fetchModels();
                        } catch (e) {
                          message.error('设置失败');
                        }
                      }}
                      style={{ color: '#f59e0b' }}
                    >
                      设为默认
                    </button>
                  )}
                  <button className="ad-btn-ghost" onClick={() => { setEditingItem(model); modelForm.setFieldsValue(model); setIsModelModalVisible(true); }}>配置</button>
                  <button className="ad-btn-ghost" onClick={() => handleTestModel(model.id, model.name)}>测试</button>
                  <button className="ad-btn-ghost ad-btn-danger" onClick={() => handleDeleteModel(model.id)}>删除</button>
                </div>
              </div>
            ))}
            {models.length === 0 && (
              <div className="ad-empty">暂无模型配置</div>
            )}
          </div>
        </div>
      );
    }

    // 工具管理页面
    if (activeNav === 'tools') {
      return (
        <div className="ad-content-wrap">
          <div className="ad-page-header">
            <div>
              <h2 className="ad-page-title">工具管理</h2>
              <p className="ad-page-sub">管理AI可调用的工具和API接口，配置权限和参数。</p>
            </div>
            <div style={{ display: 'flex', gap: '12px' }}>
              <button 
                className="ad-btn-ghost" 
                onClick={() => { 
                  setIsAiToolModalVisible(true); 
                  fetchModels(); 
                }}
                style={{ 
                  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                  color: 'white',
                  border: 'none'
                }}
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ marginRight: '6px' }}>
                  <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" strokeWidth="2"/>
                </svg>
                AI 生成工具
              </button>
              <button className="ad-btn-primary" onClick={() => { setEditingItem(null); toolForm.resetFields(); setIsToolModalVisible(true); }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" strokeWidth="2"/><line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" strokeWidth="2"/></svg>
                手动添加工具
              </button>
            </div>
          </div>

          <div className="ad-tools-grid">
            {tools.map((tool) => (
              <div key={tool.id} className="ad-tool-card">
                <div className="ad-tool-header">
                  <div className="ad-tool-icon">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z" stroke="currentColor" strokeWidth="2"/></svg>
                  </div>
                  <span className="ad-tool-category">API</span>
                </div>
                <h3 className="ad-tool-name">{tool.name}</h3>
                <p className="ad-tool-desc">{tool.description}</p>
                {tool.is_code_tool && (
                  <div className="ad-tool-badge">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none">
                      <path d="M8 3L4 7l4 4M16 3l4 4-4 4M12 3v18" stroke="#10b981" strokeWidth="2"/>
                    </svg>
                    代码工具
                  </div>
                )}
                <div className="ad-tool-footer">
                  <button className="ad-btn-ghost" onClick={() => { 
                    setEditingItem(tool); 
                    toolForm.setFieldsValue({
                      ...tool, 
                      parameters_schema: JSON.stringify(tool.parameters_schema, null, 2)
                    }); 
                    setIsToolModalVisible(true); 
                  }}>编辑</button>
                  <button className="ad-btn-ghost" onClick={() => handleViewToolLogs(tool)}>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" style={{ marginRight: '4px' }}>
                      <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" stroke="currentColor" strokeWidth="2"/>
                    </svg>
                    调用记录
                  </button>
                  {tool.is_code_tool && (
                    <button className="ad-btn-ghost" onClick={() => handleTestTool(tool.id, tool.name)}>测试</button>
                  )}
                  <button className="ad-btn-ghost ad-btn-danger" onClick={() => handleDeleteTool(tool.id)}>删除</button>
                </div>
              </div>
            ))}
            {tools.length === 0 && (
              <div className="ad-empty">暂无工具配置</div>
            )}
          </div>
        </div>
      );
    }

    // 数字员工管理页面
    if (activeNav === 'agents') {
      return (
        <div className="ad-content-wrap">
          <div className="ad-page-header">
            <div>
              <h2 className="ad-page-title">数字员工管理</h2>
              <p className="ad-page-sub">创建和管理AI Agent，配置其能力和工作流程。</p>
            </div>
            <button className="ad-btn-primary" onClick={() => { setEditingItem(null); employeeForm.resetFields(); setIsEmployeeModalVisible(true); }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" strokeWidth="2"/><line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" strokeWidth="2"/></svg>
              创建新员工
            </button>
          </div>

          <div className="ad-agents-grid">
            {employees.map((agent) => (
              <div key={agent.id} className="ad-agent-card">
                <div className="ad-agent-header">
                  <div className="ad-agent-avatar">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" strokeWidth="2"/></svg>
                  </div>
                  <span className="ad-agent-status ad-status-active">在线</span>
                </div>
                <h3 className="ad-agent-name">{agent.name}</h3>
                <div className="ad-agent-role">
                  模型: {agent.model_name || '未知模型'}
                  {models.find(m => m.id === agent.model_id)?.is_default && (
                    <span style={{ marginLeft: '8px', color: '#f59e0b' }}>⭐</span>
                  )}
                </div>
                <div className="ad-agent-info">
                  <div className="ad-agent-info-item">
                    <span className="ad-agent-info-label">工具:</span>
                    <span className="ad-agent-info-value">{agent.tool_ids?.length || 0}个</span>
                  </div>
                </div>
                <div className="ad-agent-actions">
                  <button className="ad-btn-ghost" onClick={() => {
                    setEditingItem(agent);
                    // 解析 tool_ids：可能是数组、JSON字符串或null
                    let toolIds = agent.tool_ids || [];
                    if (typeof toolIds === 'string') {
                      try { toolIds = JSON.parse(toolIds); } catch { toolIds = []; }
                    }
                    toolIds = toolIds.map(id => Number(id));
                    employeeForm.setFieldsValue({
                      ...agent,
                      tool_ids: toolIds
                    });
                    setIsEmployeeModalVisible(true);
                  }}>配置</button>
                  <button className="ad-btn-ghost" onClick={() => handleDeleteEmployee(agent.id)}>删除</button>
                </div>
              </div>
            ))}
            {employees.length === 0 && (
              <div className="ad-empty">暂无数字员工</div>
            )}
          </div>
        </div>
      );
    }

    // 对话助手页面
    if (activeNav === 'assistant') {
      return (
        <div className="ad-content-wrap">
          <ChatAssistant models={models} />
        </div>
      );
    }

    // 数据分析页面
    if (activeNav === 'analytics') {
      const COLORS = ['#4f46e5', '#06b6d4', '#ef4444'];

      return (
        <div className="ad-content-wrap">
          <div className="ad-page-header">
            <h2 className="ad-page-title">数据分析中心</h2>
            <p className="ad-page-sub">实时监控系统运行状况，分析用户行为和产品交互</p>
          </div>

          <div className="ad-stats-grid">
            <div className="ad-stat-card">
              <div className="ad-stat-icon ad-stat-icon-blue">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke="white" strokeWidth="2"/><circle cx="9" cy="7" r="4" stroke="white" strokeWidth="2"/></svg>
              </div>
              <div className="ad-stat-info">
                <div className="ad-stat-label">总用户数</div>
                <div className="ad-stat-value">{stats.user_count || 0}</div>
                <div className="ad-stat-trend ad-trend-up">+12.5%</div>
              </div>
            </div>
            <div className="ad-stat-card">
              <div className="ad-stat-icon ad-stat-icon-green">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" stroke="white" strokeWidth="2"/></svg>
              </div>
              <div className="ad-stat-info">
                <div className="ad-stat-label">活跃用户</div>
                <div className="ad-stat-value">{stats.active_user_count || 0}</div>
                <div className="ad-stat-trend ad-trend-up">+5.2%</div>
              </div>
            </div>
            <div className="ad-stat-card">
              <div className="ad-stat-icon ad-stat-icon-orange">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="white" strokeWidth="2"/></svg>
              </div>
              <div className="ad-stat-info">
                <div className="ad-stat-label">消息总量</div>
                <div className="ad-stat-value">{stats.message_count || 0}</div>
                <div className="ad-stat-trend ad-trend-down">-2.1%</div>
              </div>
            </div>
            <div className="ad-stat-card">
              <div className="ad-stat-icon ad-stat-icon-purple">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="white" strokeWidth="2"/></svg>
              </div>
              <div className="ad-stat-info">
                <div className="ad-stat-label">AI 模型数</div>
                <div className="ad-stat-value">{stats.model_count || 0}</div>
                <div className="ad-stat-trend ad-trend-up">+0.8%</div>
              </div>
            </div>
          </div>

          <div className="ad-charts-row">
            <div className="ad-chart-card ad-chart-large">
              <div className="ad-chart-header">
                <h3>每小时消息量趋势</h3>
                <div className="ad-chart-tabs">
                  <button className="ad-chart-tab ad-chart-tab-active">24小时</button>
                  <button className="ad-chart-tab">7天</button>
                </div>
              </div>
              <ResponsiveContainer width="100%" height={240}>
                <LineChart data={hourlyData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                  <XAxis dataKey="time" stroke="#9ca3af" style={{ fontSize: 12 }} />
                  <YAxis stroke="#9ca3af" style={{ fontSize: 12 }} />
                  <Tooltip />
                  <Line type="monotone" dataKey="value" stroke="#4f46e5" strokeWidth={2} dot={{ fill: '#4f46e5', r: 4 }} />
                </LineChart>
              </ResponsiveContainer>
            </div>

            <div className="ad-chart-card">
              <div className="ad-chart-header">
                <h3>消息风险分布</h3>
              </div>
              <ResponsiveContainer width="100%" height={200}>
                <PieChart>
                  <Pie data={riskData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} dataKey="value" label>
                    {riskData.map((entry, index) => <Cell key={`cell-${index}`} fill={COLORS[index]} />)}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
              <div className="ad-pie-legend">
                {riskData.map((d, i) => (
                  <div key={i} className="ad-legend-item">
                    <span className="ad-legend-dot" style={{ background: COLORS[i] }} />
                    <span>{d.name} ({d.value}%)</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      );
    }

    return (
      <div className="ad-placeholder">
        <svg width="48" height="48" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke="#d1d5db" strokeWidth="1.5"/><path d="M12 8v4M12 16h.01" stroke="#d1d5db" strokeWidth="2"/></svg>
        <div className="ad-placeholder-title">{navItems.find(n => n.key === activeNav)?.label}</div>
        <div className="ad-placeholder-sub">该功能正在开发中，敬请期待</div>
      </div>
    );
  };

  return (
    <div className="ad-root">
      {/* 左侧导航 */}
      <aside className="ad-sidebar">
        <div className="ad-logo">
          <div className="ad-logo-icon">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" stroke="white" strokeWidth="2"/></svg>
          </div>
          <div>
            <div className="ad-logo-text">灵犀智能</div>
            <div className="ad-logo-sub">管理中心</div>
          </div>
        </div>

        <nav className="ad-nav">
          {navItems.map(item => (
            <button
              key={item.key}
              className={`ad-nav-item ${activeNav === item.key ? 'ad-nav-active' : ''}`}
              onClick={() => { 
                setActiveNav(item.key); 
                if (item.key === 'users') fetchUsers(); 
                if (item.key === 'chat') fetchChatLogs('', '', ''); 
                if (item.key === 'assistant') fetchModels();
                if (item.key === 'models') fetchModels();
                if (item.key === 'tools') fetchTools();
                if (item.key === 'agents') { fetchEmployees(); fetchTools(); }
                if (item.key === 'analytics') fetchAnalytics();
              }}
            >
              <span className="ad-nav-icon">{item.icon}</span>
              {item.label}
            </button>
          ))}
        </nav>

        <div className="ad-sidebar-footer">
          <button className="ad-nav-item" onClick={handleLogout}>
            <span className="ad-nav-icon">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9" stroke="currentColor" strokeWidth="2"/></svg>
            </span>
            退出登录
          </button>
        </div>
      </aside>

      {/* 主内容 */}
      <main className="ad-main">
        {/* 顶部栏 */}
        <header className="ad-topbar">
          <div className="ad-breadcrumb">
            <span>管理控制台</span>
            <span>/</span>
            <span>{navItems.find(n => n.key === activeNav)?.label}</span>
          </div>
          <div className="ad-topbar-right">
            <div className="ad-search-mini">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="11" cy="11" r="8" stroke="#9ca3af" strokeWidth="2"/><path d="M21 21l-4.35-4.35" stroke="#9ca3af" strokeWidth="2"/></svg>
              <input placeholder="搜索..." />
            </div>
            <button className="ad-icon-btn-top">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 01-3.46 0" stroke="currentColor" strokeWidth="2"/></svg>
              <span className="ad-badge">3</span>
            </button>
            <div className="ad-user-menu">
              <div className="ad-user-avatar-top">{user?.username?.[0]?.toUpperCase() || 'A'}</div>
              <span>{user?.username || 'Admin'}</span>
            </div>
          </div>
        </header>

        {/* 内容区 */}
        <div className="ad-content">
          {renderContent()}
        </div>
      </main>

      {/* 用户创建 Modal */}
      <Modal
        title="添加新用户"
        open={isUserModalVisible}
        onCancel={() => setIsUserModalVisible(false)}
        footer={null}
      >
        <Form form={userForm} onFinish={handleCreateUser} layout="vertical">
          <Form.Item name="username" label="用户名" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="email" label="邮箱" rules={[{ required: true, type: 'email', message: '请输入有效的邮箱' }]}>
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item name="password" label="密码" rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>创建用户</Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 用户详情 Modal */}
      <Modal
        title="用户详情"
        open={isUserDetailVisible}
        onCancel={() => setIsUserDetailVisible(false)}
        footer={null}
      >
        {selectedUser && (
          <div>
            <p><strong>ID:</strong> {selectedUser.id}</p>
            <p><strong>用户名:</strong> {selectedUser.username}</p>
            <p><strong>邮箱:</strong> {selectedUser.email}</p>
            <p><strong>状态:</strong> {selectedUser.is_active ? '正常' : '已封禁'}</p>
            <p><strong>角色:</strong> {selectedUser.is_admin ? '管理员' : '普通用户'}</p>
          </div>
        )}
      </Modal>

      {/* 用户编辑 Modal */}
      <Modal
        title="编辑用户"
        open={isUserEditModalVisible}
        onCancel={() => {
          setIsUserEditModalVisible(false);
          userEditForm.resetFields();
          setSelectedUser(null);
        }}
        footer={null}
      >
        {selectedUser && (
          <div>
            <div style={{ marginBottom: '16px', padding: '12px', background: '#f5f5f5', borderRadius: '6px' }}>
              <p style={{ margin: 0 }}><strong>用户名:</strong> {selectedUser.username}</p>
              <p style={{ margin: '4px 0 0 0', fontSize: '12px', color: '#666' }}>用户名不可修改</p>
            </div>
            <Form form={userEditForm} onFinish={handleUpdateUser} layout="vertical">
              <Form.Item 
                name="email" 
                label="邮箱" 
                rules={[{ type: 'email', message: '请输入有效的邮箱' }]}
              >
                <Input placeholder="请输入新邮箱（留空则不修改）" />
              </Form.Item>
              <Form.Item 
                name="password" 
                label="新密码"
              >
                <Input.Password placeholder="请输入新密码（留空则不修改）" />
              </Form.Item>
              <div style={{ marginBottom: '16px', padding: '12px', background: '#fff7e6', borderRadius: '6px', fontSize: '13px' }}>
                <strong>💡 提示：</strong>
                <ul style={{ margin: '8px 0 0 0', paddingLeft: '20px' }}>
                  <li>只需填写要修改的字段</li>
                  <li>留空的字段将保持不变</li>
                  <li>至少需要修改一个字段</li>
                </ul>
              </div>
              <Form.Item>
                <Button type="primary" htmlType="submit" block>保存修改</Button>
              </Form.Item>
            </Form>
          </div>
        )}
      </Modal>

      {/* 模型配置 Modal */}
      <Modal
        title={editingItem ? '编辑模型' : '添加新模型'}
        open={isModelModalVisible}
        onCancel={() => setIsModelModalVisible(false)}
        footer={null}
      >
        <Form form={modelForm} onFinish={handleSaveModel} layout="vertical">
          <Form.Item name="name" label="模型名称" rules={[{ required: true, message: '请输入模型名称' }]}>
            <Input placeholder="例如: gpt-4" />
          </Form.Item>
          <Form.Item name="api_key" label="API Key" rules={[{ required: true, message: '请输入API Key' }]}>
            <Input.Password placeholder="请输入API Key" />
          </Form.Item>
          <Form.Item name="base_url" label="Base URL" rules={[{ required: true, message: '请输入Base URL' }]}>
            <Input placeholder="例如: https://api.openai.com/v1" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>{editingItem ? '更新' : '创建'}</Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 工具配置 Modal */}
      <Modal
        title={editingItem ? '编辑工具' : '添加新工具'}
        open={isToolModalVisible}
        onCancel={() => setIsToolModalVisible(false)}
        footer={null}
        width={700}
      >
        <Form form={toolForm} onFinish={handleSaveTool} layout="vertical">
          <Form.Item name="name" label="工具名称" rules={[{ required: true, message: '请输入工具名称' }]}>
            <Input placeholder="例如: 天气查询" />
          </Form.Item>
          <Form.Item name="description" label="工具描述" rules={[{ required: true, message: '请输入工具描述' }]}>
            <Input.TextArea rows={2} placeholder="描述工具的功能" />
          </Form.Item>
          <Form.Item name="is_code_tool" label="工具类型" valuePropName="checked">
            <div>
              <input 
                type="checkbox" 
                id="is_code_tool"
                onChange={(e) => {
                  toolForm.setFieldsValue({ is_code_tool: e.target.checked });
                }}
                style={{ marginRight: '8px' }}
              />
              <label htmlFor="is_code_tool">这是一个代码工具（可执行 Python 函数）</label>
            </div>
          </Form.Item>
          <Form.Item 
            noStyle 
            shouldUpdate={(prevValues, currentValues) => prevValues.is_code_tool !== currentValues.is_code_tool}
          >
            {({ getFieldValue }) => 
              getFieldValue('is_code_tool') ? (
                <Form.Item name="function_code" label="Python 函数代码" rules={[{ required: true, message: '请输入函数代码' }]}>
                  <Input.TextArea 
                    rows={10} 
                    placeholder={`def calculate_sum(a, b):
    """计算两个数的和"""
    return a + b

# 或者更复杂的函数
def get_weather(city):
    """获取城市天气"""
    # 这里可以调用真实的天气 API
    return f"{city}的天气是晴天，温度25°C"`}
                    style={{ fontFamily: 'monospace', fontSize: '13px' }}
                  />
                </Form.Item>
              ) : null
            }
          </Form.Item>
          <Form.Item name="parameters_schema" label="参数Schema (JSON)" rules={[{ required: true, message: '请输入参数Schema' }]}>
            <Input.TextArea 
              rows={8} 
              placeholder={`{
  "type": "object",
  "properties": {
    "city": {
      "type": "string",
      "description": "城市名称",
      "example": "北京"
    }
  },
  "required": ["city"]
}`}
              style={{ fontFamily: 'monospace', fontSize: '12px' }}
            />
          </Form.Item>
          <div style={{ background: '#f0f9ff', padding: '12px', borderRadius: '6px', marginBottom: '16px', fontSize: '13px' }}>
            <strong>💡 提示：</strong>
            <ul style={{ margin: '8px 0 0 0', paddingLeft: '20px' }}>
              <li>代码工具会在安全的沙箱环境中执行</li>
              <li>函数参数名必须与 Schema 中的属性名一致</li>
              <li>可以使用的模块: json, datetime, math, random</li>
              <li>在 Schema 的 example 字段中提供示例值用于测试</li>
            </ul>
          </div>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>{editingItem ? '更新' : '创建'}</Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 数字员工配置 Modal */}
      <Modal
        title={editingItem ? '编辑数字员工' : '创建新数字员工'}
        open={isEmployeeModalVisible}
        onCancel={() => setIsEmployeeModalVisible(false)}
        afterOpenChange={(open) => { if (open && tools.length === 0) fetchTools(); }}
        footer={null}
        width={600}
      >
        <Form form={employeeForm} onFinish={handleSaveEmployee} layout="vertical">
          <Form.Item name="name" label="员工名称" rules={[{ required: true, message: '请输入员工名称' }]}>
            <Input placeholder="例如: 客服助手" />
          </Form.Item>
          <Form.Item name="model_name" label="使用模型" rules={[{ required: true, message: '请选择模型' }]}>
            <Select placeholder="选择AI模型">
              {models.map(m => (
                <Select.Option key={m.id} value={m.name}>
                  {m.name}
                  {m.is_default && <span style={{ marginLeft: '8px', color: '#f59e0b' }}>⭐ 默认</span>}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item 
            name="system_prompt" 
            label={
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
                <span>系统提示词</span>
                <Button
                  type="link"
                  size="small"
                  loading={generatingPrompt}
                  onClick={handleGenerateSystemPrompt}
                  style={{ 
                    padding: '0 8px',
                    height: '24px',
                    background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px'
                  }}
                >
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" style={{ marginRight: '4px', verticalAlign: 'middle' }}>
                    <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" strokeWidth="2"/>
                  </svg>
                  AI 生成
                </Button>
              </div>
            }
            rules={[{ required: true, message: '请输入系统提示词' }]}
          >
            <Input.TextArea 
              rows={6} 
              placeholder="定义AI的角色和行为，或点击右上角的 'AI 生成' 按钮自动生成" 
            />
          </Form.Item>
          <div style={{ background: '#f0f9ff', padding: '12px', borderRadius: '6px', marginBottom: '16px', fontSize: '13px' }}>
            <strong>💡 提示：</strong>
            <ul style={{ margin: '8px 0 0 0', paddingLeft: '20px' }}>
              <li>输入员工名称后，点击"AI 生成"可自动生成系统提示词</li>
              <li>系统提示词定义了数字员工的角色、能力和行为规范</li>
              <li>可以在生成后手动修改以满足特定需求</li>
            </ul>
          </div>
          <Form.Item name="tool_ids" label="可用工具">
            <Select mode="multiple" placeholder="选择可用工具">
              {tools.map(t => (
                <Select.Option key={t.id} value={Number(t.id)}>{t.name}</Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>{editingItem ? '更新' : '创建'}</Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* AI生成工具 Modal */}
      <Modal
        title="AI 生成工具"
        open={isAiToolModalVisible}
        onCancel={() => {
          setIsAiToolModalVisible(false);
          aiToolForm.resetFields();
          setAiToolProgress(null);
          setGeneratedTool(null);
        }}
        footer={null}
        width={800}
      >
        <div style={{ marginBottom: '16px', padding: '12px', background: '#f0f9ff', borderRadius: '6px' }}>
          <strong>🤖 AI生成工具说明：</strong>
          <ul style={{ margin: '8px 0 0 0', paddingLeft: '20px', fontSize: '13px' }}>
            <li>使用自然语言描述您需要的工具功能</li>
            <li>AI会自动生成工具的名称、描述、参数和代码</li>
            <li>生成后可以预览和修改，然后创建工具</li>
            <li>支持选择不同的AI模型进行生成</li>
          </ul>
        </div>
        
        {!aiToolProgress && !generatedTool ? (
          <Form form={aiToolForm} onFinish={handleGenerateToolByAI} layout="vertical">
            <Form.Item 
              name="description" 
              label="工具描述" 
              rules={[{ required: true, message: '请输入工具描述' }]}
            >
              <TextArea 
                rows={4}
                placeholder="例如：创建一个查询天气的工具，输入城市名称，返回当前天气信息，包括温度、湿度、天气状况等"
              />
            </Form.Item>
            
            <Form.Item 
              name="model_id" 
              label="生成模型" 
              rules={[{ required: true, message: '请选择生成模型' }]}
            >
              <Select placeholder="选择AI模型进行生成">
                {models.map(m => (
                  <Select.Option key={m.id} value={m.id}>
                    {m.name}
                    <span style={{ fontSize: '12px', color: '#999', marginLeft: '8px' }}>
                      ({m.base_url})
                    </span>
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            
            <div style={{ marginTop: '16px', padding: '12px', background: '#fff7e6', borderRadius: '6px', fontSize: '13px' }}>
              <strong>💡 提示：</strong>
              <ul style={{ margin: '8px 0 0 0', paddingLeft: '20px' }}>
                <li>描述越详细，生成的工具越准确</li>
                <li>可以指定输入参数、输出格式等细节</li>
                <li>生成过程可能需要一些时间，请耐心等待</li>
                <li>生成后可以在手动添加工具界面进行修改</li>
              </ul>
            </div>
            
            <Form.Item style={{ marginTop: '16px', marginBottom: 0 }}>
              <Button 
                type="primary" 
                htmlType="submit" 
                block 
                size="large"
                style={{ 
                  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                  border: 'none'
                }}
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ marginRight: '6px' }}>
                  <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" strokeWidth="2"/>
                </svg>
                开始生成
              </Button>
            </Form.Item>
          </Form>
        ) : aiToolProgress && !generatedTool ? (
          <div className="ad-analyze-progress">
            <div className="ad-progress-header">
              <div className="ad-progress-title">
                {aiToolProgress.stage === 'start' && '🚀 准备生成...'}
                {aiToolProgress.stage === 'thinking' && '🤔 AI正在思考...'}
                {aiToolProgress.stage === 'generating' && '✨ 正在生成工具配置...'}
                {aiToolProgress.stage === 'parsing' && '📝 解析生成结果...'}
                {aiToolProgress.stage === 'validating' && '🔍 验证工具配置...'}
                {aiToolProgress.stage === 'validated' && '✅ 验证通过！'}
                {aiToolProgress.stage === 'complete' && '🎉 生成完成！'}
              </div>
            </div>
            
            <div style={{ 
              padding: '20px', 
              background: '#f9fafb', 
              borderRadius: '8px',
              marginTop: '16px',
              textAlign: 'center'
            }}>
              <div style={{ 
                fontSize: '14px', 
                color: '#6b7280',
                marginBottom: '12px'
              }}>
                {aiToolProgress.message}
              </div>
              
              <div className="ad-loading-spinner">
                <div className="ad-spinner"></div>
              </div>
            </div>
            
            <div style={{ 
              marginTop: '16px', 
              padding: '12px', 
              background: '#eff6ff', 
              borderRadius: '6px',
              fontSize: '13px',
              color: '#1e40af'
            }}>
              <strong>⏳ 请稍候：</strong> AI正在根据您的描述生成工具配置，这可能需要10-30秒...
            </div>
          </div>
        ) : generatedTool ? (
          <div className="ad-generated-tool-preview">
            <div style={{ 
              padding: '12px', 
              background: '#f0fdf4', 
              borderRadius: '6px',
              marginBottom: '16px',
              border: '1px solid #86efac'
            }}>
              <strong style={{ color: '#16a34a' }}>✅ 工具配置生成成功！</strong>
              <p style={{ margin: '8px 0 0 0', fontSize: '13px', color: '#15803d' }}>
                请预览生成的工具配置，确认无误后点击"使用此配置"按钮。
              </p>
            </div>
            
            <div className="ad-tool-preview-section">
              <div className="ad-tool-preview-label">工具名称</div>
              <div className="ad-tool-preview-value">{generatedTool.name}</div>
            </div>
            
            <div className="ad-tool-preview-section">
              <div className="ad-tool-preview-label">工具描述</div>
              <div className="ad-tool-preview-value">{generatedTool.description}</div>
            </div>
            
            <div className="ad-tool-preview-section">
              <div className="ad-tool-preview-label">工具类型</div>
              <div className="ad-tool-preview-value">
                {generatedTool.is_code_tool ? (
                  <span style={{ color: '#10b981', fontWeight: '600' }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ marginRight: '4px', verticalAlign: 'middle' }}>
                      <path d="M8 3L4 7l4 4M16 3l4 4-4 4M12 3v18" stroke="#10b981" strokeWidth="2"/>
                    </svg>
                    代码工具
                  </span>
                ) : (
                  <span style={{ color: '#6b7280' }}>API工具</span>
                )}
              </div>
            </div>
            
            <div className="ad-tool-preview-section">
              <div className="ad-tool-preview-label">参数配置</div>
              <pre className="ad-tool-preview-code">
                {JSON.stringify(generatedTool.parameters_schema, null, 2)}
              </pre>
            </div>
            
            {generatedTool.function_code && (
              <div className="ad-tool-preview-section">
                <div className="ad-tool-preview-label">函数代码</div>
                <pre className="ad-tool-preview-code">
                  {generatedTool.function_code}
                </pre>
              </div>
            )}
            
            <div style={{ 
              display: 'flex', 
              gap: '12px', 
              marginTop: '20px' 
            }}>
              <Button 
                type="primary" 
                size="large"
                block
                onClick={handleUseGeneratedTool}
                style={{ 
                  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                  border: 'none'
                }}
              >
                使用此配置
              </Button>
              <Button 
                size="large"
                onClick={() => {
                  setGeneratedTool(null);
                  setAiToolProgress(null);
                }}
              >
                重新生成
              </Button>
            </div>
          </div>
        ) : null}
      </Modal>

      {/* 工具调用记录 Modal */}
      <Modal
        title={`工具调用记录 - ${selectedTool?.name || ''}`}
        open={isToolLogsModalVisible}
        onCancel={() => {
          setIsToolLogsModalVisible(false);
          setToolCallLogs([]);
          setToolCallStats({});
          setSelectedTool(null);
        }}
        footer={null}
        width={1000}
      >
        {/* 统计信息 */}
        <div className="ad-tool-stats">
          <div className="ad-stat-card">
            <div className="ad-stat-icon" style={{ background: '#eff6ff' }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" stroke="#3b82f6" strokeWidth="2"/>
              </svg>
            </div>
            <div className="ad-stat-content">
              <div className="ad-stat-label">总调用次数</div>
              <div className="ad-stat-value">{toolCallStats.total_calls || 0}</div>
            </div>
          </div>
          
          <div className="ad-stat-card">
            <div className="ad-stat-icon" style={{ background: '#f0fdf4' }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="#10b981" strokeWidth="2"/>
              </svg>
            </div>
            <div className="ad-stat-content">
              <div className="ad-stat-label">成功率</div>
              <div className="ad-stat-value">{toolCallStats.success_rate || 0}%</div>
            </div>
          </div>
          
          <div className="ad-stat-card">
            <div className="ad-stat-icon" style={{ background: '#fef3c7' }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <path d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" stroke="#f59e0b" strokeWidth="2"/>
              </svg>
            </div>
            <div className="ad-stat-content">
              <div className="ad-stat-label">平均执行时间</div>
              <div className="ad-stat-value">{toolCallStats.avg_execution_time || 0}ms</div>
            </div>
          </div>
        </div>

        {/* 调用记录列表 */}
        {toolCallLogs.length === 0 ? (
          <div className="ad-empty-logs">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none">
              <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" stroke="#d1d5db" strokeWidth="2"/>
            </svg>
            <p>暂无调用记录</p>
          </div>
        ) : (
          <div className="ad-tool-logs-list">
            {toolCallLogs.map(log => (
              <div key={log.id} className={`ad-log-item ${log.status}`}>
                <div className="ad-log-header">
                  <span className="ad-log-time">
                    {new Date(log.timestamp).toLocaleString('zh-CN', {
                      year: 'numeric',
                      month: '2-digit',
                      day: '2-digit',
                      hour: '2-digit',
                      minute: '2-digit',
                      second: '2-digit'
                    })}
                  </span>
                  <span className={`ad-log-status ${log.status}`}>
                    {log.status === 'success' ? '✅ 成功' : '❌ 失败'}
                  </span>
                  <span className="ad-log-time-cost">
                    ⏱️ {log.execution_time}ms
                  </span>
                </div>
                
                <div className="ad-log-info">
                  <span>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ marginRight: '4px', verticalAlign: 'middle' }}>
                      <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" strokeWidth="2"/>
                    </svg>
                    员工：{log.employee_name}
                  </span>
                  {log.user_name && (
                    <span>
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ marginRight: '4px', verticalAlign: 'middle' }}>
                        <path d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" stroke="currentColor" strokeWidth="2"/>
                      </svg>
                      用户：{log.user_name}
                    </span>
                  )}
                  {log.room_name && (
                    <span>
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ marginRight: '4px', verticalAlign: 'middle' }}>
                        <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke="currentColor" strokeWidth="2"/>
                        <circle cx="9" cy="7" r="4" stroke="currentColor" strokeWidth="2"/>
                        <path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" stroke="currentColor" strokeWidth="2"/>
                      </svg>
                      房间：{log.room_name}
                    </span>
                  )}
                </div>
                
                <div className="ad-log-actions" style={{ marginTop: '12px', paddingTop: '12px', borderTop: '1px solid #f3f4f6' }}>
                  <button 
                    className="ad-btn-ghost" 
                    style={{ fontSize: '12px', padding: '4px 12px' }}
                    onClick={() => {
                      setSelectedLogDetail(log);
                      setIsLogDetailModalVisible(true);
                    }}
                  >
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" style={{ marginRight: '4px', verticalAlign: 'middle' }}>
                      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" stroke="currentColor" strokeWidth="2"/>
                      <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/>
                    </svg>
                    查看详情
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </Modal>

      {/* 调用记录详情 Modal */}
      <Modal
        title="调用记录详情"
        open={isLogDetailModalVisible}
        onCancel={() => {
          setIsLogDetailModalVisible(false);
          setSelectedLogDetail(null);
        }}
        footer={null}
        width={800}
      >
        {selectedLogDetail && (
          <div>
            {/* 基本信息 */}
            <div style={{ marginBottom: '20px', padding: '16px', background: '#f9fafb', borderRadius: '8px' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', fontSize: '13px' }}>
                <div>
                  <strong style={{ color: '#6b7280' }}>调用时间：</strong>
                  <span style={{ color: '#111827' }}>
                    {new Date(selectedLogDetail.timestamp).toLocaleString('zh-CN', {
                      year: 'numeric',
                      month: '2-digit',
                      day: '2-digit',
                      hour: '2-digit',
                      minute: '2-digit',
                      second: '2-digit'
                    })}
                  </span>
                </div>
                <div>
                  <strong style={{ color: '#6b7280' }}>执行状态：</strong>
                  <span className={`ad-log-status ${selectedLogDetail.status}`} style={{ marginLeft: '8px' }}>
                    {selectedLogDetail.status === 'success' ? '✅ 成功' : '❌ 失败'}
                  </span>
                </div>
                <div>
                  <strong style={{ color: '#6b7280' }}>执行时间：</strong>
                  <span style={{ color: '#111827' }}>{selectedLogDetail.execution_time}ms</span>
                </div>
                <div>
                  <strong style={{ color: '#6b7280' }}>数字员工：</strong>
                  <span style={{ color: '#111827' }}>{selectedLogDetail.employee_name}</span>
                </div>
                {selectedLogDetail.user_name && (
                  <div>
                    <strong style={{ color: '#6b7280' }}>触发用户：</strong>
                    <span style={{ color: '#111827' }}>{selectedLogDetail.user_name}</span>
                  </div>
                )}
                {selectedLogDetail.room_name && (
                  <div>
                    <strong style={{ color: '#6b7280' }}>所在房间：</strong>
                    <span style={{ color: '#111827' }}>{selectedLogDetail.room_name}</span>
                  </div>
                )}
              </div>
            </div>

            {/* 输入参数 */}
            <div style={{ marginBottom: '20px' }}>
              <h4 style={{ fontSize: '14px', fontWeight: '600', color: '#111827', marginBottom: '8px' }}>
                📥 输入参数
              </h4>
              <pre style={{
                background: '#f9fafb',
                border: '1px solid #e5e7eb',
                borderRadius: '6px',
                padding: '12px',
                fontFamily: 'Courier New, monospace',
                fontSize: '12px',
                lineHeight: '1.6',
                overflow: 'auto',
                margin: 0,
                whiteSpace: 'pre-wrap',
                wordWrap: 'break-word',
                maxHeight: '300px'
              }}>
                {JSON.stringify(selectedLogDetail.input_params, null, 2)}
              </pre>
            </div>

            {/* 输出结果或错误信息 */}
            {selectedLogDetail.status === 'success' ? (
              <div>
                <h4 style={{ fontSize: '14px', fontWeight: '600', color: '#111827', marginBottom: '8px' }}>
                  📤 输出结果
                </h4>
                <pre style={{
                  background: '#f0fdf4',
                  border: '1px solid #bbf7d0',
                  borderRadius: '6px',
                  padding: '12px',
                  fontFamily: 'Courier New, monospace',
                  fontSize: '12px',
                  lineHeight: '1.6',
                  color: '#166534',
                  overflow: 'auto',
                  margin: 0,
                  whiteSpace: 'pre-wrap',
                  wordWrap: 'break-word',
                  maxHeight: '300px'
                }}>
                  {selectedLogDetail.output_result}
                </pre>
              </div>
            ) : (
              <div>
                <h4 style={{ fontSize: '14px', fontWeight: '600', color: '#111827', marginBottom: '8px' }}>
                  ❌ 错误信息
                </h4>
                <pre style={{
                  background: '#fef2f2',
                  border: '1px solid #fecaca',
                  borderRadius: '6px',
                  padding: '12px',
                  fontFamily: 'Courier New, monospace',
                  fontSize: '12px',
                  lineHeight: '1.6',
                  color: '#991b1b',
                  overflow: 'auto',
                  margin: 0,
                  whiteSpace: 'pre-wrap',
                  wordWrap: 'break-word',
                  maxHeight: '300px'
                }}>
                  {selectedLogDetail.error_message}
                </pre>
              </div>
            )}
          </div>
        )}
      </Modal>

      {/* AI分析 Modal */}
      <Modal
        title="AI 消息分析"
        open={isAnalyzeModalVisible}
        onCancel={() => {
          setIsAnalyzeModalVisible(false);
          analyzeForm.resetFields();
          setAnalyzeProgress(null);
          setAnalyzingMessages([]);
        }}
        footer={null}
        width={700}
      >
        <div style={{ marginBottom: '16px', padding: '12px', background: '#f0f9ff', borderRadius: '6px' }}>
          <strong>🤖 AI分析说明：</strong>
          <ul style={{ margin: '8px 0 0 0', paddingLeft: '20px', fontSize: '13px' }}>
            <li>选择时间段内的消息进行分析</li>
            <li>AI模型会判断消息是否包含敏感内容</li>
            <li>分析结果会自动保存到数据库</li>
            <li>可用于后续的统计和审核</li>
          </ul>
        </div>
        
        {!analyzeProgress ? (
          <Form form={analyzeForm} onFinish={handleAnalyzeSensitive} layout="vertical">
            <Form.Item name="start_date" label="开始时间">
              <Input 
                type="datetime-local" 
                placeholder="选择开始时间"
              />
            </Form.Item>
            <Form.Item name="end_date" label="结束时间">
              <Input 
                type="datetime-local" 
                placeholder="选择结束时间"
              />
            </Form.Item>
            <Form.Item name="model_id" label="分析模型" rules={[{ required: true, message: '请选择分析模型' }]}>
              <Select placeholder="选择AI模型进行分析">
                {models.map(m => (
                  <Select.Option key={m.id} value={m.id}>
                    {m.name}
                    <span style={{ fontSize: '12px', color: '#999', marginLeft: '8px' }}>
                      ({m.base_url})
                    </span>
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            
            <div style={{ marginTop: '16px', padding: '12px', background: '#fff7e6', borderRadius: '6px', fontSize: '13px' }}>
              <strong>💡 提示：</strong>
              <ul style={{ margin: '8px 0 0 0', paddingLeft: '20px' }}>
                <li>不选择时间段将分析所有消息</li>
                <li>时间选择器使用本地时间（东八区）</li>
                <li>建议选择合适的时间范围以提高效率</li>
                <li>分析过程可能需要一些时间，请耐心等待</li>
              </ul>
            </div>
            
            <Form.Item style={{ marginTop: '16px', marginBottom: 0 }}>
              <Button type="primary" htmlType="submit" block size="large">
                开始分析
              </Button>
            </Form.Item>
          </Form>
        ) : (
          <div className="ad-analyze-progress">
            <div className="ad-progress-header">
              <div className="ad-progress-title">正在分析消息...</div>
              <div className="ad-progress-status">
                {analyzeProgress.analyzed} / {analyzeProgress.total}
              </div>
            </div>
            
            <div className="ad-progress-bar-wrap">
              <div className="ad-progress-bar">
                <div 
                  className="ad-progress-bar-fill" 
                  style={{ width: `${(analyzeProgress.analyzed / analyzeProgress.total) * 100}%` }}
                />
              </div>
              <div className="ad-progress-text">
                <span>进度: {Math.round((analyzeProgress.analyzed / analyzeProgress.total) * 100)}%</span>
                <span>敏感消息: {analyzeProgress.sensitive_found}</span>
              </div>
            </div>
            
            <div style={{ marginBottom: '12px', fontSize: '13px', color: '#6b7280' }}>
              <strong>分析详情：</strong>
            </div>
            
            <div className="ad-progress-messages">
              {analyzingMessages.map((msg, idx) => (
                <div 
                  key={idx} 
                  className={`ad-progress-message ${msg.status}`}
                >
                  <div className="ad-progress-message-icon">
                    {msg.status === 'analyzing' && '🔄'}
                    {msg.status === 'normal' && '✅'}
                    {msg.status === 'sensitive' && '⚠️'}
                  </div>
                  <div className="ad-progress-message-content">
                    {msg.content}
                  </div>
                  {msg.status !== 'analyzing' && (
                    <div className={`ad-progress-message-result ${msg.status}`}>
                      {msg.is_sensitive ? '敏感' : '正常'}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default AdminDashboard;
