page.tsx 17 KB

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