<!-- 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 === '' }">
              <span v-html="message.content"></span>
              <span class="loading-indicator" v-if="sendLoading && index === messages.length - 1">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
              </span>
            </div>
            <div v-else class="content">{{ message.content }}
              <span class="loading-indicator" v-if="sendLoading && index === messages.length - 1">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
              </span>
            </div>
            <div class="timestamp ">{{ message.timestamp }}
              <span v-if="message.add" style="cursor: pointer;" @click="handleInput">填充</span>
            </div>
          </div>
        </div>
      </div>
    </el-scrollbar>

    <Tools @read-click="readClick"
           @upload-file="handleUpload"
           @handle-capture="handleCapture"
           @his-records="hisRecords"
           @add-new-dialogue="addNewDialogue" />

    <div>

      <!-- 输入区域 -->
      <div class="input-area">
        <div v-show="isShowPage" style="border-bottom: 1px solid #F0F0F0;">
          <div class="card_list">
            <div v-for="(v,i) in pageInfoList" :key="i"
                 :class="`card-content ${pageInfoList.length > 1 ? 'card_width' : ''}`">
              <img :src="v?.favIconUrl" style="width: 24px;display: block" />
              <div class="title-wrapper">
                <span class="els title-scroller">{{ v?.title }}</span>
                <span class="els url-scroller">{{ v?.url }}</span>
              </div>
              <el-icon class="closeIcon" size="16px" color="#909399" @click="deletePageInfo(i)">
                <CircleClose />
              </el-icon>
            </div>
          </div>

          <div class="card-btn">
            <el-tooltip content="总结当前页面" placement="top">
              <el-button round @click="handleSummary" :disabled="!taklToHtml">总结</el-button>
            </el-tooltip>

            <el-tooltip content="选择后，在输入框描述填表流程" placement="top">
              <el-button round @click="handelIntelligentFillingClick" :disabled="!taklToHtml">智能填表</el-button>
            </el-tooltip>
          </div>
        </div>

        <el-input ref="textareaRef" v-model="inputMessage" type="textarea" :rows="3" placeholder="输入消息..."
                  @keyup.enter="handleAsk" />
        <div class="chat_area_op">
          <el-button type="primary" link @click="handleAsk" :disabled="!inputMessage.trim() || sendLoading">
            <el-icon size="18" :color="inputMessage.trim() ? 'black' : 'gray'">
              <Promotion />
            </el-icon>
          </el-button>
        </div>
      </div>

    </div>


    <!--  历史记录  -->
    <historyComponent :msgUuid="msgUuid" ref="historyComponentRef" @currentData="(e)=>handleCurrentData(e)" />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, inject, useTemplateRef } from 'vue'
import { ElScrollbar, ElAvatar, ElInput, ElButton } from 'element-plus'
import moment from 'moment'
import {
  buildExcelUnderstandingPrompt,
  getFileSummaryPrompt,
  getSummaryPrompt,
  getFileContent,
  buildObjPrompt
} from '@/utils/ai-service.js'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
import { useMsg } from '@/entrypoints/sidepanel/hook/useMsg.ts'
import Tools from '@/entrypoints/sidepanel/component/tools.vue'
import historyComponent from '@/entrypoints/sidepanel/component/historyComponent.vue'
import { mockData, startMsg, mockData2 } from '@/entrypoints/sidepanel/mock'
import { useAutoResizeTextarea } from '@/entrypoints/sidepanel/hook/useAutoResizeTextarea.ts'
import { getPageInfo, getXlsxValue, handleInput } from './utils/index.js'
import { useMsgStore } from '@/store/modules/msg.ts'

// 滚动条引用
const scrollbar = ref(null)
const xlsxData = ref({})
const isShowPage = ref(false)
const tareRef = useTemplateRef('textareaRef')
const drawerRef = useTemplateRef('historyComponentRef')
// 获取父组件提供的 Hook 实例
const { registerStore, useStore } = inject('indexedDBHook')
const { pageInfoList, messages, msgUuid } = storeToRefs(useMsgStore())
const {
  taklToHtml,
  sendLoading,
  type,
  streamRes,
  getFormKeyAndValue,
  handleSend
} = useMsg(scrollbar)
const inputMessage = ref('')
const pageInfo = ref('')

const addMessage = (msg, raw) => {
  if (!msg) return
  const newMessage = reactive({
    id: messages.value.length + 1,
    username: '我',
    rawContent: raw ?? msg,
    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)
  useStore(msgUuid.value).add(newMessage)
  nextTick(() => {
    scrollbar.value?.setScrollTop(99999)
  })
  return newMessage
}
const handleSummary = async () => {
  const res = await getPageInfo()
  addMessage('总结页面', getSummaryPrompt(res.content))
  handleSend()
}

function handelIntelligentFillingClick() {
  inputMessage.value = '/智能填表 '
  type.value = '2'
}

function handleCurrentData(e) {
  drawerRef.value.drawer = false
  if (!e) {
    addNewDialogue()
    return
  }
  // 添加indexDB Store配置
  msgUuid.value = e
  useStore(e).getAll().then((res) => {
    messages.value = res
    nextTick(() => {
      scrollbar.value?.setScrollTop(99999)
    })
  })
}

async function readClick() {
  isShowPage.value = true
  taklToHtml.value = true
  const tempPageInfo = await getPageInfo()
  pageInfo.value = tempPageInfo
  pageInfoList.value.push(tempPageInfo)
}

function deletePageInfo(i) {
  pageInfoList.value.splice(i, 1)
  if (pageInfoList.value.length === 0) {
    isShowPage.value = false
    taklToHtml.value = false
  }

}

function addNewDialogue() {
  messages.value = []
  msgUuid.value = 'D' + Date.now().toString()
  registerStore({
    name: msgUuid.value,
    keyPath: 'id'
  })
  messages.value.push(startMsg)
  useStore(msgUuid.value).add(startMsg)
}

async function handleAsk() {
  if (sendLoading.value) return
  addMessage(inputMessage.value.trim())
  handleSend(inputMessage.value.trim())
  inputMessage.value = ''
  // streamRes(taklToHtml)
}

function handleCapture() {
  ElMessage({
    message: '开发中...',
    grouping: true,
    showClose: true
  })
}

function hisRecords() {
  drawerRef.value.drawer = true
}

const handleUpload = async (file) => {
  if (type.value === '2') {
    chrome.runtime.sendMessage({
      type: 'FROM_SIDE_PANEL_TO_GET_PAGE_FORM'
    }, async (response) => {
      if (chrome.runtime.lastError) {
        console.error('消息发送错误:', chrome.runtime.lastError)
      } else {
        const fileExtension = file.name.split('.').pop().toLowerCase()
        if (response.status === 'error') return ElMessage({
          message: response.message,
          type: 'error',
          duration: 4 * 1000,
          grouping: true
        })
        if (fileExtension === 'xlsx') {
          const readData = await getXlsxValue(file)
          readData[0].forEach((header, i) => {
            // if (!xlsxData.value[header]) xlsxData.value[header] = []
            xlsxData.value[header] = readData[1][i]
          })
          addMessage(`已上传文件：${file.name}`, buildExcelUnderstandingPrompt(readData[0], file?.name, response.data))
          const a = await streamRes()
          handleInput(xlsxData.value, JSON.parse(a.split('json')[1].split('```')[0]))
        } else {
          const { data, msg } = await getFileValue(file)
          const res2 = await getFormKeyAndValue(data, response.data)
          xlsxData.value = res2.data
          msg.rawContent = buildObjPrompt(res2.data, response.data)
          console.log()

          const a = await streamRes()
          handleInput(xlsxData.value, JSON.parse(a.split('json')[1].split('```')[0]))
          console.log(xlsxData.value)
          console.log(type.value)
        }
      }
      return true
    })
  }
  if (type.value === '') {
    const fileVaue = await getFileValue(file)
    // streamRes()
  }
}
let str = ''

async function getFileValue(file) {
  const msg = addMessage(`文件上传中`)
  sendLoading.value = true
  let formData = new FormData()
  formData.append('file', file)
  const res = await getFileContent(formData)
  sendLoading.value = false
  msg.content = `已上传文件：${file.name}`
  msg.rawContent = res.data
  return {
    data: res.data,
    msg
  }
}
}
const isHoveringTitle = ref(false)
// 组件挂载时滚动到底部
onMounted(() => {
  useAutoResizeTextarea(tareRef, inputMessage)
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'TO_SIDE_PANEL_PAGE_INFO') {
      pageInfo.value = message.data
      // 转发到 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
    }
  })

  // 添加标题悬停事件监听
  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)
  })
  // 添加indexDB Store配置
  msgUuid.value = 'D' + Date.now().toString()
  registerStore({
    name: msgUuid.value,
    keyPath: 'id'
  })
  messages.value.push(startMsg)
  useStore(msgUuid.value).add(startMsg)
})
</script>

<style lang="scss" scoped>
@import '@/entrypoints/sidepanel/css/chat.scss';
</style>
