<!-- 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>
