123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727 |
- <!-- Chat.vue -->
- <template>
- <div class="chat-container">
- <!-- 消息列表 -->
- <el-scrollbar class="message-list" ref="scrollbar">
- <div class="messages">
- <div
- v-for="(message, index) in messages"
- :key="index"
- :class="['message-item', message.isSelf ? 'self' : 'other']"
- >
- <el-avatar :size="32" :src="message.avatar" />
- <div class="message-content">
- <div
- class="content"
- v-if="!message.isSelf"
- :class="{'loading-content': message.content === ''}"
- >
- <div v-html="message.content"></div>
- <div class="loading-indicator" v-if="sendLoading && index === messages.length - 1">
- <span class="dot"></span>
- <span class="dot"></span>
- <span class="dot"></span>
- </div>
- </div>
- <div v-else class="content">{{message.content}}</div>
- <div class="timestamp ">{{ message.timestamp }}
- <!-- <span v-if="message.add" style="cursor: pointer;" @click="handleInput">填充</span> -->
- </div>
- </div>
- </div>
- </div>
- </el-scrollbar>
- <div style="display: flex;gap: 4px;padding: 1rem;">
- <!-- <el-check-tag :checked="type === '1'" @change="type = '1'">文档总结</el-check-tag> -->
- <el-check-tag :disabled="!taklToHtml" :checked="type === '2'" @change="() => {
- if (type !== '2') {
- inputMessage = '/智能填表 '
- type = '2'
- } else {
- type = ''
- }
- }">
- <el-tooltip content="选择后,在输入框描述填表流程" placement="top">
- 智能填表
- </el-tooltip>
- </el-check-tag>
- </div>
- <div class="card-content">
- <img :src="pageInfo?.favIconUrl" style="width: 32px;"/>
- <div class="title-wrapper">
- <div class="title-scroller" :class="{ 'scroll': isHoveringTitle && titleScroll }">
- {{ pageInfo?.title }}
- </div>
- </div>
- <el-button :disabled="!taklToHtml" type="primary" size="small" @click="handleCardButtonClick">
- 总结
- </el-button>
- </div>
- <!-- 输入区域 -->
- <div class="input-area">
- <el-input
- v-model="inputMessage"
- type="textarea"
- :rows="2"
- placeholder="输入消息..."
- @keyup.enter="() => {
- addMessage(inputMessage.trim(),true)
- inputMessage = ''
- }"
- />
- <div >
- <div style="width: 100px;display: flex;justify-content: space-between;">
- <el-upload
- :before-upload="file => handleUpload(file)"
- :multiple="false"
- :class="['upload', {'can-hover': taklToHtml}]"
- name="file"
- :show-file-list="false"
- :accept="'.xlsx'"
- :disabled="!taklToHtml"
- >
- <el-icon size="24" :color="taklToHtml ? 'gray' : '#c0c4cc'" style="cursor: pointer;"><Upload /></el-icon>
- </el-upload>
-
- <el-button size="small" type="primary" @click="() => {
- addMessage(inputMessage.trim(),true)
- inputMessage = ''
- }" :disabled="!inputMessage.trim() || sendLoading">
- 发送
- </el-button>
- </div>
- <el-tooltip content="开启后,将会根据左侧网页中的内容做出回答" placement="top">
- <el-switch size="small" v-model="taklToHtml" @change="(_) => {
- !_ && (type = '')
- }"/>
- </el-tooltip>
- 与页面对话
- </div>
- </div>
- </div>
- </template>
- <script setup>
- import { ref, onMounted, nextTick ,inject} from 'vue'
- import { ElScrollbar, ElAvatar, ElInput, ElButton } from 'element-plus'
- import avator from '@/public/icon/32.png'
- import moment from 'moment'
- import {hepl,getSummaryPrompt,sendMessage ,formatMessage,buildExcelUnderstandingPrompt} from '@/utils/ai-service.js'
- import * as XLSX from "xlsx";
- import { ElMessage } from 'element-plus';
- const pageInfo = ref({})
- const sendLoading = ref(false)
- // 消息列表数据
- const messages = ref([
- {
- username: '用户1',
- content: '你好!有什么我可以帮助你的吗?',
- rawContent: '你好!有什么我可以帮助你的吗?',
- timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
- isSelf: false,
- avatar: avator,
- addToHistory: false
- }
- ])
- // 输入框内容
- const inputMessage = ref('')
- // 滚动条引用
- const scrollbar = ref(null)
- // 计算标题是否需要滚动
- const titleScroll = computed(() => {
- return pageInfo.value?.title?.length > 20 // 当标题超过20个字符时触发滚动
- })
- let xlsxData = {}
- let formMap = []
- let formInfo = []
- const handleInput = () => {
- console.log(formMap,1005);
-
- const arr = xlsxData
- chrome.runtime.sendMessage({
- type: 'FROM_SIDE_PANEL_TO_INPUT_FORM',
- data: {
- excelData: arr,
- formData:formMap
- }
- });
- }
- const taklToHtml = ref(false)
- const handleUpload = (file) => {
- chrome.runtime.sendMessage({
- type: 'FROM_SIDE_PANEL_TO_GET_PAGE_FORM',
- },async (response) => {
- if (chrome.runtime.lastError) {
-
- console.error("消息发送错误:", chrome.runtime.lastError);
- } else {
- addMessage(`已上传文件:${file.name}`,false)
-
- formInfo = response.data
- const reader = new FileReader();
- reader.readAsArrayBuffer(file);
- reader.onload = async (e) => {
- const data = new Uint8Array(e.target.result);
- const workbook = XLSX.read(data, {
- type: "array",
- cellDates: false,
- cellNF: true,
- cellText: true,
- dateNF: 'yyyy-mm-dd'
- });
-
- // 修复日期处理
- const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
-
- // 转换为JSON数据
- const readData = XLSX.utils.sheet_to_json(firstSheet, {
- header: 1,
- raw: false,
- defval: "",
- dateNF: 'yyyy-mm-dd'
- });
- console.log(readData,58);
-
- readData[0].forEach((header, i) => {
- if (!xlsxData[header]) xlsxData[header] = []
- xlsxData[header].push(readData[1][i])
- })
- if (type.value === '2') {
- await streamRes(buildExcelUnderstandingPrompt(readData,file?.name,response),false)
- }
- };
- }
- return true
- });
-
- }
- const getPageInfo = () => {
- return new Promise((res, rej) => {
- chrome.runtime.sendMessage({
- type: 'FROM_SIDE_PANEL_TO_GET_PAGE_INFO',
- },async (response) => {
- if (chrome.runtime.lastError) {
- console.error("消息发送错误:", chrome.runtime.lastError);
- rej(chrome.runtime.lastError)
- } else {
- pageInfo.value = response.data
- res(response.data)
- }
- });
- })
-
- }
- const type = ref('')
- const handleCardButtonClick = async () => {
- addMessage('总结当前页面',false)
- await sendRequese('',false)
- }
- const flag = ref(false) //true调用算法接口
- const streamRes = async (msg, addHtml,) => {
- sendLoading.value = true
- console.log(messages.value);
-
- const obj = reactive({
- username: '用户1',
- content: '',
- rawContent: '', // 存储原始内容
- timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
- isSelf: false,
- avatar: avator,
- addToHistory: !taklToHtml.value
- })
- let history = []
- console.log(messages.value);
-
- if (taklToHtml.value) {
- if (addHtml) {
- history.push({
- role: 'user',
- content: `页面主要内容${pageInfo.value.content.mainContent}`
- })
- }
- history.push({
- role: 'user',
- content: msg
- })
- } else {
- history = messages.value.filter(item => item.addToHistory).slice(-20).map(item => ({
- role: item.isSelf ? 'user' : 'system',
- content: item.isSelf ? item.content : item.rawContent
- }))
- // const index = history.findIndex(item => item.content === '总结当前页面')
- // if (index !== -1) {
- // history.splice(index, 2)
- // }
- // const index2 = history.findIndex(item => item.has === true)
- // if (index2 !== -1) {
- // history.splice(index2, 1)
- // }
- }
-
- messages.value.push(obj)
- nextTick(() => {
- scrollbar.value?.setScrollTop(99999)
- })
- const iterator = await sendMessage(history, addHtml)
-
- for await (const chunk of iterator) {
- if (chunk) {
- const decodedChunk = chunk.choices[0].delta.content;
- if (decodedChunk) {
- // 保存原始内容
- obj.rawContent += decodedChunk
- // 实时格式化显示内容
- obj.content = formatMessage(obj.rawContent)
- }
- }
- scrollbar.value?.setScrollTop(99999)
- }
- scrollbar.value?.setScrollTop(99999)
-
- // 处理最终内容
- if (type.value === '2') {
- try {
- formMap = JSON.parse(obj.rawContent.split('json')[1].split('```')[0])
- console.log(formMap,100);
-
- handleInput()
- } catch (e) {
- console.error('解析JSON失败:', e)
- }
- }
- console.log(messages.value);
- sendLoading.value = false
- nextTick(() => {
- scrollbar.value?.setScrollTop(99999)
- })
- }
- const mockData = [
- {action:'click', class: "ant-menu-item", tag: "li", innerHTML: "<span class=\"ant-menu-item-icon\"><span role=\"img\" aria-label=\"book\" class=\"anticon anticon-book\"></span></span><span class=\"ant-menu-title-content\"><span>项目建档</span></span>", id: "", text: "项目建档", next: "是" },
- {action:'click',class: "ant-menu-item", tag: "button", innerHTML: "<span class=\"ant-menu-item-icon\"><span role=\"img\" aria-label=\"book\" class=\"anticon anticon-book\"></span></span><span class=\"ant-menu-title-content\"><span>项目建档</span></span>", id: "", text: "新增", next: "是"},
- {action:'show',class: "ant-menu-item", tag: "button", innerHTML: "<span class=\"ant-menu-item-icon\"><span role=\"img\" aria-label=\"book\" class=\"anticon anticon-book\"></span></span><span class=\"ant-menu-title-content\"><span>项目建档</span></span>", id: "", text: "请上传数据", next: "是"},
- ]
- let indexTemp = 0
- const fetchRes = async (msg) => {
- sendLoading.value = true
- const obj =reactive({
- id: moment(),
- username: '用户1',
- content: '',
- timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
- isSelf: false,
- avatar: avator,
- addToHistory:!taklToHtml.value
- })
- messages.value.push(obj)
- if (type.value === '2') {
- await fetchDataAndProcess(msg,obj)
- sendLoading.value = false
- // await handleClick(res)
- }
-
- // strArr = msg.split(',')
- // await fetchDataAndProcess(msg)
- // obj.content = '执行操作中'
-
- }
- let strArr = []
- let index = 0
- async function fetchDataAndProcess(input,obj) {
- console.log(input);
-
- const pageInfo = await getPageInfo()
- console.log(pageInfo);
-
- // 发起请求获取数据
- // const res = await hepl({
- // input_data: input,
- // body:pageInfo.content.mainContent
- // })
- const res = await new Promise((resolve, reject) => {
- setTimeout(() => {
- resolve({data:mockData[indexTemp]})
- }, 1000)
- })
- await handleClick(res.data,obj)
-
- }
- async function handleClick(res, msgObj) {
- await new Promise(resolve => setTimeout(resolve, 1000))
- if (res.action === 'click') {
- msgObj.content = `点击${res.tag}元素`
- chrome.runtime.sendMessage({
- type: 'FROM_SIDE_PANEL_TO_ACTION',
- data: res
- }, async (response) => {
- if (chrome.runtime.lastError) {
- console.error("消息发送错误:", chrome.runtime.lastError);
- rej(chrome.runtime.lastError)
- } else {
- if (res.next === '是') {
- indexTemp++
- fetchDataAndProcess(strArr[index],msgObj)
- } else {
- ElMessage({ message: '操作执行完成', type: 'success', duration: 2 * 1000, grouping: true })
- index = 0
- }
- }
- return true
- });
- }
- if (res.action === 'show') {
- msgObj.content = `请上传数据`
- ElMessage({ message: '请上传数据', type: 'success', duration: 4 * 1000, grouping: true })
- }
- // chrome.runtime.sendMessage({
- // type: 'FROM_SIDE_PANEL_TO_ACTION',
- // data:obj
- // }, async (response) => {
- // if (chrome.runtime.lastError) {
- // console.error("消息发送错误:", chrome.runtime.lastError);
- // rej(chrome.runtime.lastError)
- // } else {
- // if (obj.next === '是') {
- // console.log(strArr[index]);
-
- // index++
- // fetchDataAndProcess(strArr[index])
- // } else {
- // ElMessage({ message: '操作执行完成', type: 'success', duration: 2 * 1000, grouping: true })
- // index = 0
- // }
- // }
- // return true
- // });
- }
- const sendRequese = async (msg, addHtml = false) => {
- const a = await getPageInfo()
- if (type.value === '2' && msg.startsWith('/')) {
- indexTemp = 0
- fetchRes(msg, addHtml)
- }
- else {
- if (!addHtml) msg = getSummaryPrompt(a.content)
- streamRes(msg, addHtml)
- }
- // if (msg === '') msg = getSummaryPrompt(a.content)
- // streamRes(msg, Summary, format = false, add, copy)
- }
- // 发送消息
- const addMessage = (msg,fetch) => {
- if (!msg) return
- const newMessage = {
- id: messages.value.length + 1,
- username: '我',
- content: msg,
- timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
- isSelf: true,
- avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
- addToHistory: !taklToHtml.value
- }
- messages.value.push(newMessage)
- // 滚动到底部
- nextTick(() => {
- scrollbar.value?.setScrollTop(99999)
- fetch && sendRequese(msg, taklToHtml.value)
- })
- }
- const isHoveringTitle = ref(false)
- // 组件挂载时滚动到底部
- onMounted(async () => {
- chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
- if (message.type === 'TO_SIDE_PANEL_PAGE_INFO') {
- pageInfo.value = message.data
- console.log(pageInfo.value);
-
- // 转发到 content.js
- chrome.tabs.sendMessage(sender.tab.id, {
- type: 'TO_CONTENT_SCRIPT',
- data: message.data
- });
- }
- if (message.type === 'TO_SIDE_PANEL_PAGE_CHANGE') {
- pageInfo.value = message.data
- }
- });
- await getPageInfo()
- nextTick(() => {
- scrollbar.value?.setScrollTop(99999)
- })
- // 添加标题悬停事件监听
- nextTick(() => {
- const titleWrapper = document.querySelector('.title-wrapper')
- if (titleWrapper) {
- titleWrapper.addEventListener('mouseenter', () => {
- isHoveringTitle.value = true
- })
- titleWrapper.addEventListener('mouseleave', () => {
- isHoveringTitle.value = false
- })
- }
-
- scrollbar.value?.setScrollTop(99999)
- })
- })
- </script>
- <style scoped>
- .chat-container {
- height: 100vh;
- display: flex;
- flex-direction: column;
- border: 1px solid #dcdfe6;
- border-radius: 4px;
- background-color: #fff;
- font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
- }
- .message-list {
- flex: 1;
- padding: 16px;
- overflow: auto;
- }
- .messages {
- min-height: 100%;
- display: flex;
- flex-direction: column;
- }
- .message-item {
- display: flex;
- margin-bottom: 20px;
- gap: 12px;
- color: #333;
- align-items: flex-start;
- animation: fadeIn 0.3s ease-in-out;
- }
- @keyframes fadeIn {
- from { opacity: 0; transform: translateY(10px); }
- to { opacity: 1; transform: translateY(0); }
- }
- .message-item.self {
- flex-direction: row-reverse;
- }
- .message-content {
- max-width: 80%;
- }
- .username {
- font-size: 14px;
- color: #606266;
- margin-bottom: 4px;
- }
- .content {
- padding: 12px;
- min-height: 40px;
- background-color: #F0F4F8;
- border-radius: 12px;
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
- word-break: break-all;
- line-height: 1.5;
- font-size: 14px;
- }
- .content :deep(pre) {
- margin: 10px 0;
- border-radius: 8px;
- }
- .content :deep(code) {
- font-family: 'Menlo', 'Monaco', 'Courier New', monospace;
- }
- .content :deep(p) {
- margin: 8px 0;
- }
- .content :deep(ul), .content :deep(ol) {
- padding-left: 20px;
- margin: 8px 0;
- }
- .content :deep(blockquote) {
- border-left: 4px solid #ddd;
- padding-left: 10px;
- color: #666;
- margin: 8px 0;
- }
- .self .content {
- background: #409eff;
- color: white;
- border-bottom-right-radius: 4px;
- }
- .other .content {
- border-bottom-left-radius: 4px;
- }
- .timestamp {
- display: flex;
- justify-content: space-between;
- font-size: 12px;
- color: #909399;
- margin-top: 6px;
- }
- .timestamp span {
- transition: color 0.2s;
- }
- .timestamp span:hover {
- color: #409eff;
- }
- .input-area {
- padding: 16px;
- color: #7F838A;
- border-top: 1px solid #eaeaea;
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: 12px;
- background-color: #f9f9f9;
- }
- .input-area :deep(.el-textarea__inner) {
- border-radius: 8px;
- transition: border-color 0.3s;
- resize: none;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
- }
- .input-area :deep(.el-textarea__inner:focus) {
- border-color: #409eff;
- box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
- }
- .info-card {
- margin: 10px;
- }
- .card-content {
- display: flex;
- align-items: center;
- gap: 12px;
- padding: 14px 16px;
- margin: 0 16px 12px;
- background: #fff;
- border-radius: 10px;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
- transition: transform 0.2s, box-shadow 0.2s;
- }
- .card-content:hover {
- transform: translateY(-2px);
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
- }
- .card-icon {
- color: #409eff;
- }
- .title-wrapper {
- flex: 1;
- overflow: hidden;
- position: relative;
- height: 24px;
- }
- .title-scroller {
- display: inline-block;
- white-space: nowrap;
- color: #333;
- font-weight: 500;
- }
- .title-scroller.scroll {
- animation: scrollTitle 10s linear infinite;
- }
- @keyframes scrollTitle {
- 0% {
- transform: translateX(0);
- }
- 100% {
- transform: translateX(-100%);
- }
- }
- .upload :deep(.el-icon) {
- transition: color 0.3s;
- }
- .can-hover :deep(.el-icon:hover) {
- color: #409eff !important;
- }
- .el-check-tag {
- margin-right: 8px;
- transition: all 0.3s;
- }
- .el-check-tag:hover {
- transform: scale(1.05);
- }
- /* 加载中的消息样式 */
- .loading-content {
- min-height: 40px;
- display: flex;
- align-items: center;
- justify-content: flex-start;
- }
- .loading-indicator {
- display: flex;
- align-items: center;
- gap: 4px;
- }
- .dot {
- width: 8px;
- height: 8px;
- background-color: #409eff;
- border-radius: 50%;
- display: inline-block;
- animation: pulse 1.5s infinite ease-in-out;
- }
- .dot:nth-child(2) {
- animation-delay: 0.3s;
- }
- .dot:nth-child(3) {
- animation-delay: 0.6s;
- }
- @keyframes pulse {
- 0%, 100% {
- transform: scale(0.8);
- opacity: 0.6;
- }
- 50% {
- transform: scale(1.2);
- opacity: 1;
- }
- }
- </style>
|