ソースを参照

Merge branch 'main' into wzg

wzg 5 ヶ月 前
コミット
b72fc9c3b0

+ 7 - 11
src/entrypoints/content.js

@@ -10,10 +10,8 @@ export default defineContentScript({
         let page = document.getElementsByTagName('body')[0];
         const src = chrome.runtime.getURL('images/begin.png')
         window.pageAnalyzer = new PageAnalyzer();
-        console.log(PageAnalyzer)
         window.onload = () => {
             chrome.runtime.sendMessage(getPageInfo())
-            console.log(getPageInfo());
         }
         let form = null
         let formChildren = []
@@ -26,8 +24,6 @@ export default defineContentScript({
             }
             let dom = null
             if (message.type === "GET_TAG_ACTION") {
-                const a = sendResponse
-                console.log(message);
                 const data = message.data
                 if (data.id) {
                     dom = document.getElementById(data.id)
@@ -39,9 +35,6 @@ export default defineContentScript({
                 }
                 console.log(dom);
                 dom[0].click()
-                await new Promise(res => setTimeout(() => {
-                    res()
-                }, 500))
                 sendResponse({ data: '完成' })
                 return true
             }
@@ -86,6 +79,7 @@ export default defineContentScript({
                 console.log(formData, excelData);
                 await handleFillInput(formData, 0)
             }
+            return true
         });
         function getPageInfo() {
             const favIconUrl = getFavicon()
@@ -217,8 +211,6 @@ export default defineContentScript({
         }
         const simulateCompleteUserAction = async (clickElement, inputElement, inputText, tdTitle) => {
             // 1. 模拟鼠标弹起事件
-            console.log(inputText, inputElement);
-
             const simulateMouseUp = (element) => {
                 const mouseUpEvent = new MouseEvent('mouseup', {
                     bubbles: true,
@@ -341,10 +333,14 @@ export default defineContentScript({
             }
         };
         function formatDate(date) {
+            // 直接创建北京时间的日期对象
             const d = new Date(date);
+
+            // 获取年、月、日
             const year = d.getFullYear();
-            const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1,并确保两位数
-            const day = String(d.getDate()).padStart(2, '0'); // 确保两位数
+            const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1
+            const day = String(d.getDate()).padStart(2, '0');
+
             return `${year}-${month}-${day}`;
         }
 

+ 261 - 226
src/entrypoints/sidepanel/Chat.vue

@@ -24,10 +24,21 @@
         </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 :checked="type === '2'" @change="type = '2'">表单填写</el-check-tag>
-    </div> -->
+    <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>
     <Tools @read-click="isShowPage = true, taklToHtml = true" />
 
     <div>
@@ -53,11 +64,12 @@
           <el-button class="op" link @click="handleCardButtonClick" :disabled="!taklToHtml">总结</el-button>
         </div>
       </div>
-
       <!-- 输入区域 -->
       <div class="input-area">
-        <el-input v-model="inputMessage" type="textarea" :rows="2" placeholder="输入消息..."
-          @keyup.enter="() => sendMessage()" />
+        <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"
@@ -77,10 +89,7 @@
 
       </div>
 
-
-
     </div>
-
   </div>
 </template>
 
@@ -89,56 +98,52 @@ 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 as sendServer,
-  formatMessage,
-  buildExcelUnderstandingPrompt
-} from '@/utils/ai-service.js'
+import { hepl, getSummaryPrompt, sendMessage, formatMessage, buildExcelUnderstandingPrompt } from '@/utils/ai-service.js'
 import * as XLSX from "xlsx";
 import { ElMessage } from 'element-plus';
 import { useMsg } from '@/entrypoints/sidepanel/hook/useMsg.ts';
 import Tools from "@/entrypoints/sidepanel/component/tools.vue";
 import { useSummary } from '@/entrypoints/sidepanel/hook/useSummary.ts'
+import { mockData } from "@/entrypoints/sidepanel/mock"
 
-// 消息列表数据
-const { messages, inputMessage } = useMsg();
-const { taklToHtml, handleCardButtonClick } = useSummary(messages.value, inputMessage.value);
+// 滚动条引用
+const scrollbar = ref(null);
+const type = ref('');
+const xlsxData = ref({});
+const isShowPage = ref(false);
+const {
+  messages,
+  inputMessage,
+  indexTemp,
+  taklToHtml,
+  pageInfo,
+  sendLoading,
+  addMessage,
+  sendRequese,
+  getPageInfo,
+  streamRes,
+  handleInput
+} = useMsg(scrollbar, type, xlsxData, fetchDataAndProcess);
+const { handleCardButtonClick } = useSummary(addMessage, sendRequese);
 
 
-const pageInfo = ref({})
-const isShowPage = ref(false);
-const sendLoading = ref(false)
+
+// const pageInfo = ref({})
 
 
 // 输入框内容
 // const inputMessage = ref('')
 
-// 滚动条引用
-const scrollbar = ref(null)
-
-
 // 计算标题是否需要滚动
 const titleScroll = computed(() => {
   return pageInfo.value?.title?.length > 20 // 当标题超过20个字符时触发滚动
 })
-let xlsxData = {}
-let formMap = []
+
+// let formMap = []
 let formInfo = []
-const handleInput = () => {
-  const arr = xlsxData
-  chrome.runtime.sendMessage({
-    type: 'FROM_SIDE_PANEL_TO_INPUT_FORM',
-    data: {
-      excelData: arr,
-      formData: formMap
-    }
-  });
-}
+const flag = ref(false)  //true调用算法接口
 
 const handleUpload = (file) => {
-  sendMessage(`已上传文件:${file.name}`)
   chrome.runtime.sendMessage({
     type: 'FROM_SIDE_PANEL_TO_GET_PAGE_FORM',
   }, async (response) => {
@@ -146,6 +151,8 @@ const handleUpload = (file) => {
 
       console.error("消息发送错误:", chrome.runtime.lastError);
     } else {
+      addMessage(`已上传文件:${file.name}`, false)
+
       formInfo = response.data
       const reader = new FileReader();
       reader.readAsArrayBuffer(file);
@@ -153,242 +160,270 @@ const handleUpload = (file) => {
         const data = new Uint8Array(e.target.result);
         const workbook = XLSX.read(data, {
           type: "array",
-          cellDates: true,
-          cellNF: false,
-          cellText: false,
+          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: true,
+          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 (!xlsxData.value[header]) xlsxData.value[header] = []
+          xlsxData.value[header].push(readData[1][i])
         })
-        await sendRequese(buildExcelUnderstandingPrompt(readData, file?.name, response), false, true, true)
+        if (type.value === '2') {
+          await streamRes(buildExcelUnderstandingPrompt(readData, file?.name, response), false)
+        }
       };
-      // await sendRequese(getSummaryPrompt(response.data.content),true)
     }
     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 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 handleCardButtonClick = async () => {
-//   sendMessage('总结当前页面')
-//   await sendRequese('', true)
+//   addMessage('总结当前页面', false)
+//   await sendRequese('', false)
 // }
 
 
+// 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 flag = ref(false)  //true调用算法接口
-const streamRes = async (msg, Summary, format = false, add, copy) => {
+const fetchRes = async (msg) => {
   sendLoading.value = true
-  console.log(messages.value);
-
   const obj = reactive({
+    id: moment(),
     username: '用户1',
     content: '',
-    rawContent: '', // 存储原始内容
     timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
     isSelf: false,
     avatar: avator,
-    add: false
+    addToHistory: !taklToHtml.value
   })
-  let history = []
-  if (taklToHtml.value) {
-    if (!add && !Summary) {
-      history.push({
-        role: 'user',
-        content: `页面主要内容${pageInfo.value.content.mainContent}`
-      })
-    }
-    history.push({
-      role: 'user',
-      content: msg
-    })
-  } else {
-    history = messages.value.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)
-    }
-    (Summary || add) && history.push({
-      role: 'user',
-      content: msg
-    })
-
-  }
-
   messages.value.push(obj)
-  nextTick(() => {
-    scrollbar.value?.setScrollTop(99999)
-  })
-  const iterator = await sendServer(history, Summary)
-
-  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 (add) {
-    try {
-      formMap = JSON.parse(obj.rawContent.split('json')[1].split('```')[0])
-    } catch (e) {
-      console.error('解析JSON失败:', e)
-    }
+  if (type.value === '2') {
+    await fetchDataAndProcess(msg, obj)
+    sendLoading.value = false
+    // await handleClick(res)
   }
 
-  // 最终格式化完整内容
-  // if (format) {
-  //     try {
-  //         const jsonContent = obj.rawContent.split('json')[1].split('```')[0]
-  //         obj.content = formatMessage(jsonContent)
-  //     } catch (e) {
-  //         console.error('格式化JSON内容失败:', e)
-  //         obj.content = formatMessage(obj.rawContent)
-  //     }
-  // }
-  console.log(messages.value);
-  sendLoading.value = false
-  obj.add = add
-  nextTick(() => {
-    scrollbar.value?.setScrollTop(99999)
-  })
-}
-const fetchRes = async (msg, Summary, format = false, add, copy) => {
-  const obj = reactive({
-    id: moment(),
-    username: '用户1',
-    content: '',
-    timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
-    isSelf: false,
-    avatar: avator,
-    add: false
-  })
-  messages.value.push(obj)
-  strArr = msg.split(',')
+  // strArr = msg.split(',')
 
-  await fetchDataAndProcess(msg)
-  obj.content = '执行操作中'
+  // await fetchDataAndProcess(msg)
+  // obj.content = '执行操作中'
 
 }
+
+
 let strArr = []
 let index = 0
-
-async function fetchDataAndProcess(input) {
+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 hepl({
+  //     input_data: input,
+  //     body:pageInfo.content.mainContent
+  // })
+  const res = await new Promise((resolve, reject) => {
+    setTimeout(() => {
+      resolve({ data: mockData[indexTemp.value] })
+    }, 1000)
   })
-  await handleClick(res.data)
-
+  await handleClick(res.data, obj);
 }
-
-let actionValue = ''
-
-async function handleClick(obj) {
-  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])
+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 {
-        ElMessage({ message: '操作执行完成', type: 'success', duration: 2 * 1000, grouping: true })
-        index = 0
+        if (res.next === '是') {
+          indexTemp.value++
+          fetchDataAndProcess(strArr[index], msgObj)
+        } else {
+          ElMessage({ message: '操作执行完成', type: 'success', duration: 2 * 1000, grouping: true })
+          index = 0
+        }
       }
-    }
-    return true
-  });
-}
-
-const sendRequese = async (msg, Summary = false, format = false, add = false, copy) => {
-  const a = await getPageInfo()
-  // if (msg.startsWith('帮我')) {
-  //     actionValue = msg
-  //     fetchRes(msg, Summary, format = false, add, copy)
-  // }
-  // else {
-  //     if (msg === '') msg = getSummaryPrompt(a.content)
-  //       streamRes(msg, Summary, format = false, add, copy)
-  // }
-  if (msg === '') msg = getSummaryPrompt(a.content)
-  streamRes(msg, Summary, format = false, add, copy)
-}
-
-// 发送消息
-const sendMessage = (msg = false) => {
-  if (!msg && !inputMessage.value.trim()) return
-  const newMessage = {
-    id: messages.value.length + 1,
-    username: '我',
-    content: msg ? msg : inputMessage.value,
-    timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
-    isSelf: true,
-    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
+      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.value = 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)
+// }
 
-  messages.value.push(newMessage)
-
-  // 滚动到底部
-  nextTick(() => {
-    scrollbar.value?.setScrollTop(99999)
-    !msg && sendRequese(inputMessage.value.trim(), false)
-    inputMessage.value = ''
-  })
-}
+// 发送消息
+// 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)
 
@@ -590,6 +625,7 @@ onMounted(async () => {
   background: #fff;
   border-radius: 10px;
   border: 1px solid rgba(0, 0, 0, 0.08);
+  font-size: 14px;
   /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
   transition: transform 0.2s, box-shadow 0.2s; */
 }
@@ -615,7 +651,6 @@ onMounted(async () => {
   flex: 1;
   overflow: hidden;
   position: relative;
-  height: 24px;
 }
 
 .title-scroller {

+ 166 - 6
src/entrypoints/sidepanel/hook/useMsg.ts

@@ -1,9 +1,14 @@
 // 消息数组
-import { ref, watch } from 'vue';
+import { ref, reactive } from 'vue';
 import avator from '@/public/icon/32.png';
 import moment from 'moment'
-export function useMsg() {
+export function useMsg(scrollbar: any, type: any, xlsxData: any, fetchDataAndProcess: Function) {
   const inputMessage = ref('');
+  const indexTemp = ref(0);
+  const taklToHtml = ref<any>(false);
+  const sendLoading = ref(false);
+  const pageInfo = ref<any>({});
+  const formMap = ref([]);
   const messages = ref([{
     username: '用户1',
     content: '你好!有什么我可以帮助你的吗?',
@@ -13,10 +18,165 @@ export function useMsg() {
     avatar: avator
   }]);
 
-  watch(inputMessage, (newVal) => {
-    console.log(newVal)
+  // 发送消息
+  const addMessage = (msg: any, fetch: any) => {
+    if (!msg) return
+    const newMessage: any = {
+      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);
+    })
+  }
 
-  return { messages, inputMessage }
+  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 sendRequese = async (msg: any, addHtml = false) => {
+    const res: any = await getPageInfo()
+    if (type.value === '2' && msg.startsWith('/')) {
+      indexTemp.value = 0
+      fetchRes(msg)
+    }
+    else {
+      if (!addHtml) msg = getSummaryPrompt(res.content)
+      streamRes(msg, addHtml)
+    }
+  }
+
+  const fetchRes = async (msg: any) => {
+    sendLoading.value = true
+    const obj: any = 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
+    }
+  }
+
+
+  const streamRes = async (msg: any, addHtml: any) => {
+    sendLoading.value = true;
+    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 = []
+    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: any) => item.addToHistory).slice(-20)
+        .map((item: any) => ({
+          role: item.isSelf ? 'user' : 'system',
+          content: item.isSelf ? item.content : item.rawContent
+        }))
+    }
+
+    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.value = JSON.parse(obj.rawContent.split('json')[1].split('```')[0])
+
+        handleInput()
+      } catch (e) {
+        console.error('解析JSON失败:', e)
+      }
+    }
+    sendLoading.value = false
+    nextTick(() => {
+      scrollbar.value?.setScrollTop(99999)
+    })
+  }
+
+  const handleInput = () => {
+    const arr = xlsxData.value;
+    chrome.runtime.sendMessage({
+      type: 'FROM_SIDE_PANEL_TO_INPUT_FORM',
+      data: {
+        excelData: arr,
+        formData: formMap.value
+      }
+    });
+  }
+
+  return {
+    messages,
+    inputMessage,
+    indexTemp,
+    taklToHtml,
+    pageInfo,
+    sendLoading,
+    formMap,
+    addMessage,
+    sendRequese,
+    getPageInfo,
+    streamRes,
+    handleInput
+  }
 }

+ 4 - 146
src/entrypoints/sidepanel/hook/useSummary.ts

@@ -1,152 +1,10 @@
-import { ref, watch, toRefs } from "vue";
-import moment from 'moment';
-
-export function useSummary(messages: any, inputMessage: any) {
-
-
-  // 滚动条引用
-  const scrollbar = ref<any>(null);
-  const taklToHtml = ref<any>(false);
-  const pageInfo = ref({});
-  const inputMessageRef = toRefs(inputMessage);
-
-  watch(inputMessageRef, (newVal) => {
-    console.log(newVal)
-  })
-
-
-
-  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 sendMessage = (msg: Boolean | string = false) => {
-    if (!msg && !inputMessage.value.trim()) return
-    const newMessage = {
-      id: messages.value.length + 1,
-      username: '我',
-      content: msg ? msg : inputMessage.value,
-      timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
-      isSelf: true,
-      avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
-    }
-
-    messages.value.push(newMessage)
-
-    // 滚动到底部
-    nextTick(() => {
-      scrollbar.value?.setScrollTop(99999)
-      !msg && sendRequese(inputMessage.value.trim(), false)
-      inputMessage.value = ''
-    })
-  }
-
-  const sendRequese = async (msg, Summary = false, format = false, add = false, copy) => {
-    const a = await getPageInfo()
-    if (msg === '') msg = getSummaryPrompt(a.content)
-    streamRes(msg, Summary, format = false, add, copy)
-  }
-
-  const streamRes = async (msg, Summary, format = false, add, copy) => {
-    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,
-      add: false
-    })
-    let history = []
-    if (taklToHtml.value) {
-      if (!add && !Summary) {
-        history.push({
-          role: 'user',
-          content: `页面主要内容${pageInfo.value.content.mainContent}`
-        })
-      }
-      history.push({
-        role: 'user',
-        content: msg
-      })
-    } else {
-      history = messages.value.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)
-      }
-      (Summary || add) && history.push({
-        role: 'user',
-        content: msg
-      })
-
-    }
-
-    messages.value.push(obj)
-    nextTick(() => {
-      scrollbar.value?.setScrollTop(99999)
-    })
-    const iterator = await sendServer(history, Summary)
-
-    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 (add) {
-      try {
-        formMap = JSON.parse(obj.rawContent.split('json')[1].split('```')[0])
-      } catch (e) {
-        console.error('解析JSON失败:', e)
-      }
-    }
-    console.log(messages.value);
-    sendLoading.value = false
-    obj.add = add
-    nextTick(() => {
-      scrollbar.value?.setScrollTop(99999)
-    })
-  }
-
-  async function handleCardButtonClick() {
-    sendMessage('总结当前页面')
-    // await sendRequese('', true)
+export function useSummary(addMessage: Function, sendRequese: Function) {
+  const handleCardButtonClick = async () => {
+    addMessage('总结当前页面', false)
+    await sendRequese('', false)
   }
 
   return {
-    taklToHtml,
     handleCardButtonClick
   }
 }

+ 26 - 20
src/entrypoints/sidepanel/mock.ts

@@ -1,22 +1,28 @@
 export const options = [
-    {
-        value: 'DeepSeek-R1',
-        label: 'DeepSeek-R1',
-    },
-    {
-        value: 'DeepSeek-V3',
-        label: 'DeepSeek-V3',
-    },
-    {
-        value: 'GPT-4o mini',
-        label: 'GPT-4o mini',
-    },
-    {
-        value: 'Claude 3.5',
-        label: 'Claude 3.5',
-    },
-    {
-        value: 'DeepSeek-R1 14B',
-        label: 'DeepSeek-R1 14B',
-    },
+  {
+    value: 'DeepSeek-R1',
+    label: 'DeepSeek-R1',
+  },
+  {
+    value: 'DeepSeek-V3',
+    label: 'DeepSeek-V3',
+  },
+  {
+    value: 'GPT-4o mini',
+    label: 'GPT-4o mini',
+  },
+  {
+    value: 'Claude 3.5',
+    label: 'Claude 3.5',
+  },
+  {
+    value: 'DeepSeek-R1 14B',
+    label: 'DeepSeek-R1 14B',
+  },
+];
+
+export 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: "是" },
 ]

+ 1 - 1
src/utils/ai-service.js

@@ -22,7 +22,7 @@ export async function hepl(data) {
 
     }
 }
-export async function sendMessage(message, Summary, html,) {
+export async function sendMessage(message) {
     try {
         // 创建新的 AbortController
         const controller = new AbortController();