This commit is contained in:
14651
2025-08-14 15:43:24 +08:00
parent 253825ab0c
commit e66713b51f
19 changed files with 1685 additions and 26 deletions

View File

@@ -0,0 +1,770 @@
<template>
<div class="chat-container">
<!-- 状态栏占位 -->
<div class="status-bar-placeholder"></div>
<!-- 自定义导航栏 -->
<div class="custom-nav-bar">
<div class="nav-left" @click="toggleHistoryDrawer">
<img src="@/assets/ai_icon/history.svg" class="nav-icon">
</div>
<div class="nav-title">智水AI辅导员</div>
</div>
<!-- 消息列表 -->
<div ref="messageList" class="message-list" @scroll="onScroll">
<!-- 加载提示 -->
<div v-if="isLoadingHistory" class="loading-history">
<span>正在加载历史记录...</span>
</div>
<!-- 没有更多历史记录提示 -->
<div v-if="!hasMoreHistory && messages.length > 0" class="no-more-history">
<span>没有更多历史记录了</span>
</div>
<!-- 消息列表 -->
<div v-for="(item, index) in messages" :key="item.messageId || index"
:class="['message-item', item.sender === 'user' ? 'user-message' : 'ai-message']">
<img class="avatar" :src="item.avatar">
<div class="message-content">
<!-- 文字内容 -->
<div v-if="item.content && item.sender === 'ai'" class="markdown-content"
v-html="renderMarkdown(item.content)"></div>
<span v-else-if="item.content">{{ item.content }}</span>
<!-- 图片内容 -->
<img v-if="item.image" :src="item.image" class="sent-image">
<!-- AI 特有内容 -->
<div v-if="item.sender === 'ai'" class="ai-hint">
<!-- 引用来源部分 -->
<div v-if="item.retrieverResources && item.retrieverResources.length" class="reference-section">
<span class="reference-title">引用来源</span>
<div v-for="(ref, idx) in item.retrieverResources" :key="idx" class="reference-item-wrapper">
<span class="doc-name-link" @click="toggleSingleReference(index, idx)">
{{ ref.document_name }}
</span>
<div v-if="showSingleReference[index] && showSingleReference[index][idx]"
class="reference-details-item">
<span class="reference-meta">{{ ref.name }}{{ ref.document_name }}</span>
<span class="reference-content" v-if="ref.content">{{ ref.content }}</span>
</div>
</div>
</div>
<!-- AI操作区域点赞/点踩 -->
<div class="ai-actions">
<span class="ai-text">回答由AI生成</span>
<div class="icon-group">
<img src="@/assets/ai_icon/good.svg" class="btn-icon" @click="handleThumbUpClick(item.messageId)" />
<img src="@/assets/ai_icon/tread.svg" class="btn-icon" @click="handleThumbDownClick(item.messageId)" />
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 输入框和发送按钮 -->
<div class="input-container">
<history-drawer v-if="showHistoryDrawer" :visible="showHistoryDrawer" @close="toggleHistoryDrawer"
@item-click="onHistoryItemClick" />
<input v-model="inputMessage" placeholder="输入消息..." @keyup.enter="sendMessage" />
<img src="@/assets/ai_icon/add.svg" class="add-icon" @click="selectImage" />
<img src="@/assets/ai_icon/send.svg" class="send-icon" @click="sendMessage" />
</div>
</div>
</template>
<script>
import HistoryDrawer from '@/components/aiChat/HistoryDrawer.vue'
import { createChatStream } from '@/utils/ai_stream.js'
import { sendFeedback, getHistory } from '@/api/aiChat/ai_index.js'
// 简单的文本渲染函数,替代 markdown-it
function simpleTextRender(text) {
if (!text) return ''
// 简单的换行处理
return text.replace(/\n/g, '<br>')
}
export default {
components: {
HistoryDrawer
},
data() {
return {
showHistoryDrawer: false,
inputMessage: '',
messages: [],
conversation_id: localStorage.getItem('conversation_id') || null,
showSingleReference: {},
currentCancel: null,
sending: false,
user: localStorage.getItem('stuNo') || '',
userId: localStorage.getItem('stuId') || '',
userName: localStorage.getItem('stuName') || '',
isLoadingHistory: false,
hasMoreHistory: true,
earliestMessageId: null,
lastScrollTime: 0,
scrollDebounce: 100,
lastUserScrollTime: 0
}
},
methods: {
// 页面导航
goHome() {
this.$router.push('/')
},
// 切换历史记录抽屉
toggleHistoryDrawer() {
this.showHistoryDrawer = !this.showHistoryDrawer
},
// 渲染Markdown内容
renderMarkdown(text) {
return simpleTextRender(text || '')
},
// 显示提示信息
showToast(title, type = 'info') {
console.log(`[${type}] ${title}`)
},
// 强制滚动到底部
forceScrollToBottom(offset = 50) {
this.$nextTick(() => {
if (this.$refs.messageList) {
const targetScrollTop = this.$refs.messageList.scrollHeight - this.$refs.messageList.clientHeight - offset
this.$refs.messageList.scrollTo({
top: targetScrollTop,
behavior: 'smooth'
})
}
})
},
// 初始化聊天
async initChat() {
if (!this.user) {
this.initConversation()
return
}
this.isLoadingHistory = false
this.hasMoreHistory = true
this.earliestMessageId = null
this.messages = []
try {
const res = await getHistory({
user: this.user,
conversationId: this.conversation_id || '',
limit: 20
})
if (res.code === 200 && res.data && Array.isArray(res.data.data)) {
const newMessages = []
res.data.data.forEach(msg => {
if (msg.query) {
newMessages.push({
sender: 'user',
avatar: require('@/assets/ai_icon/yonghu.png'),
content: msg.query,
image: '',
messageId: msg.id,
conversationId: msg.conversation_id
})
}
if (msg.answer) {
newMessages.push({
sender: 'ai',
avatar: require('../../../assets/ai_icon/AI.png'),
content: msg.answer,
retrieverResources: msg.retriever_resources || [],
image: '',
messageId: 'ai-' + msg.id,
conversationId: msg.conversation_id
})
}
})
newMessages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at))
this.messages = newMessages
if (newMessages.length > 0) {
this.conversation_id = newMessages[0].conversationId
localStorage.setItem('conversation_id', this.conversation_id)
this.earliestMessageId = newMessages[0].messageId
}
this.hasMoreHistory = res.data.has_more || false
this.forceScrollToBottom()
} else {
this.messages = this.getWelcomeMessage()
this.hasMoreHistory = false
}
} catch (e) {
console.error('初始化聊天失败:', e)
this.showToast('加载历史记录失败')
this.initConversation()
}
},
// 发送消息
async sendMessage() {
const msg = this.inputMessage.trim()
if (!msg || this.sending) return
this.sending = true
// 添加用户消息
this.messages.push({
sender: 'user',
avatar: require('@/assets/big/fdy-avatar.png'),
content: msg,
image: '',
messageId: Date.now().toString()
})
this.inputMessage = ''
this.saveMessagesToLocal()
// 添加AI消息占位
const aiIdx = this.messages.push({
sender: 'ai',
avatar: require('@/assets/imagesPage1/ai.png'),
content: '<span class="loading-text">正在思考...</span>',
retrieverResources: [],
image: '',
messageId: 'pending-' + Date.now().toString()
}) - 1
this.$set(this.showSingleReference, aiIdx, {})
this.scrollToBottom()
try {
const { stream, cancel } = createChatStream({
conversationId: this.conversation_id,
prompt: msg,
user: this.user,
userId: this.userId,
userName: this.userName
})
this.currentCancel = cancel
// 处理流式响应
for await (const data of stream) {
if (data.event === 'message' && data.answer) {
const currentContent = this.messages[aiIdx].content
const newContent = (currentContent.includes('loading-text') ? '' : currentContent) + data.answer
this.messages[aiIdx].content = newContent
this.scrollToBottom(true)
this.saveMessagesToLocal()
}
if (data.event === 'message_end') {
if (data.conversation_id) {
this.conversation_id = data.conversation_id
localStorage.setItem('conversation_id', this.conversation_id)
}
if (data.metadata?.retriever_resources) {
this.messages[aiIdx].retrieverResources = data.metadata.retriever_resources
}
if (data.message_id) {
this.messages[aiIdx].messageId = data.message_id
}
}
}
} catch (e) {
console.error('流式请求失败:', e)
this.messages[aiIdx].content = 'AI回复失败: ' + (e.message || '网络错误')
} finally {
this.sending = false
this.currentCancel = null
if (this.messages[aiIdx].messageId.startsWith('pending-')) {
this.messages[aiIdx].messageId = 'ai-' + Date.now().toString()
}
this.saveMessagesToLocal()
}
},
// 初始化对话
initConversation() {
this.messages = this.getWelcomeMessage()
this.conversation_id = null
localStorage.removeItem('conversation_id')
},
// 获取欢迎消息
getWelcomeMessage() {
return [
{
sender: 'ai',
avatar: require('@/assets/imagesPage1/ai.png'),
content: '你好我是智水AI辅导员有什么可以帮助你的吗',
retrieverResources: [],
image: '',
messageId: 'welcome-message'
}
]
},
// 保存消息到本地
saveMessagesToLocal() {
try {
const messagesToSave = this.messages.filter(msg => !msg.messageId.startsWith('pending-'))
localStorage.setItem('chat_messages', JSON.stringify(messagesToSave))
} catch (e) {
console.warn('保存消息到本地失败:', e)
}
},
// 滚动到底部
scrollToBottom(smooth = false) {
this.$nextTick(() => {
if (this.$refs.messageList) {
const behavior = smooth ? 'smooth' : 'auto'
this.$refs.messageList.scrollTo({
top: this.$refs.messageList.scrollHeight,
behavior
})
}
})
},
// 选择图片
selectImage() {
console.log('选择图片功能待实现')
},
// 历史记录项点击
onHistoryItemClick(item) {
console.log('历史记录项点击:', item)
},
// 点赞
async handleThumbUpClick(messageId) {
try {
await sendFeedback({
messageId,
feedback: 'like'
})
this.showToast('感谢您的反馈!')
} catch (e) {
console.error('点赞失败:', e)
}
},
// 点踩
async handleThumbDownClick(messageId) {
try {
await sendFeedback({
messageId,
feedback: 'dislike'
})
this.showToast('感谢您的反馈!')
} catch (e) {
console.error('点踩失败:', e)
}
},
// 切换单个引用显示
toggleSingleReference(messageIndex, refIndex) {
if (!this.showSingleReference[messageIndex]) {
this.$set(this.showSingleReference, messageIndex, {})
}
this.$set(this.showSingleReference[messageIndex], refIndex,
!this.showSingleReference[messageIndex][refIndex])
},
// 滚动事件处理
onScroll() {
const now = Date.now()
if (now - this.lastScrollTime < this.scrollDebounce) {
return
}
this.lastScrollTime = now
this.lastUserScrollTime = now
// 检查是否需要加载更多历史记录
if (this.$refs.messageList &&
this.$refs.messageList.scrollTop === 0 &&
this.hasMoreHistory &&
!this.isLoadingHistory) {
console.log('加载更多历史记录')
}
}
},
mounted() {
if (!this.user) {
this.showToast('请先登录', 'error')
setTimeout(() => this.$router.push('/login'), 1500)
return
}
this.initChat().then(() => {
const scrollWithRetry = (attempt = 0) => {
this.$nextTick(() => {
setTimeout(() => {
this.forceScrollToBottom()
setTimeout(() => {
this.forceScrollToBottom(30)
if (attempt < 2) {
setTimeout(() => {
if (this.$refs.messageList &&
Math.abs(this.$refs.messageList.scrollHeight -
this.$refs.messageList.clientHeight -
this.$refs.messageList.scrollTop) > 50) {
scrollWithRetry(attempt + 1)
}
}, attempt === 0 ? 500 : 800)
}
}, 200)
}, 100)
})
}
scrollWithRetry()
})
}
}
</script>
<!-- /* ChatPopup.vue 的 <style> 部分 */ -->
<style scoped>
/* ============= 整体容器 ============= */
.chat-container {
display: flex;
flex-direction: column;
min-height: 100vh;
width: 100%;
overflow: hidden;
position: relative;
background-color: #f5f5f5;
padding-top: 10px;
box-sizing: border-box;
}
/* ============= 状态栏占位 ============= */
.status-bar-placeholder {
height: var(--status-bar-height, 20px);
background-color: #fff;
}
/* ============= 自定义导航栏 ============= */
.custom-nav-bar {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
height: 44px;
padding: 0 16px;
background-color: #fff;
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
position: fixed;
top: 0;
left: 0;
z-index: 999;
border-bottom: 1px solid #eee;
}
.nav-title {
font-size: 17px;
font-weight: 600;
color: #333;
text-align: center;
flex: 1;
margin-right: 45px;
}
.nav-icon {
width: 24px;
height: 24px;
}
.nav-left,
.nav-right {
width: 44px;
height: 44px;
display: flex;
align-items: center;
justify-content: center;
}
/* ============= 消息列表 ============= */
.message-list {
flex: 1;
padding: 60px 0 80px;
/* 调整顶部和底部间距 */
background-color: #f5f5f5;
overflow-y: auto;
scroll-behavior: smooth;
}
/* ============= 消息项 ============= */
.message-item {
display: flex;
align-items: flex-start;
margin-bottom: 16px;
max-width: 100%;
padding: 0 16px;
}
.user-message {
flex-direction: row-reverse;
}
.ai-message {
flex-direction: row;
}
.avatar {
width: 40px;
height: 40px;
border-radius: 8px;
margin: 0 8px;
flex-shrink: 0;
}
.message-content {
max-width: 70%;
padding: 10px 12px;
border-radius: 10px;
word-break: break-word;
line-height: 1.5;
font-size: 15px;
}
.user-message .message-content {
background-color: #e1f5fe;
}
.ai-message .message-content {
background-color: #fff;
border: 1px solid #eee;
}
.sent-image {
max-width: 200px;
max-height: 200px;
border-radius: 8px;
margin-top: 4px;
}
/* ============= AI提示区域 ============= */
.ai-hint {
margin-top: 8px;
font-size: 12px;
color: #666;
}
.ai-actions {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 8px;
}
.ai-text {
color: #999;
}
.icon-group {
display: flex;
gap: 12px;
}
.btn-icon {
width: 16px;
height: 16px;
cursor: pointer;
}
/* ============= 输入框区域 ============= */
.input-container {
display: flex;
align-items: center;
padding: 8px 16px;
background-color: #fff;
border-top: 1px solid #eee;
position: fixed;
bottom: 0;
left: 0;
right: 0;
z-index: 10;
}
.input-container input {
flex: 1;
height: 40px;
padding: 0 16px;
background-color: #f5f5f5;
border-radius: 20px;
font-size: 14px;
margin: 0 10px;
border: none;
outline: none;
}
.add-icon,
.send-icon {
width: 24px;
height: 24px;
cursor: pointer;
}
/* ============= 引用相关样式 ============= */
.reference-section {
margin-top: 8px;
border-top: 1px dashed #ddd;
padding-top: 8px;
}
.reference-title {
display: block;
font-weight: bold;
margin-bottom: 4px;
}
.doc-name-link {
color: #007aff;
text-decoration: underline;
margin-right: 8px;
font-size: 13px;
cursor: pointer;
}
.reference-item-wrapper {
margin-top: 8px;
}
.reference-details-item {
margin-top: 8px;
padding: 10px;
background-color: #f9f9f9;
border-radius: 4px;
border: 1px solid #e0e0e0;
font-size: 13px;
color: #555;
}
.reference-meta {
font-weight: 500;
color: #333;
margin-bottom: 4px;
}
/* ============= Markdown内容样式 ============= */
.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3) {
margin: 1em 0 0.5em;
}
.markdown-content :deep(p) {
margin: 0.5em 0;
}
.markdown-content :deep(code) {
background-color: #f3f4f6;
padding: 0.2em 0.4em;
border-radius: 3px;
font-family: monospace;
}
.markdown-content :deep(pre) {
background-color: #f6f8fa;
border-radius: 5px;
padding: 10px;
overflow-x: auto;
}
.markdown-content :deep(blockquote) {
border-left: 4px solid #d0d7de;
color: #57606a;
padding-left: 1em;
margin: 1em 0;
}
/* ============= AI悬浮按钮 ============= */
.ai-hover {
position: fixed;
right: 20px;
bottom: 80px;
z-index: 1000;
width: 50px;
height: 50px;
border-radius: 50%;
background-color: #409eff;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
cursor: pointer;
transition: transform 0.2s;
}
.ai-hover:active {
transform: scale(0.95);
}
.ai-hover-content {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.ai-hover-text {
font-size: 18px;
font-weight: bold;
}
/* ============= 加载状态 ============= */
.loading-history {
text-align: center;
padding: 10px;
color: #999;
font-size: 14px;
}
.no-more-history {
text-align: center;
padding: 10px;
color: #ccc;
font-size: 12px;
}
/* ============= 响应式调整 ============= */
@media (max-width: 600px) {
.message-content {
max-width: 80%;
font-size: 14px;
}
.nav-title {
font-size: 15px;
}
.btn-icon {
width: 14px;
height: 14px;
}
.ai-hover {
right: 15px;
bottom: 70px;
width: 45px;
height: 45px;
}
}
</style>

View File

@@ -1,3 +1,4 @@
<!--E:\桌面\AI辅导员\学工系统\zhxg_pc\src\layout\index.vue-->
<template>
<div :class="classObj" class="app-wrapper" :style="{ '--current-color': theme }">
<el-scrollbar>
@@ -16,11 +17,16 @@
</el-scrollbar>
<!-- ai悬停 -->
<div class="ai-hover" @click="showAI()">
<div class="ai-hover-content">
<i class="el-icon-question" style="font-size: 30px;"></i>
<div>
<!-- 其他页面内容 -->
<!-- 触发按钮控制弹窗显示隐藏 -->
<div class="ai-hover" @click="showAI = !showAI">
<i class="el-icon-question" style="font-size: 24px;"></i>
</div>
<!-- 聊天弹窗通过 v-if 控制显隐 -->
<ChatPopup v-if="showAI" />
</div>
</div>
</template>
@@ -30,13 +36,15 @@ import { AppMain, Navbar, Settings, Sidebar, TagsView } from './components'
import ResizeMixin from './mixin/ResizeHandler'
import { mapState } from 'vuex'
import variables from '@/assets/styles/variables.scss'
import ChatPopup from '../layout/components/Aichat/ChatPopup.vue'
import {
initCoze
} from "@/utils/ai.js";
} from '@/utils/ai.js'
import {
getAccessToken
} from "@/api/aiJWT/aiJWT.js"
} from '@/api/aiJWT/aiJWT.js'
export default {
name: 'Layout',
components: {
@@ -45,9 +53,15 @@ export default {
RightPanel,
Settings,
Sidebar,
TagsView
TagsView,
ChatPopup // 注册ChatPopup组件
},
mixins: [ResizeMixin],
data() {
return {
showAI: false // 控制AI弹窗显示/隐藏的变量
}
},
computed: {
...mapState({
theme: state => state.settings.theme,
@@ -70,42 +84,54 @@ export default {
}
},
variables() {
return variables;
return variables
}
},
methods: {
handleClickOutside() {
this.$store.dispatch('app/closeSideBar', { withoutAnimation: false })
},
async showAI() {
let userInfo = {
roleGroup: this.userInfo.roles[0].roleName || "student",
nickName: this.userInfo.nickName,
username: this.userInfo.userName,
avater: this.avatar,
user_token: this.token
}
console.log("请求AI的信息", userInfo)
//1.获取token
userInfo.accessToken = (await this.getAccessToken()).access_token;
userInfo.onRefreshToken = async () => (await this.getAccessToken()).accessToken;
const sdk = await initCoze(userInfo);
sdk.showChatBot();
// 切换AI弹窗显示状态
toggleAI() {
this.showAI = !this.showAI
// 如果需要在显示时执行原有逻辑,可以取消下面的注释
// if (this.showAI) {
// this.initializeAI()
// }
},
// 原有AI初始化逻辑保持注释状态
async initializeAI() {
// let userInfo = {
// roleGroup: this.userInfo.roles[0].roleName || "student",
// nickName: this.userInfo.nickName,
// username: this.userInfo.userName,
// avater: this.avatar,
// user_token: this.token
// }
// console.log("请求AI的信息", userInfo)
//
// //1.获取token
// userInfo.accessToken = (await this.getAccessToken()).access_token;
// userInfo.onRefreshToken = async () => (await this.getAccessToken()).accessToken;
// const sdk = await initCoze(userInfo);
// sdk.showChatBot();
},
async getAccessToken() {
const res = await getAccessToken(); // 调用请求函数
const data = JSON.parse(res.data); // 解析数据
return data; // ✅ 返回 data
const res = await getAccessToken() // 调用请求函数
const data = JSON.parse(res.data) // 解析数据
return data // ✅ 返回 data
}
}
}
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/mixin.scss";
@import "~@/assets/styles/variables.scss";
//~@/assets/styles/variables.scss
.app-wrapper {
@include clearfix;
position: relative;
@@ -178,4 +204,22 @@ export default {
align-items: center;
cursor: pointer;
}
//AI
.ai-hover {
position: fixed;
right: 20px;
bottom: 20px;
/* 和弹窗拉开距离 */
width: 40px;
height: 40px;
background-color: #409eff;
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
color: #fff;
cursor: pointer;
z-index: 9999;
}
</style>