houzhongjian
9 天以前 2c5e4638f84676fa1e3949a62212d2a4a97e784a
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
<!--  AI 对话  -->
<template>
  <el-aside width="280px" class="conversation-container h-100%">
    <!-- 左顶部:对话 -->
    <div class="h-80%">
      <div class="conversation-title">
        <img
          src="@/assets/ai/zhuanlu/conversation_big.png"
          class="mr-3px w-[1.2em] h-[1.2em]"
          alt="icon"
        />
        对话列表
      </div>
<!--      <hr class="line"/>-->
      <el-button class="w-1/1 btn-new-conversation" type="primary" @click="createNewConversation">
        <img
          src="@/assets/ai/zhuanlu/conversation_big.png"
          class="mr-8px w-[1.5em] h-[1.5em]"
          alt="icon"
        />
        开始新对话
      </el-button>
 
      <!-- 左顶部:搜索对话 -->
      <el-input
        v-model="searchName"
        size="large"
        class="mt-10px search-input"
        placeholder="搜索历史记录"
        @keyup="searchConversation"
      >
        <template #prefix>
          <Icon icon="ep:search" />
        </template>
      </el-input>
 
      <!-- 左中间:对话列表 -->
      <div class="conversation-list">
        <!-- 情况一:加载中 -->
        <el-empty v-if="loading" description="." :v-loading="loading" />
        <!-- 情况二:按照 group 分组,展示聊天会话 list 列表 -->
        <div v-for="conversationKey in Object.keys(conversationMap)" :key="conversationKey">
          <div
            class="conversation-item classify-title"
            v-if="conversationMap[conversationKey].length"
          >
            <el-text class="mx-1" size="small" tag="b">{{ conversationKey }}</el-text>
          </div>
          <div
            class="conversation-item"
            v-for="conversation in conversationMap[conversationKey]"
            :key="conversation.id"
            @click="handleConversationClick(conversation.id)"
            @mouseover="hoverConversationId = conversation.id"
            @mouseout="hoverConversationId = ''"
          >
            <div
              :class="
                conversation.id === activeConversationId ? 'conversation active' : 'conversation'
              "
            >
              <div class="title-wrapper">
                <img class="avatar" :src="conversation.roleAvatar || roleAvatarDefaultImg" />
                <span class="title">{{ conversation.title }}</span>
              </div>
              <div class="button-wrapper" v-show="hoverConversationId === conversation.id">
                <el-button class="btn" link @click.stop="handleTop(conversation)">
                  <el-icon title="置顶" v-if="!conversation.pinned"><Top /></el-icon>
                  <el-icon title="置顶" v-if="conversation.pinned"><Bottom /></el-icon>
                </el-button>
                <el-button class="btn" link @click.stop="updateConversationTitle(conversation)">
                  <el-icon title="编辑">
                    <Icon icon="ep:edit" />
                  </el-icon>
                </el-button>
                <el-button class="btn" link @click.stop="deleteChatConversation(conversation)">
                  <el-icon title="删除对话">
                    <Icon icon="ep:delete" />
                  </el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
 
    <!-- 左底部:工具栏 -->
    <div class="tool-box">
      <div @click="handleClearConversation">
        <Icon icon="ep:delete" />
        <el-text size="small">清空未置顶对话</el-text>
      </div>
    </div>
 
  </el-aside>
</template>
 
<script setup lang="ts">
import { ChatConversationApi, ChatConversationVO } from '@/api/ai/chat/conversation'
import { Bottom, Top } from '@element-plus/icons-vue'
import roleAvatarDefaultImg from '@/assets/ai/zhuanlu/assistant.png'
import {ChatMessageVO} from "@/api/ai/chat/message";
import {formatToDate, formatToDateTime} from "@/utils/dateUtil";
 
const message = useMessage() // 消息弹窗
 
// 定义属性
const searchName = ref<string>('') // 对话搜索
const activeConversationId = ref<number | null>(null) // 选中的对话,默认为 null
const hoverConversationId = ref<number | null>(null) // 悬浮上去的对话
const conversationList = ref([] as ChatConversationVO[]) // 对话列表
const conversationMap = ref<any>({}) // 对话分组 (置顶、今天、三天前、一星期前、一个月前)
const loading = ref<boolean>(false) // 加载中
const loadingTime = ref<any>() // 加载中定时器
 
// 定义组件 props
const props = defineProps({
  activeId: {
    type: String || null,
    required: true
  },
  modelName: {
    type: String || null,
    required: true
  },
  quickAccess: {
    type: Boolean || null,
    required: true
  },
  defaultMessage: {
    type: Object as PropType<ChatMessageVO>
  }
})
 
// 定义钩子
const emits = defineEmits([
  'onConversationCreate',
  'onConversationClick',
  'onConversationClear',
  'onConversationDelete'
])
 
/** 搜索对话 */
const searchConversation = async (e) => {
  // 恢复数据
  if (!searchName.value.trim().length) {
    conversationMap.value = await getConversationGroupByCreateTime(conversationList.value)
  } else {
    // 过滤
    const filterValues = conversationList.value.filter((item) => {
      return item.title.includes(searchName.value.trim())
    })
    conversationMap.value = await getConversationGroupByCreateTime(filterValues)
  }
}
 
/** 点击对话 */
const handleConversationClick = async (id: number) => {
  // 过滤出选中的对话
  const filterConversation = conversationList.value.filter((item) => {
    return item.id === id
  })
  // 回调 onConversationClick
  // noinspection JSVoidFunctionReturnValueUsed
  const success = emits('onConversationClick', filterConversation[0])
  // 切换对话
  if (success) {
    activeConversationId.value = id
  }
}
 
/** 获取对话列表 */
const getChatConversationList = async () => {
  try {
    // 加载中
    loadingTime.value = setTimeout(() => {
      loading.value = true
    }, 50)
 
    // 1.1 获取 对话数据
    conversationList.value = await ChatConversationApi.getChatConversationEnergyList(props.modelName)
    // 1.2 排序
    conversationList.value.sort((a, b) => {
      return b.createTime - a.createTime
    })
    // 1.3 没有任何对话情况
    if (conversationList.value.length === 0) {
      activeConversationId.value = null
      conversationMap.value = {}
      return
    }
 
    // 2. 对话根据时间分组(置顶、今天、昨天、三天前、七天前、30 天前)
    conversationMap.value = await getConversationGroupByCreateTime(conversationList.value)
  } finally {
    // 清理定时器
    if (loadingTime.value) {
      clearTimeout(loadingTime.value)
    }
    // 加载完成
    loading.value = false
  }
}
 
/** 按照 creteTime 创建时间,进行分组 */
const getConversationGroupByCreateTime = async (list: ChatConversationVO[]) => {
  // 排序、指定、时间分组(今天、一天前、三天前、七天前、30天前)
  // noinspection NonAsciiCharacters
  const groupMap = {
    置顶: [],
    今天: [],
    昨天: [],
    三天前: [],
    七天前: [],
    三十天前: []
  }
  // 当前时间的时间戳
  const now = Date.now()
  // 定义时间间隔常量(单位:毫秒)
  const oneDay = 24 * 60 * 60 * 1000
  const sevenDays = 7 * oneDay
  const thirtyDays = 30 * oneDay
  //今天
  const today = formatToDate(new Date())
  const yesterday = formatToDate(new Date().setDate(new Date().getDate() - 1))
  for (const conversation of list) {
    // 置顶
    if (conversation.pinned) {
      groupMap['置顶'].push(conversation)
      continue
    }
    // 计算时间差(单位:毫秒)
    const diff = now - conversation.createTime
    let conversationDate = formatToDate(conversation.createTime)
    let titleDate = conversation.title.split(' ')[0]
    // 根据时间间隔判断
    if (titleDate == today) {
      groupMap['今天'].push(conversation)
    } else if (titleDate == yesterday) {
      groupMap['昨天'].push(conversation)
    } else if (diff < sevenDays) {
      groupMap['三天前'].push(conversation)
    } else if (diff < thirtyDays) {
      groupMap['七天前'].push(conversation)
    } else {
      groupMap['三十天前'].push(conversation)
    }
  }
  return groupMap
}
 
/** 新建对话 */
const createNewConversation = async () => {
  await createConversation(null)
}
 
/** 新建对话 */
const createConversation = async (title: String) => {
  // 1. 新建对话
  const conversationId = await ChatConversationApi.createChatConversationEnergy(
    {modelName: props.modelName, title: title} as unknown as ChatConversationVO
  )
  // 2. 获取对话内容
  await getChatConversationList()
  // 3. 选中对话
  await handleConversationClick(conversationId)
  // // 4. 回调
  // emits('onConversationCreate')
}
 
/** 修改对话的标题 */
const updateConversationTitle = async (conversation: ChatConversationVO) => {
  // 1. 二次确认
  const { value } = await ElMessageBox.prompt('修改标题', {
    inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空,且非空格
    inputErrorMessage: '标题不能为空',
    inputValue: conversation.title
  })
  // 2. 发起修改
  await ChatConversationApi.updateChatConversationMy({
    id: conversation.id,
    title: value
  } as ChatConversationVO)
  message.success('重命名成功')
  // 3. 刷新列表
  await getChatConversationList()
  // 4. 过滤当前切换的
  const filterConversationList = conversationList.value.filter((item) => {
    return item.id === conversation.id
  })
  if (filterConversationList.length > 0) {
    // tip:避免切换对话
    if (activeConversationId.value === filterConversationList[0].id) {
      emits('onConversationClick', filterConversationList[0])
    }
  }
}
 
/** 删除聊天对话 */
const deleteChatConversation = async (conversation: ChatConversationVO) => {
  try {
    // 删除的二次确认
    await message.delConfirm(`是否确认删除对话 - ${conversation.title}?`)
    // 发起删除
    await ChatConversationApi.deleteChatConversationMy(conversation.id)
    message.success('对话已删除')
    // 刷新列表
    await getChatConversationList()
    // 回调
    emits('onConversationDelete', conversation)
  } catch {}
}
 
/** 清空对话 */
const handleClearConversation = async () => {
  try {
    await message.confirm('确认后对话会全部清空,置顶的对话除外。')
    await ChatConversationApi.deleteChatConversationMyByUnpinned()
    ElMessage({
      message: '操作成功!',
      type: 'success'
    })
    // 清空 对话 和 对话内容
    activeConversationId.value = null
    // 获取 对话列表
    await getChatConversationList()
    // 回调 方法
    emits('onConversationClear')
  } catch {}
}
 
/** 对话置顶 */
const handleTop = async (conversation: ChatConversationVO) => {
  // 更新对话置顶
  conversation.pinned = !conversation.pinned
  await ChatConversationApi.updateChatConversationMy(conversation)
  // 刷新对话
  await getChatConversationList()
}
 
// ============ 角色仓库 ============
 
/** 角色仓库抽屉 */
const roleRepositoryOpen = ref<boolean>(false) // 角色仓库是否打开
const handleRoleRepository = async () => {
  roleRepositoryOpen.value = !roleRepositoryOpen.value
}
 
/** 监听选中的对话 */
const { activeId } = toRefs(props)
watch(activeId, async (newValue, oldValue) => {
  activeConversationId.value = newValue as string
})
 
// 定义 public 方法
defineExpose({ createConversation })
 
/** 初始化 */
onMounted(async () => {
  // 获取 对话列表
  await getChatConversationList()
  if(!props.quickAccess) {
    // 默认选中
    if (props.activeId) {
      activeConversationId.value = props.activeId
    } else {
      // 首次默认选中第一个
      if (conversationList.value.length) {
        activeConversationId.value = conversationList.value[0].id
        // 回调 onConversationClick
        await emits('onConversationClick', conversationList.value[0])
      }
    }
  } else if(props.defaultMessage) {
    let tempTitle = formatToDateTime(new Date(props.defaultMessage.createTime))
    if (conversationList.value.length) {
      conversationList.value.forEach((item) => {
        if(item.title === tempTitle) {
          activeConversationId.value = item.id
          // 回调 onConversationClick
          emits('onConversationClick', item)
        }
      })
    }
  }
})
</script>
 
<style scoped lang="scss">
.conversation-container {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 10px 10px 0;
  overflow: hidden;
 
  .conversation-title {
    color: #73C4FF;
    line-height: 25px;
    margin-bottom: 8px;
    border-bottom: 1px solid rgba(69,133,255,0.2);
    img {
      padding: 6px 0 0 5px;
    }
  }
  .line {
    margin: 5px 0;
  }
 
  .btn-new-conversation {
    border-radius: 4px;
    border: 1px solid rgba(69,133,255,0.6);
    background: rgba(69,133,255,0.4);
    color: #73C4FF;
  }
 
  .search-input {
    height: 30px;
    border-radius: 4px;
    border: 1px solid rgba(69,133,255,0.6);
    background: rgba(69,133,255,0.4);
  }
 
  .conversation-list {
    overflow-y: auto;
    height: 100%;
    margin-top: 10px;
    /* Firefox */
    scrollbar-width: thin;
    scrollbar-color: rgba(0, 0, 0, 0.15) transparent;
 
    /* WebKit */
    &::-webkit-scrollbar {
      width: 6px;
      background: transparent;
    }
    &::-webkit-scrollbar-thumb {
      border-radius: 4px;
      background: rgba(0, 0, 0, 0.15);
      transition: background 0.3s;
      &:hover { background: rgba(0, 0, 0, 0.25); }
    }
    .classify-title {
      padding-top: 10px;
      b {
        color: white;
      }
    }
    .conversation-item {
      margin-top: 5px;
    }
 
    .conversation {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      flex: 1;
      padding: 0 5px;
      cursor: pointer;
      border-radius: 5px;
      align-items: center;
      line-height: 30px;
      background-color: rgba(69,133,255,0.1);
      &.active {
        background-color: rgba(69,133,255,0.5);
        .button {
          display: inline-block;
        }
        .title-wrapper {
          > span {
            font-weight: bold;
            color: rgba(115, 196, 255);
          }
        }
      }
 
      .title-wrapper {
        display: flex;
        flex-direction: row;
        align-items: center;
        > span {
          color: rgba(115, 196, 255, 0.5);
        }
      }
 
      .title {
        padding: 2px 5px;
        max-width: 220px;
        font-size: 13px;
        color: rgba(0, 0, 0, 0.77);
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
 
      .avatar {
        width: 25px;
        height: 25px;
        border-radius: 5px;
        display: flex;
        flex-direction: row;
        justify-items: center;
      }
 
      // 对话编辑、删除
      .button-wrapper {
        right: 2px;
        display: flex;
        flex-direction: row;
        justify-items: center;
        color: #606266;
 
        .btn {
          margin: 0;
          color: #73C4FF;
        }
      }
    }
  }
 
  // 清空未设置对话
  .tool-box {
    display: flex;
    padding: 0 20px;
    width: 90%;
    margin-left: 5%;
    background-color: rgba(69,133,255,0.2);
    box-shadow: 0 0 1px 1px rgba(69,133,255,0.4);
    line-height: 35px;
    justify-content: space-between;
    align-items: center;
    color: var(--el-text-color);
    border-radius: 2px;
    div {
      display: flex;
      margin-left: 20%;
      align-items: center;
      color: #73C4FF;
      padding: 0;
      cursor: pointer;
      > span {
        color: #73C4FF;
        margin-left: 5px;
      }
    }
  }
}
 
/* 移除所有输入框边框 */
:deep(.el-form-item .el-input__wrapper) {
  border: none !important;
  box-shadow: none !important;
  background: rgba(255,255,255,0.1) !important; /* 保留浅色背景 */
}
 
/* 移除输入框边框 */
:deep(.el-input .el-input__wrapper) {
  border: 1px solid #1E5A86 !important;
  box-shadow: none !important;
}
 
:deep(.el-input__inner) {
  color: #73C4FF;
}
:deep(.el-input__wrapper) {
  background: rgba(0,194,255,0.08) !important;
}
</style>