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

    <Tools @read-click="isShowPage = true, taklToHtml = true" @upload-file="handleUpload" />

    <div>
      <!-- 输入区域 -->
      <div class="input-area">
        <div v-show="isShowPage" style="border-bottom: 1px solid #F0F0F0;">
          <div class="card-content">
            <img :src="pageInfo?.favIconUrl" style="width: 24px;" />
            <div class="title-wrapper">
              <div class="title-scroller" :class="{ 'scroll': isHoveringTitle && titleScroll }">
                {{ pageInfo?.title }}
              </div>
            </div>
            <el-icon size="16px" @click="isShowPage = false; taklToHtml = false">
              <CircleClose />
            </el-icon>
          </div>
          <div class="card-btn">
            <el-tooltip content="总结当前页面" placement="top">
              <el-button round @click="handleCardButtonClick" :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="() => {
          addMessage(inputMessage.trim(), true)
          inputMessage = ''
        }" />
        <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>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, inject, useTemplateRef } from 'vue'
import { ElScrollbar, ElAvatar, ElInput, ElButton } from 'element-plus'
import avator from '@/public/icon/32.png'
import moment from 'moment'
import { 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"
import {upload} from '@/utils/ai-service'
import { useAutoResizeTextarea } from '@/entrypoints/sidepanel/hook/useAutoResizeTextarea.ts';

// 滚动条引用
const scrollbar = ref(null);
const type = ref('');
const xlsxData = ref({});
const isShowPage = ref(false);
const tareRef = useTemplateRef("textareaRef");
const {
  messages,
  inputMessage,
  indexTemp,
  taklToHtml,
  pageInfo,
  sendLoading,
  addMessage,
  sendRequese,
  getPageInfo,
  streamRes,
  handleInput
} = useMsg(scrollbar, type, xlsxData, fetchDataAndProcess);
const { handleCardButtonClick } = useSummary(addMessage, sendRequese);

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

function handleAsk() {
  addMessage(inputMessage.value.trim(), true);
  inputMessage.value = '';
}

// 计算标题是否需要滚动
const titleScroll = computed(() => {
  return pageInfo.value?.title?.length > 20 // 当标题超过20个字符时触发滚动
})

// let formMap = []
let formInfo = []
const flag = ref(false)  //true调用算法接口

const handleUpload = (file) => {
 console.log(upload);
 
  chrome.runtime.sendMessage({
    type: 'FROM_SIDE_PANEL_TO_GET_PAGE_FORM',
  }, async (response) => {
    if (chrome.runtime.lastError) {
      console.error("消息发送错误:", chrome.runtime.lastError);
    } else {
      console.log(file);
      addMessage(`已上传文件：${file.name}`, false)
      const fileExtension = file.name.split('.').pop().toLowerCase();
      console.log('文件后缀:', fileExtension);
      if (fileExtension === 'xlsx') {

        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.value[header]) xlsxData.value[header] = []
            xlsxData.value[header].push(readData[1][i])
          })
          if (type.value === '2') {
            await streamRes(buildExcelUnderstandingPrompt(readData, file?.name, response), false)
          }
        };
      } else {
        let formData = new FormData();
        formData.append("file", file);
        const res = await upload(formData)
        console.log(res);
      }
    }
    return true
  });

}

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.value] })
    }, 1000)
  })
  await handleClick(res.data, obj);
}


async function handleClick(res, msgObj) {
  await new Promise(resolve => setTimeout(resolve, 2000))
  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.value++
          fetchDataAndProcess('', 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 isHoveringTitle = ref(false)

// 组件挂载时滚动到底部
onMounted(async () => {
  useAutoResizeTextarea(tareRef, inputMessage);
  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 lang="scss" scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #F0F0F0;
  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;
}

.info-card {
  margin: 10px;
}

/* .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;
}

.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;
  }
}


.input-area {
  padding: 8px 10px;
  color: black;
  background-color: #fff;
  border: 1px solid rgba(102, 102, 102, 0.3);
  border-radius: 16px;
  margin: 0 12px 12px;

  .card-content {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 14px 12px;
    margin: 0 0 6px;
    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.4s;
  }

  .card-btn {
    padding: 0 0 4px;

    .op {
      margin-right: 3px;
    }
  }

  .chat_area_op {
    margin-top: 3px;
    display: flex;
    justify-content: end;
  }
}

.input-area:hover {
  border-color: rgba(102, 102, 102, 0.4);
}

.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) {
  padding: 0 4px;
  margin-top: 3px;
}

.input-area :deep(.el-textarea__inner:focus) {
  border-color: #409eff;
  box-shadow: none;
}
</style>
