page.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. "use client";
  2. import { useState, useEffect } from "react";
  3. import { useRouter } from "next/navigation";
  4. import { ResponsiveLayout } from "@/components/layout";
  5. import { Button } from "@/components/ui/button";
  6. import { Input } from "@/components/ui/input";
  7. import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
  8. import {
  9. fetchAIConfigs,
  10. createAIConfig,
  11. updateAIConfig,
  12. deleteAIConfig,
  13. type AIConfig,
  14. type CreateAIConfigRequest,
  15. type UpdateAIConfigRequest,
  16. } from "@/features/agent/services/aiConfigApi";
  17. import { useProfile } from "@/features/agent/hooks/useProfile";
  18. import { API_BASE_URL } from "@/lib/config";
  19. import { Checkbox } from "@/components/ui/checkbox";
  20. import { Label } from "@/components/ui/label";
  21. interface SettingsPageProps {
  22. embedded?: boolean; // 是否嵌入模式(不使用 ResponsiveLayout)
  23. }
  24. export default function SettingsPage({ embedded = false }: SettingsPageProps = {}) {
  25. const router = useRouter();
  26. const [userId, setUserId] = useState<number | null>(null);
  27. const [configs, setConfigs] = useState<AIConfig[]>([]);
  28. const [loading, setLoading] = useState(true);
  29. const [editingId, setEditingId] = useState<number | null>(null);
  30. const [formData, setFormData] = useState<CreateAIConfigRequest>({
  31. provider: "",
  32. api_url: "",
  33. api_key: "",
  34. model: "",
  35. model_type: "text",
  36. is_active: true,
  37. is_public: false,
  38. description: "",
  39. });
  40. const [submitting, setSubmitting] = useState(false);
  41. const [error, setError] = useState("");
  42. // 检查登录状态
  43. useEffect(() => {
  44. const storedUserId = localStorage.getItem("agent_user_id");
  45. if (!storedUserId) {
  46. router.push("/");
  47. return;
  48. }
  49. setUserId(Number.parseInt(storedUserId, 10));
  50. }, [router]);
  51. // 加载个人资料(用于获取和更新 AI 对话接收设置)
  52. const {
  53. profile,
  54. loading: profileLoading,
  55. update: updateProfile,
  56. } = useProfile({
  57. userId: userId ?? null,
  58. enabled: Boolean(userId),
  59. });
  60. // 加载配置列表
  61. const loadConfigs = async () => {
  62. if (!userId) return;
  63. try {
  64. setLoading(true);
  65. const data = await fetchAIConfigs(userId);
  66. setConfigs(data);
  67. } catch (error) {
  68. console.error("加载配置失败:", error);
  69. setError("加载配置失败");
  70. } finally {
  71. setLoading(false);
  72. }
  73. };
  74. useEffect(() => {
  75. if (userId) {
  76. loadConfigs();
  77. }
  78. }, [userId]);
  79. // 重置表单
  80. const resetForm = () => {
  81. setFormData({
  82. provider: "",
  83. api_url: "",
  84. api_key: "",
  85. model: "",
  86. model_type: "text",
  87. is_active: true,
  88. is_public: false,
  89. description: "",
  90. });
  91. setEditingId(null);
  92. setError("");
  93. };
  94. // 开始编辑
  95. const handleEdit = (config: AIConfig) => {
  96. setFormData({
  97. provider: config.provider,
  98. api_url: config.api_url,
  99. api_key: "", // 不显示 API Key(已加密)
  100. model: config.model,
  101. model_type: config.model_type,
  102. is_active: config.is_active,
  103. is_public: config.is_public,
  104. description: config.description,
  105. });
  106. setEditingId(config.id);
  107. };
  108. // 提交表单
  109. const handleSubmit = async (e: React.FormEvent) => {
  110. e.preventDefault();
  111. if (!userId) return;
  112. setSubmitting(true);
  113. setError("");
  114. try {
  115. if (editingId) {
  116. // 更新配置
  117. const updateData: UpdateAIConfigRequest = {
  118. provider: formData.provider,
  119. api_url: formData.api_url,
  120. model: formData.model,
  121. model_type: formData.model_type,
  122. is_active: formData.is_active,
  123. is_public: formData.is_public,
  124. description: formData.description,
  125. };
  126. // 如果提供了新的 API Key,才更新
  127. if (formData.api_key) {
  128. updateData.api_key = formData.api_key;
  129. }
  130. await updateAIConfig(userId, editingId, updateData);
  131. } else {
  132. // 创建配置
  133. await createAIConfig(userId, formData);
  134. }
  135. resetForm();
  136. await loadConfigs();
  137. } catch (error) {
  138. setError((error as Error).message || "操作失败");
  139. } finally {
  140. setSubmitting(false);
  141. }
  142. };
  143. // 删除配置
  144. const handleDelete = async (id: number) => {
  145. if (!userId) return;
  146. if (!confirm("确定要删除这个配置吗?")) return;
  147. try {
  148. await deleteAIConfig(userId, id);
  149. await loadConfigs();
  150. } catch (error) {
  151. setError((error as Error).message || "删除失败");
  152. }
  153. };
  154. // 退出登录
  155. const handleLogout = async () => {
  156. try {
  157. await fetch(`${API_BASE_URL}/logout`, { method: "POST" });
  158. } catch (error) {
  159. console.error("退出登录失败:", error);
  160. } finally {
  161. localStorage.removeItem("agent_user_id");
  162. localStorage.removeItem("agent_username");
  163. localStorage.removeItem("agent_role");
  164. router.push("/");
  165. }
  166. };
  167. if (!userId) {
  168. return null;
  169. }
  170. // 构建头部内容
  171. const headerContent = (
  172. <div className="bg-card border-b p-4 shadow-sm">
  173. <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
  174. <div>
  175. <h1 className="text-xl font-bold text-foreground">AI 配置管理</h1>
  176. <div className="text-sm text-muted-foreground mt-1">管理 AI 服务商配置</div>
  177. </div>
  178. {!embedded && (
  179. <div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
  180. <Button
  181. onClick={() => router.push("/agent/dashboard")}
  182. variant="outline"
  183. size="sm"
  184. className="w-full sm:w-auto"
  185. >
  186. 返回工作台
  187. </Button>
  188. <Button
  189. onClick={handleLogout}
  190. variant="outline"
  191. size="sm"
  192. className="w-full sm:w-auto"
  193. >
  194. 退出登录
  195. </Button>
  196. </div>
  197. )}
  198. </div>
  199. </div>
  200. );
  201. // 构建主内容区
  202. const mainContent = (
  203. <div className="flex-1 overflow-auto p-4 md:p-6">
  204. <div className="max-w-6xl mx-auto space-y-6">
  205. {/* 全局设置 */}
  206. <Card>
  207. <CardHeader>
  208. <CardTitle>全局设置</CardTitle>
  209. </CardHeader>
  210. <CardContent>
  211. <div className="flex items-center space-x-2">
  212. <Checkbox
  213. id="receive_ai_conversations"
  214. checked={!(profile?.receive_ai_conversations ?? false)}
  215. onCheckedChange={async (checked) => {
  216. if (userId) {
  217. try {
  218. await updateProfile({
  219. receive_ai_conversations: !checked,
  220. });
  221. } catch (error) {
  222. console.error("更新设置失败:", error);
  223. alert("更新设置失败,请重试");
  224. }
  225. }
  226. }}
  227. disabled={profileLoading}
  228. />
  229. <Label
  230. htmlFor="receive_ai_conversations"
  231. className="text-sm font-medium cursor-pointer"
  232. >
  233. 客服不接收 AI 对话
  234. </Label>
  235. </div>
  236. <p className="text-xs text-muted-foreground mt-2">
  237. 开启后,AI 对话将不会显示在对话列表中,也不会收到 AI 消息通知。
  238. 但您仍可以在会话页面手动开启&quot;显示 AI 消息&quot;来查看 AI 对话历史。
  239. </p>
  240. </CardContent>
  241. </Card>
  242. {/* 配置表单 */}
  243. <Card>
  244. <CardHeader>
  245. <CardTitle>
  246. {editingId ? "编辑 AI 配置" : "添加 AI 配置"}
  247. </CardTitle>
  248. </CardHeader>
  249. <CardContent>
  250. <form onSubmit={handleSubmit} className="space-y-4">
  251. {error && (
  252. <div className="p-3 bg-red-50 border border-red-200 rounded-md text-red-600 text-sm">
  253. {error}
  254. </div>
  255. )}
  256. <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
  257. <div>
  258. <label className="block text-sm font-medium mb-1">
  259. 服务商名称 <span className="text-red-500">*</span>
  260. </label>
  261. <Input
  262. value={formData.provider}
  263. onChange={(e) =>
  264. setFormData({ ...formData, provider: e.target.value })
  265. }
  266. placeholder="例如:OpenAI、Claude、自定义"
  267. required
  268. />
  269. </div>
  270. <div>
  271. <label className="block text-sm font-medium mb-1">
  272. API 地址 <span className="text-red-500">*</span>
  273. </label>
  274. <Input
  275. value={formData.api_url}
  276. onChange={(e) =>
  277. setFormData({ ...formData, api_url: e.target.value })
  278. }
  279. placeholder="https://api.openai.com/v1/chat/completions"
  280. required
  281. />
  282. </div>
  283. <div>
  284. <label className="block text-sm font-medium mb-1">
  285. API Key <span className="text-red-500">*</span>
  286. </label>
  287. <Input
  288. type="password"
  289. value={formData.api_key}
  290. onChange={(e) =>
  291. setFormData({ ...formData, api_key: e.target.value })
  292. }
  293. placeholder={editingId ? "留空则不更新" : "输入 API Key"}
  294. required={!editingId}
  295. />
  296. </div>
  297. <div>
  298. <label className="block text-sm font-medium mb-1">
  299. 模型名称 <span className="text-red-500">*</span>
  300. </label>
  301. <Input
  302. value={formData.model}
  303. onChange={(e) =>
  304. setFormData({ ...formData, model: e.target.value })
  305. }
  306. placeholder="例如:gpt-3.5-turbo、gpt-4"
  307. required
  308. />
  309. </div>
  310. <div>
  311. <label className="block text-sm font-medium mb-1">
  312. 模型类型
  313. </label>
  314. <select
  315. value={formData.model_type}
  316. onChange={(e) =>
  317. setFormData({ ...formData, model_type: e.target.value })
  318. }
  319. className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-primary"
  320. >
  321. <option value="text">文本</option>
  322. <option value="image">图片</option>
  323. <option value="audio">语音</option>
  324. <option value="video">视频</option>
  325. </select>
  326. </div>
  327. </div>
  328. <div>
  329. <label className="block text-sm font-medium mb-1">
  330. 配置描述
  331. </label>
  332. <Input
  333. value={formData.description}
  334. onChange={(e) =>
  335. setFormData({ ...formData, description: e.target.value })
  336. }
  337. placeholder="例如:OpenAI GPT-3.5 Turbo 模型"
  338. />
  339. </div>
  340. <div className="flex items-center gap-4">
  341. <label className="flex items-center gap-2">
  342. <input
  343. type="checkbox"
  344. checked={formData.is_active}
  345. onChange={(e) =>
  346. setFormData({ ...formData, is_active: e.target.checked })
  347. }
  348. className="w-4 h-4"
  349. />
  350. <span className="text-sm">启用配置</span>
  351. </label>
  352. <label className="flex items-center gap-2">
  353. <input
  354. type="checkbox"
  355. checked={formData.is_public}
  356. onChange={(e) =>
  357. setFormData({ ...formData, is_public: e.target.checked })
  358. }
  359. className="w-4 h-4"
  360. />
  361. <span className="text-sm">开放给访客使用</span>
  362. </label>
  363. </div>
  364. <div className="flex gap-2">
  365. <Button type="submit" disabled={submitting}>
  366. {submitting
  367. ? "提交中..."
  368. : editingId
  369. ? "更新配置"
  370. : "创建配置"}
  371. </Button>
  372. {editingId && (
  373. <Button
  374. type="button"
  375. variant="outline"
  376. onClick={resetForm}
  377. >
  378. 取消
  379. </Button>
  380. )}
  381. </div>
  382. </form>
  383. </CardContent>
  384. </Card>
  385. {/* 配置列表 */}
  386. <Card>
  387. <CardHeader>
  388. <CardTitle>已配置的 AI 服务</CardTitle>
  389. </CardHeader>
  390. <CardContent>
  391. {loading ? (
  392. <div className="text-center py-8 text-gray-500">
  393. 加载中...
  394. </div>
  395. ) : configs.length === 0 ? (
  396. <div className="text-center py-8 text-gray-500">
  397. 暂无配置,请添加
  398. </div>
  399. ) : (
  400. <div className="space-y-4">
  401. {configs.map((config) => (
  402. <div
  403. key={config.id}
  404. className="p-4 border rounded-lg hover:shadow-md transition-shadow"
  405. >
  406. <div className="flex justify-between items-start">
  407. <div className="flex-1">
  408. <div className="flex items-center gap-2 mb-2">
  409. <h3 className="font-semibold">
  410. {config.provider} - {config.model}
  411. </h3>
  412. {config.is_active && (
  413. <span className="px-2 py-1 text-xs bg-green-100 text-green-800 rounded">
  414. 启用
  415. </span>
  416. )}
  417. {config.is_public && (
  418. <span className="px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded">
  419. 开放
  420. </span>
  421. )}
  422. </div>
  423. <div className="text-sm text-gray-600 space-y-1">
  424. <p>
  425. <span className="font-medium">API 地址:</span>
  426. {config.api_url}
  427. </p>
  428. <p>
  429. <span className="font-medium">模型类型:</span>
  430. {config.model_type}
  431. </p>
  432. {config.description && (
  433. <p>
  434. <span className="font-medium">描述:</span>
  435. {config.description}
  436. </p>
  437. )}
  438. </div>
  439. </div>
  440. <div className="flex gap-2">
  441. <Button
  442. size="sm"
  443. variant="outline"
  444. onClick={() => handleEdit(config)}
  445. >
  446. 编辑
  447. </Button>
  448. <Button
  449. size="sm"
  450. variant="destructive"
  451. onClick={() => handleDelete(config.id)}
  452. >
  453. 删除
  454. </Button>
  455. </div>
  456. </div>
  457. </div>
  458. ))}
  459. </div>
  460. )}
  461. </CardContent>
  462. </Card>
  463. </div>
  464. </div>
  465. );
  466. // 如果是嵌入模式,只返回内容,不包含 ResponsiveLayout
  467. if (embedded) {
  468. return (
  469. <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
  470. {headerContent}
  471. {mainContent}
  472. </div>
  473. );
  474. }
  475. return (
  476. <ResponsiveLayout
  477. main={mainContent}
  478. header={headerContent}
  479. />
  480. );
  481. }