You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
dianshang-qianduan/src/views/analysis-of-students/dialogue.vue

433 lines
12 KiB
Vue

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<!--
* @Author: qinzhenpen qzp1807@126.com
* @Date: 2025-03-27 15:35:52
* @LastEditors: qinzhenpen qzp1807@126.com
* @LastEditTime: 2025-05-16 17:04:10
* @FilePath: \corporate-finance\src\components\AI\dialogue.vue
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
<div class="dialogue" v-loading="loading" element-loading-text="Loading..." element-loading-background="rgba(122, 122, 122, 0.8)">
<div class="tz-centent" ref="container">
<el-scrollbar :height="scrollbarHeight" ref="scrollArea">
<ul class="QAlist">
<li :class="[item.role == 'user' ? 'questionItem' : 'answerItem']" v-for="item in messages" :key="item" :data-name="item.name">
<div :class="[item.role == 'user' ? 'qustionCon' : 'answerCon']">
<div v-if="item.role !== 'user'" class="answerCon-img">
<img src="@/assets/images/ai.webp" alt="" />
</div>
<MdPreview :editorId="id" :modelValue="item.content" :codeFoldable="false" theme="dark" codeTheme="a11y" />
<div class="copy">
<el-tooltip class="box-item" effect="dark" content="复制" placement="top">
<svg-icon icon-class="copy" v-copyText="item.content" v-copyText:callback="copyTextSuccess" />
</el-tooltip>
</div>
</div>
</li>
<li v-if="isRequestPending">
<div style="display: flex; align-items: center">
<img src="@/assets/images/ai.webp" alt="" />
<div style="height: 68px" v-loading="isRequestPending" :element-loading-svg="svg"></div>
</div>
</li>
</ul>
</el-scrollbar>
</div>
<div class="tz-footer-ipt" ref="footer">
<el-input type="textarea" placeholder="可以问我任何问题" v-model.trim="inputMessage" @keyup.enter="sendMessage" :autosize="{ minRows: 4.5, maxRows: 3 }" />
<svg-icon icon-class="发送" class="fr" v-if="isTypingComplete" @click="sendMessage" :class="{ disdabled: !inputMessage }" />
<svg-icon icon-class="中断" class="fr" @click="gInterrupt" v-else />
<svg-icon icon-class="导出" class="fr" style="margin-right: 10px" @click="exportData" v-show="messages.length > 0" />
</div>
</div>
</template>
<script setup>
import { MdPreview, MdCatalog } from "md-editor-v3";
import { getAssetsFile } from "@/utils/index.js";
import * as AI from "@/api/AI.js";
import "md-editor-v3/lib/style.css";
import * as XLSX from "xlsx";
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
let resizeObserver = null; // ResizeObserver 实例
const isRequestPending = ref(false);
const loading = ref(false);
const footer = ref(null);
let abortController = null;
const isTypingComplete = ref(true);
const scrollArea = ref(null);
const scrollbarHeight = ref(null);
const inputMessage = ref("");
const messages = ref([]);
// 发送消息
const sendMessage = async () => {
if (!inputMessage.value.trim() || isRequestPending.value) return proxy.$message.warning("请输入内容");
isRequestPending.value = true;
isTypingComplete.value = true; // 重置为初始状态
// 重置状态
// 添加用户消息
messages.value.push({
id: Date.now(),
role: "user",
content: inputMessage.value,
});
// 用户提问后立即滚动到底部
nextTick(() => {
scrollToBottom();
inputMessage.value = "";
});
abortController = new AbortController();
const signal = abortController.signal;
// 调用后端API
let params = {
systemOwner: "电商互联网产品",
userId: userStore.userInfo.userId,
type: "2",
};
isTypingComplete.value = false;
// 将参数对象转换为查询字符串
const queryString = new URLSearchParams(params);
const resp = await fetch(`${import.meta.env.VITE_APP_AI_API}api/kimi4?${queryString}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: inputMessage.value.trim(),
signal,
});
// 添加AI消息占位
let newMessage = reactive({ id: Date.now(), role: "assistant", content: "" });
messages.value.push(newMessage); // 滚动到底部
console.log(messages.value, " messages.value");
// 处理流式响应
const reader = resp.body.getReader();
const decoder = new TextDecoder("utf-8");
while (true) {
const { done, value } = await reader.read();
isRequestPending.value = false;
if (done) break;
const text = decoder.decode(value, { stream: true });
await typeText(newMessage, text);
//滚动到最新消息
nextTick(() => {
const scrollEl = scrollArea.value.wrapRef;
scrollEl.scrollTop = scrollEl.scrollHeight;
});
}
};
const typeText = (message, text) => {
return new Promise((resolve) => {
isTypingComplete.value = false; // 重置状态
let index = 0;
message.content = ""; // 清空原内容
const textLength = text.length;
const chunkSize = textLength > 100 ? 3 : 1; // 根据文本长度动态调整批量字数
const typingSpeed = textLength > 100 ? 30 : 60; // 适配长短文本
const interval = setInterval(() => {
if (index < text.length) {
message.content += text.slice(index, index + chunkSize);
index += chunkSize;
if (index % 10 === 0) nextTick(() => scrollToBottom()); // 限制滚动更新频率
} else {
clearInterval(interval);
isTypingComplete.value = true;
nextTick(() => scrollToBottom());
resolve();
}
}, typingSpeed);
});
};
// 滚动到底部的函数
const scrollToBottom = () => {
const scrollEl = scrollArea.value.wrapRef;
if (scrollEl) {
scrollEl.scrollTop = scrollEl.scrollHeight;
}
};
const copyTextSuccess = () => {
proxy.$modal.msgSuccess("复制成功");
};
// 中断对话
const gInterrupt = () => {
if (abortController) {
abortController.abort();
abortController = null;
isRequestPending.value = false;
isTypingComplete.value = true;
}
};
// 获取分析
const getAnalysis = async () => {
loading.value = true;
try {
const res = await AI.getLearningAnalysis({ stuNeed: proxy.$cache.session.getJSON("msg"), stuData: proxy.$cache.session.getJSON("learningAnalysisData") });
messages.value.push({
id: Date.now(),
role: "assistant",
content: res,
});
} catch (error) {
proxy.$message.error("AI学情分析暂时不可用,请稍后重试");
} finally {
loading.value = false;
}
};
// 计算高度的函数
const updateHeight = () => {
const windowHeight = window.innerHeight; // 视口高度
const footerHeight = footer.value?.offsetHeight || 0; // 底部高度
const totalOffset = footerHeight;
scrollbarHeight.value = `${windowHeight - totalOffset - 120}px`;
};
// 导出方法
const exportData = () => {
const data = messages.value.map((item) => {
return {
role: item.role,
content: item.content,
};
});
// 手动定义表头
const headers = [
{ A: "user", B: "content" }, // 显示的表头
];
const data1 = data.map((item) => ({
A: item.role, // 将 name 映射到 A 列
B: item.content, // 将 age 映射到 B 列
}));
// 合并表头和数据
const worksheet = XLSX.utils.json_to_sheet([...headers, ...data1], { skipHeader: true });
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, "人员信息");
// 导出 Excel
XLSX.writeFile(workbook, "export.xlsx");
};
onMounted(() => {
if (proxy.$cache.session.getJSON("msg") && proxy.$cache.session.getJSON("learningAnalysisData")) {
getAnalysis();
} else {
if (proxy.$cache.session.getJSON("teachingPlan")) {
inputMessage.value = proxy.$cache.session.getJSON("teachingPlan");
sendMessage();
// 删除我提问的这条
messages.value.splice(0, 1);
}
}
updateHeight();
// 监听窗口大小变化
window.addEventListener("resize", updateHeight);
// 使用 ResizeObserver 监听头部和底部的尺寸变化
resizeObserver = new ResizeObserver(() => {
updateHeight(); // 元素尺寸变化时重新计算
});
if (footer.value) resizeObserver.observe(footer.value);
});
// 清理监听
onUnmounted(() => {
window.removeEventListener("resize", updateHeight);
if (resizeObserver) {
resizeObserver.disconnect();
}
});
</script>
<style lang='scss' scoped>
.dialogue {
padding: 20px 40px;
height: calc(100vh - 2.5rem);
position: relative;
background: url("@/assets/images/背景.webp") no-repeat;
background-size: 100% 100%;
.tz-centent {
width: calc(100vw - 50rem);
height: calc(100vh - 18rem);
margin: 0 auto;
.QAlist {
padding-left: 0px;
li {
display: flex !important;
overflow: hidden;
margin-bottom: 12px;
:deep(.el-loading-mask) {
background: transparent !important;
}
}
.task-introduction {
color: #ffffff;
.title {
font-size: 1.2rem;
}
// p除了第一个
p:not(:first-child) {
margin-top: 1rem;
font-size: 0.8rem !important;
}
ul {
margin: 0;
padding: 0;
width: 30rem;
li {
margin-top: 10px;
background: #011031;
border: 1px solid #003e7c;
border-radius: 12px 12px 12px 0;
padding: 10px 12px 10px 12px;
font-size: 14px;
color: #ffffff;
// 鼠标小手
cursor: pointer;
line-height: 22px;
&:hover {
background: #002c5b;
}
}
}
}
.md-editor-preview-wrapper {
padding: 0px 0px !important;
.md-editor-preview {
font-size: 15px !important;
}
}
.questionItem {
// display: flex;
justify-content: flex-end;
.qustionCon {
background: #ffffff;
border-radius: 12px 12px 0 12px;
// padding: 0px 12px 0px 16px;
font-weight: 400;
font-size: 14px;
line-height: 20px;
max-width: calc(100% - 51px);
word-break: break-all;
}
}
.answerItem {
display: flex;
margin-bottom: 12px;
overflow: hidden;
:deep(.answerCon) {
display: flex;
font-weight: 400;
font-size: 14px;
// color: rgb(68, 68, 68);
line-height: 22px;
// width: calc(100% - 51px);
word-break: break-all;
flex: 1 1 0%;
padding: 0px 16px 0px 16px;
}
}
margin-top: 10px;
}
}
.tz-footer-ipt {
position: absolute;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
width: calc(100vw - 50rem);
height: 11rem;
background: #001d40;
margin: 0 auto;
border-radius: 35px;
padding: 10px;
border: 1px solid #003e7c;
.svg-icon {
width: 3rem;
height: 2.7rem;
// 鼠标小手
cursor: pointer;
}
.disdabled {
// 禁用
cursor: not-allowed;
.svg-icon {
fill: #d6dee8;
}
}
:deep(.el-textarea) {
.el-textarea__inner {
background: transparent !important;
box-shadow: none !important;
// 光标颜色
border-radius: 0px;
color: #ffffff;
&::placeholder {
color: #ffffff;
}
}
}
}
}
.qustionCon {
.md-editor {
--md-color: #333333 !important;
--md-bk-color: transparent !important;
}
}
.answerCon {
display: flex;
gap: 1rem;
position: relative;
padding-right: 10px;
.copy {
position: absolute;
top: 5px;
right: 23px;
display: none;
.svg-icon {
fill: #ffffff;
width: 1.5rem;
height: 1.5rem;
}
}
&:hover {
.copy {
display: block;
cursor: pointer;
}
}
.md-editor {
background: #011031;
border-radius: 10px;
border: 1px solid #003e7c;
--md-color: #ffffff !important;
--md-bk-color: #02132f !important;
}
}
.el-loading-mask {
background: transparent !important;
.el-loading-spinner {
text-align: left;
padding-left: 2.5rem;
}
}
.qustionCon {
position: relative;
padding-left: 10px;
.copy {
position: absolute;
top: 5px;
left: 8px;
display: none;
.svg-icon {
fill: #333333;
width: 1.5rem;
height: 1.5rem;
}
}
&:hover {
.copy {
display: block;
cursor: pointer;
}
}
}
.el-scrollbar {
--el-scrollbar-bg-color: transparent !important;
}
</style>