addUpdate.vue
23.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { assistantCreate, assistantDetail, assistantUpdate } from "@/api/assistant";
import { uploadFile } from "@/utils/upload";
import { Delete, Document } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
const router = useRouter();
const route = useRoute();
// 判断是新增还是编辑模式
const isEditMode = computed(() => !!route.params.id);
const agentId = computed(() => {
const id = route.params.id;
return id ? String(id) : undefined;
});
// 加载状态
const loading = ref(false);
const saving = ref(false);
const saveTimer = ref(null); // 防抖定时器
// 表单数据(匹配接口结构)
const formData = reactive({
id: 0,
agentName: "", // 智能体名称
avatarUrl: "", // 头像
personaPromptDetail: "", // 人设提示词
associatedWeworkRoleId: 0, // 企微角色关联(数字ID)
companionScenarioPromptDetail: "", // 陪伴场景提示词
jobDescriptionFileUrl: "", // 岗位说明书文件URL
});
// 级联选择器的值(用于UI显示,数组格式)
const cascaderValue = ref([]);
// 文件显示信息(用于UI显示)
const fileInfo = ref({
name: "",
url: "",
});
// 部门数据 (级联选择器)
const departmentOptions = ref([]);
// 加载部门树数据
const loadDeptTree = async () => {
try {
// 先从 sessionStorage 读取
const cachedData = sessionStorage.getItem("deptTreeData");
if (cachedData) {
try {
const parsedData = JSON.parse(cachedData);
departmentOptions.value = parsedData;
} catch (error) {
console.warn("解析缓存的部门数据失败:", error);
}
}
} catch {
ElMessage.error("加载部门数据失败,请稍后重试");
departmentOptions.value = [];
}
};
const formRef = ref(null);
// 表单校验规则
const rules = {
agentName: [
{ required: true, message: "请输入智能体名称", trigger: "blur" },
{ max: 50, message: "智能体名称不能超过50个字符", trigger: "blur" },
],
personaPromptDetail: [
{ required: true, message: "请输入人设提示词", trigger: "blur" },
{ max: 5000, message: "人设提示词不能超过5000个字符", trigger: "blur" },
],
associatedWeworkRoleId: [
{
validator: (rule, value, callback) => {
if (!value || value === 0) {
callback(new Error("请选择企微角色关联"));
} else {
callback();
}
},
trigger: "change",
},
],
companionScenarioPromptDetail: [
{ required: true, message: "请输入陪伴场景提示词", trigger: "blur" },
{ max: 5000, message: "陪伴场景提示词不能超过5000个字符", trigger: "blur" },
],
};
// 加载详情数据
const loadAgentData = async (id) => {
try {
loading.value = true;
const response = await assistantDetail({ id });
// 根据实际 API 返回结构解析数据
const data = response?.data || response || {};
// 映射 API 数据到表单字段
formData.id = data.id || 0;
formData.agentName = data.agentName || "";
formData.avatarUrl = data.avatarUrl || "";
formData.personaPromptDetail = data.personaPromptDetail || "";
formData.companionScenarioPromptDetail = data.companionScenarioPromptDetail || "";
formData.associatedWeworkRoleId = data.associatedWeworkRoleId || 0;
formData.jobDescriptionFileUrl = data.jobDescriptionFileUrl || "";
// 处理级联选择器的值(需要根据 departmentId 找到对应的路径数组)
if (formData.associatedWeworkRoleId) {
// 根据 departmentId 查找在部门树中的路径
const findPath = (options, targetId, path = []) => {
for (const option of options) {
const currentPath = [ ...path, option.departmentId ];
if (option.departmentId === targetId) {
return currentPath;
}
if (option.children && option.children.length > 0) {
const found = findPath(option.children, targetId, currentPath);
if (found) return found;
}
}
return null;
};
const path = findPath(departmentOptions.value, formData.associatedWeworkRoleId);
if (path) {
cascaderValue.value = path;
}
}
// 处理文件信息(用于UI显示)
if (formData.jobDescriptionFileUrl) {
fileInfo.value = {
name: formData.jobDescriptionFileUrl.split("/").pop() || "文件",
url: formData.jobDescriptionFileUrl,
};
} else {
fileInfo.value = { name: "", url: "" };
}
} catch (error) {
console.error("加载详情数据失败:", error);
ElMessage.error("加载详情数据失败,请稍后重试");
// 加载失败时返回列表页
setTimeout(() => {
router.push("/assistant");
}, 1500);
} finally {
loading.value = false;
}
};
// 初始化数据(编辑模式下加载数据)
onMounted(async () => {
// 先加载部门树数据
await loadDeptTree();
// 如果是编辑模式,加载详情数据
if (isEditMode.value && agentId.value) {
loadAgentData(agentId.value);
}
});
// 方法
const goBack = () => {
router.push("/assistant");
};
/**
* 通用文件验证函数
* @param {File} file 文件对象
* @param {object} config 验证配置
* @param {string[]} [config.allowedTypes] 允许的 MIME 类型
* @param {string[]} [config.allowedExtensions] 允许的文件扩展名
* @param {number} [config.maxSize] 最大文件大小(字节)
* @param {string} config.errorMessage 错误提示信息
* @returns {boolean} 验证是否通过
*/
const validateFile = (file, config) => {
const { allowedTypes = [], allowedExtensions = [], maxSize, errorMessage } = config;
// 验证文件大小
if (maxSize && file.size > maxSize) {
ElMessage.error(`文件大小不能超过${(maxSize / 1024 / 1024).toFixed(0)}MB`);
return false;
}
// 验证文件类型
const fileType = file.type || "";
const fileName = file.name || "";
const fileExtension = fileName.split(".").pop()?.toLowerCase() || "";
const isValidType = allowedTypes.length > 0 && allowedTypes.includes(fileType);
const isValidExtension = allowedExtensions.length > 0 && allowedExtensions.includes(fileExtension);
if (allowedTypes.length > 0 && allowedExtensions.length > 0) {
// 同时验证 MIME 类型和扩展名
if (!isValidType && !isValidExtension) {
ElMessage.error(errorMessage);
return false;
}
} else if (allowedTypes.length > 0) {
// 仅验证 MIME 类型
if (!isValidType) {
ElMessage.error(errorMessage);
return false;
}
} else if (allowedExtensions.length > 0 && // 仅验证扩展名
!isValidExtension) {
ElMessage.error(errorMessage);
return false;
}
return true;
};
/**
* 通用文件上传处理函数
* @param {File} file 文件对象
* @param {object} config 上传配置
* @param {object} config.validation 验证配置
* @param {Function} config.onSuccess 成功回调函数
* @param {Function} [config.onError] 失败回调函数
* @param {string} [config.successMessage] 成功提示信息
* @param {string} [config.errorMessage] 失败提示信息
*/
const handleFileUpload = async (file, config) => {
// 验证文件
if (!validateFile(file, config.validation)) {
return;
}
try {
// 上传文件到OSS
const result = await uploadFile(file, {
onSuccess: (uploadResult) => {
console.log("文件上传成功,响应结果:", uploadResult);
},
onError: (error) => {
console.error("文件上传失败:", error);
},
});
// 上传成功后处理
if (result?.aliyunAddress) {
config.onSuccess(result.aliyunAddress);
if (config.successMessage) {
ElMessage.success(config.successMessage);
}
} else {
throw new Error("上传结果中缺少文件地址");
}
} catch (error) {
console.error("文件上传失败:", error);
ElMessage.error(config.errorMessage || "文件上传失败,请稍后重试");
config.onError?.();
}
};
// 处理头像上传
const handleAvatarChange = async (file) => {
if (!file?.raw) {
ElMessage.error("请选择有效的文件");
return;
}
// 先使用本地预览,提升用户体验
const previewUrl = URL.createObjectURL(file.raw);
await handleFileUpload(
file.raw,
{
validation: {
allowedTypes: [ "image/jpeg", "image/jpg", "image/png", "image/gif", "image/bmp", "image/webp" ],
allowedExtensions: [ "jpg", "jpeg", "png", "gif", "bmp", "webp" ],
errorMessage: "文件格式错误,仅支持 JPG、PNG、GIF、BMP、WEBP 等图片格式",
},
onSuccess: (url) => {
// 释放本地预览URL,避免内存泄漏
URL.revokeObjectURL(previewUrl);
formData.avatarUrl = url;
console.log("头像上传成功,最终URL:", url);
},
onError: () => {
// 上传失败时清除预览
URL.revokeObjectURL(previewUrl);
formData.avatarUrl = "";
},
successMessage: "头像上传成功",
errorMessage: "头像上传失败,请稍后重试",
},
);
};
// 处理文件上传
const handleFileChange = async (file) => {
if (!file?.raw) {
ElMessage.error("请选择有效的文件");
return;
}
await handleFileUpload(
file.raw,
{
validation: {
allowedTypes: [ "application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ],
allowedExtensions: [ "pdf", "doc", "docx" ],
maxSize: 10 * 1024 * 1024, // 50MB
errorMessage: "文件格式错误,仅支持 PDF、Word 格式",
},
onSuccess: (url) => {
formData.jobDescriptionFileUrl = url;
fileInfo.value = {
name: file.name,
url,
};
console.log("文件上传成功,最终URL:", url);
},
onError: () => {
// 上传失败时清除文件信息
formData.jobDescriptionFileUrl = "";
fileInfo.value = { name: "", url: "" };
},
successMessage: "文件上传成功",
errorMessage: "文件上传失败,请稍后重试",
},
);
};
// 移除文件
const removeFile = () => {
formData.jobDescriptionFileUrl = "";
fileInfo.value = { name: "", url: "" };
};
// 处理级联选择器变化
const handleCascaderChange = (value) => {
cascaderValue.value = value || [];
// 取最后一个值作为 associatedWeworkRoleId
if (value && value.length > 0) {
formData.associatedWeworkRoleId = value[value.length - 1];
} else {
formData.associatedWeworkRoleId = 0;
}
// 触发校验
if (formRef.value) {
formRef.value.validateField("associatedWeworkRoleId");
}
};
// 实际保存逻辑
const doSave = async () => {
// 表单校验
if (!formRef.value) return;
try {
await formRef.value.validate();
} catch {
ElMessage.warning("请完善表单信息");
return;
}
// 校验级联选择器
if (!formData.associatedWeworkRoleId || formData.associatedWeworkRoleId === 0) {
ElMessage.warning("请选择企微角色关联");
return;
}
try {
saving.value = true;
// 构建提交数据(匹配接口结构)
const submitData = {
id: isEditMode.value ? Number(agentId.value) : 0,
agentName: formData.agentName,
avatarUrl: formData.avatarUrl,
associatedWeworkRoleId: formData.associatedWeworkRoleId,
personaPromptDetail: formData.personaPromptDetail,
companionScenarioPromptDetail: formData.companionScenarioPromptDetail,
jobDescriptionFileUrl: formData.jobDescriptionFileUrl,
};
// 调用API保存数据
if (isEditMode.value) {
await assistantUpdate(submitData);
ElMessage.success("更新成功");
} else {
await assistantCreate(submitData);
ElMessage.success("创建成功");
}
// 保存成功后返回列表页
setTimeout(() => {
router.push("/assistant");
}, 1000);
} catch (error) {
console.error("保存失败:", error);
ElMessage.error(isEditMode.value ? "更新失败,请稍后重试" : "创建失败,请稍后重试");
} finally {
saving.value = false;
}
};
// 保存表单(带防抖)
const save = () => {
// 如果正在保存中,直接返回
if (saving.value) {
return;
}
// 清除之前的定时器
if (saveTimer.value) {
clearTimeout(saveTimer.value);
}
// 设置新的定时器,300ms 后执行保存
saveTimer.value = setTimeout(() => {
doSave();
}, 300);
};
const cancel = () => {
router.push("/assistant");
};
</script>
<template>
<div v-loading="loading" class="w-full px-10 py-5 mx-auto bg-white">
<!-- 顶部标题栏 -->
<div class="flex items-center justify-between pb-[10px]">
<h2 class="m-0 text-lg font-semibold">
{{ isEditMode ? '编辑智能体' : '新增智能体' }}
</h2>
<!-- <el-button @click="goBack">返回列表</el-button> -->
<div class="w-[88px] h-[32px] rounded-[5px] border border-[#E1E3E6] bg-white flex items-center justify-center cursor-pointer text-[#666666] text-[14px] hover:bg-[#ecf5ff] hover:text-[#1956fe] transition-all duration-200" @click="goBack">
返回列表
</div>
</div>
<el-form ref="formRef"
class="form-content"
label-position="top"
:model="formData"
:rules="rules">
<!-- 1. 基本信息 -->
<div class="mb-10">
<CustomHeaderTitle title="基本信息" />
<el-form-item label="智能体名称"
prop="agentName"
required>
<el-input v-model="formData.agentName"
class="w-[376px]"
maxlength="50"
placeholder="请输入名称"
show-word-limit />
</el-form-item>
<el-form-item label="智能体头像">
<div class="relative w-[80px] h-[80px] bg-white">
<!--预览图 -->
<el-avatar class="bg-[#F7F8F9]"
shape="circle"
:size="80"
:src="formData.avatarUrl" />
<!-- 上传组件 -->
<div class="absolute w-[28px] h-[28px] right-0 bottom-[-10px] flex items-center justify-center w-6 h-6 text-[#409eff] cursor-pointer rounded-full shadow-sm bg-g-white">
<el-upload accept="image/jpeg,image/jpg,image/png,image/gif,image/bmp,image/webp"
action="#"
:auto-upload="false"
class="avatar-uploader"
:on-change="handleAvatarChange"
:show-file-list="false">
<img alt="edit" src="/images/icon-upload-avatar.png">
<!-- <el-icon class="text-sm"><EditPen /></el-icon> -->
</el-upload>
</div>
</div>
</el-form-item>
</div>
<!-- 2. 人设配置 -->
<div class="mb-10">
<CustomHeaderTitle title="人设配置" />
<el-form-item label="人设提示词"
prop="personaPromptDetail"
required>
<el-input v-model="formData.personaPromptDetail"
class="w-[776px]"
maxlength="5000"
placeholder="请输入人设提示词."
:rows="4"
show-word-limit
type="textarea" />
</el-form-item>
</div>
<!-- 3. 岗位配置 -->
<div class="mb-10">
<CustomHeaderTitle title="岗位配置" />
<div class="flex gap-10">
<!-- 左侧:组织架构选择 -->
<div class="flex-1">
<el-form-item label="企微角色关联"
prop="associatedWeworkRoleId"
required>
<el-cascader v-model="cascaderValue"
class="w-[376px] custom-cascader"
clearable
:options="departmentOptions"
placeholder="请选择部门"
popper-class="custom-cascader-popper"
:props="{ value: 'departmentId', label: 'departmentName', children: 'children' }"
@change="handleCascaderChange" />
</el-form-item>
</div>
<!-- 右侧:留白或说明,图中右侧为空白,维持布局平衡 -->
<div class="flex-1"></div>
</div>
<div class="flex gap-10 mt-5">
<!-- 岗位说明书 -->
<div class="flex">
<el-form-item label="岗位说明书">
<div class="flex flex-col">
<el-upload accept=".pdf,.doc,.docx"
action="#"
:auto-upload="false"
class="upload-demo"
:on-change="handleFileChange"
:show-file-list="false">
<div class="flex items-center justify-center cursor-pointer w-[98px] h-[32px] rounded-[5px] border border-[#E1E3E6] bg-white hover:bg-[#ecf5ff] hover:text-[#1956fe] transition-all duration-200">
<img alt="upload-file"
class="w-[16px] h-[16px] mr-[4px]"
src="/images/icon-upload.png"> <span>选择文件</span>
</div>
</el-upload>
<div class="mt-[5px] text-[12px] text-[#909399]">
支持pdf, word格式,大小在10M以内
</div>
<!-- 已上传文件显示 -->
<div v-if="fileInfo.name" class="mt-2 flex items-center gap-2">
<div class="flex items-center gap-2 w-[376px] bg-[#F5F7FA] px-[10px] rounded-[4px]">
<el-icon class="text-[#9BA3AD]">
<Document />
</el-icon>
<span class="text-[12px] w-[376px] text-[#606266]">{{ fileInfo.name }}</span>
</div>
<el-button class="ml-2"
link
size="small"
type="danger"
@click="removeFile">
<el-icon class="text-[#9BA3AD]">
<Delete />
</el-icon>
</el-button>
</div>
</div>
</el-form-item>
</div>
</div>
</div>
<!-- 4. 多智能体任务编排 -->
<div class="mb-10">
<CustomHeaderTitle title="多智能体任务编排" />
<el-form-item label="任务画布">
<div class="w-[776px] h-[320px] overflow-hidden bg-[#f5f7fa] rounded-md">
<!-- 这里通常使用 LogicFlow 或 X6,这里用图片或背景模拟 -->
<img alt="任务画布"
class="w-full h-full object-cover"
src="https://img02.glsx.com.cn/weapp/resource/venus-agentic/bg-agentic-train.jpg">
</div>
</el-form-item>
</div>
<!-- 5. 陪伴属性配置 -->
<div class="mb-10">
<CustomHeaderTitle title="陪伴属性配置" />
<el-form-item label="陪伴场景提示词"
prop="companionScenarioPromptDetail"
required>
<el-input v-model="formData.companionScenarioPromptDetail"
class="w-[776px]"
maxlength="5000"
placeholder="场景1:员工主动抱怨/吐槽场景..."
:rows="6"
show-word-limit
type="textarea" />
</el-form-item>
</div>
<!-- 底部按钮 -->
<div class="flex mt-10">
<!-- <el-button type="primary" @click="save" :loading="saving">保存</el-button> -->
<!-- <el-button @click="cancel">取消</el-button> -->
<div class="w-[60px] h-8 rounded-[5px] border bg-[#185EFE] border-[#8baefe] flex items-center justify-center cursor-pointer text-[#FFFFFF] hover:bg-[#79bbff] transition-colors"
@click="save">
保存
</div>
<div class="w-[60px] h-8 rounded-[5px] border border-[#E1E3E6] bg-white flex items-center justify-center cursor-pointer text-[#666666] ml-2 hover:bg-[#ecf5ff] hover:text-[#1956fe] transition-all duration-200"
@click="cancel">
取消
</div>
</div>
</el-form>
</div>
</template>
<style scoped lang="scss">
/* 覆盖 Element Plus 一些默认样式以更贴合设计图 */
:deep(.el-form-item__label) {
font-weight: normal;
color: #565C66;
}
:deep(.el-textarea__inner) {
background-color: #fcfcfc;
}
/* 将必选标记移动到 label 后面 */
:deep(.el-form-item.is-required .el-form-item__label) {
&::before {
display: none;
}
&::after {
margin-left: 4px;
color: var(--el-color-danger);
content: '*';
}
}
/* 设置 el-cascader 选中项的主题色 */
:deep(.el-cascader) {
--el-cascader-menu-selected-text-color: #1956FE;
}
:deep(.el-cascader-panel) {
--el-cascader-menu-selected-text-color: #1956FE;
}
/* 直接覆盖选中节点的样式,确保生效 */
:deep(.el-cascader-node.in-active-path),
:deep(.el-cascader-node.is-selectable.in-checked-path),
:deep(.el-cascader-node.is-active) {
color: #1956FE !important;
.el-cascader-node__label {
color: #1956FE !important;
}
}
</style>
<!-- 非 scoped 样式,用于覆盖渲染到 body 的 popper 面板 -->
<style lang="scss">
/* 覆盖自定义 popper 类中的 cascader 选中项颜色 */
.custom-cascader-popper {
--el-cascader-menu-selected-text-color: #1956FE;
.el-cascader-panel {
--el-cascader-menu-selected-text-color: #1956FE;
}
/* 直接覆盖选中节点的样式 */
.el-cascader-node.in-active-path,
.el-cascader-node.is-selectable.in-checked-path,
.el-cascader-node.is-active {
color: #1956FE !important;
.el-cascader-node__label {
color: #1956FE !important;
}
}
}
</style>