<template>
  <div class="ai-report-chat" ref="reportRef">
    <!-- 页面头部 -->
    <div class="chat-header">
      <h2 v-if="!currentExecutionStep">🤖 AI自动生成报表</h2>
      <p v-if="!currentExecutionStep">描述您的数据分析需求，AI将自动生成报表</p>

      <!-- 执行步骤指示器 -->
      <div class="execution-steps" v-if="currentExecutionStep">
        <div class="step-indicator">
          <div class="step" :class="{ active: currentExecutionStep >= 1, completed: currentExecutionStep > 1 }">
            <span class="step-number">1</span>
            <span class="step-text">解析需求</span>
          </div>
          <div class="step-line" :class="{ active: currentExecutionStep >= 2 }"></div>
          <div class="step" :class="{ active: currentExecutionStep >= 2, completed: currentExecutionStep > 2 }">
            <span class="step-number">2</span>
            <span class="step-text">生成SQL</span>
          </div>
          <div class="step-line" :class="{ active: currentExecutionStep >= 3 }"></div>
          <div class="step" :class="{ active: currentExecutionStep >= 3, completed: currentExecutionStep > 3 }">
            <span class="step-number">3</span>
            <span class="step-text">生成报表</span>
          </div>
          <div class="step-line" :class="{ active: currentExecutionStep >= 4 }"></div>
          <div class="step" :class="{ active: currentExecutionStep >= 4, completed: currentExecutionStep > 4 }">
            <span class="step-number">4</span>
            <span class="step-text">生成完成</span>
          </div>
        </div>
      </div>


    </div>


    <!-- 聊天界面 -->
    <div class="chat-container">


      <!-- 消息列表 -->
      <div class="messages-container" ref="messagesContainer">
        <div
          v-for="message in messages"
          :key="message.id"
          :class="['message', message.type]"
        >
          <div class="message-content">
            <!-- 用户消息 -->
            <div v-if="message.type === 'user'" class="user-message">
              <div class="message-text">{{ message.content }}</div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>

            <!-- AI响应消息 -->
            <div v-else-if="message.type === 'ai'" class="ai-message">
              <div class="ai-avatar">🤖</div>
              <div class="ai-content">
                <div v-if="message.content" class="ai-text">{{ message.content }}</div>

                <!-- SQL展示 -->
                <!--                <div v-if="message.sql" class="sql-section">-->
                <!--                  <div class="section-header">-->
                <!--                    <h4>📝 生成的SQL语句</h4>-->
                <!--                    <button @click="copyToClipboard(message.sql)" class="copy-btn">📋 复制</button>-->
                <!--                  </div>-->
                <!--                  <div class="sql-code">-->
                <!--                    <pre><code>{{ message.sql }}</code></pre>-->
                <!--                  </div>-->
                <!--                </div>-->

                <!-- 图表展示 -->
                <div v-if="message.chartHtml" class="chart-section">
                  <div class="chart-actions">
                    <el-button type="primary" size="small" @click="downloadIframeAsImage(message)" class="control-btn"
                               icon="Download" v-hasPermi="['ai:aiReport:download']">
                      下载图片
                    </el-button>

                    <el-button type="primary" size="small" @click="handleExport(message)" class="control-btn"
                               icon="Download" v-hasPermi="['ai:aiReport:export']">
                      导出数据
                    </el-button>
                  </div>

                  <!-- 图表容器 - 固定宽度，防止超出 -->
                  <div class="chart-wrapper">
                    <div class="chart-container">
                      <iframe ref="iframeRef" :srcdoc="message.chartHtml" class="html-preview" style="width: 100%;"
                              :height="message.messageHeight || '300px'"
                              @load="(event) => onIframeLoad(event, message)"></iframe>
                    </div>
                  </div>
                </div>

                <div class="message-time">{{ formatTime(message.timestamp) }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="isLoading" class="loading-message">
          <div class="loading-spinner"></div>
          <div class="loading-content">
            <div class="loading-text">{{ loadingMessage }}</div>
            <div class="loading-progress">
              <div class="progress-bar" :style="{ width: loadingProgress + '%' }"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-container">
        <div class="input-wrapper">
          <div class="input-header">
            <span class="input-tip">💬 描述您的数据分析需求</span>
            <!-- 快速体验示例 - 单行显示在描述文字后面 -->
            <div class="quick-examples-single-line" v-if="showRecents">
              <div
                v-for="recentReport in recentReportList"
                :key="recentReport.chatMessageId"
                class="example-item"
                @click="selectRecentReport(recentReport)"
                :title="removeQuotes(recentReport.messageTopic)"
              >
                {{ removeQuotes(recentReport.messageTopic) }}
              </div>
            </div>
            <span class="input-count">{{ currentMessage.length }}/500</span>
          </div>
          <div class="input-main">
            <textarea
              v-model="currentMessage"
              @keydown="handleKeyDown"
              placeholder="例如：分析物料库存"
              class="message-input"
              rows="3"
              maxlength="500"
            ></textarea>
            <button
              @click="sendMessage"
              :disabled="!currentMessage.trim() || isLoading || currentMessage.length > 500"
              class="send-button"
              :class="{ 'disabled': !currentMessage.trim() || isLoading }"
            >
              {{ isLoading ? '分析中...' : '🚀 发送' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, nextTick, computed} from 'vue'
import {ElMessage} from 'element-plus'
import {
  generateReportSql,
  generateReport,
  getRecentReports,
  getRecentReportInfo,
  generateTestReport,
} from '@/api/ai/skill/aiReport'
import {getToken} from "@/utils/auth";
import html2canvas from 'html2canvas'
import service from "@/utils/request";
import {AiChatMessageForm} from "@/api/ai/skill/aiChat/types";

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

// 响应式数据
const reportRef = ref(null)
const currentMessage = ref('')
const isLoading = ref(false)
const showRecents = ref(true)
const recentReportList = ref([])
const messagesContainer = ref(null)
const messageContainerHeight = ref(100)


const iframeRef = ref(null);
const iframeHeight = ref(0);


// 新增：图表控制相关数据
const showChartControls = ref(false)
const chartSettings = ref({
  width: 600,
  height: 400,
  fontSize: 14,
  labelPosition: 'bottom'
})

// 新增：执行步骤相关数据
const currentExecutionStep = ref(0)
const loadingMessage = ref('')
const loadingProgress = ref(0)

// 新增：表格滚动相关数据
const tableScrollable = ref(true)

// 消息ID生成器
let messageId = 0

// 图表容器样式计算属性
const chartContainerStyle = computed(() => ({
  width: chartSettings.value.width + 'px',
  height: chartSettings.value.height + 'px',
  margin: '0 auto'
}))

// 类型定义
interface ChatMessage {
  id: number,
  type: 'user' | 'ai' | 'system',
  content: string,
  timestamp: number,
  chartHtml: string,
  messageHeight: number,
  messageTopic: string
}

interface ChatSession {
  sessionId: string
  messageTopic: string
  messages: ChatMessage[]
  createdAt: number
  updatedAt: number
}

const provider = ref('DeepSeek');//ai平台编码
const activeChatSessionId = ref('')//当前对话会话id
const streamingContent = ref('')
const currentChat = ref<ChatSession>();
const messages = ref<ChatMessage[]>([]);

// 组件挂载时获取快速体验示例
onMounted(async () => {
  try {
    const response = await getRecentReports()
    console.log(response);
    if (response.code === 200) {
      recentReportList.value = response.rows || []
    }
  } catch (error) {
    console.error('获取常用报表失败:', error)
  }
})

const removeQuotes = (str) => {
  if (!str) return ''
  // 使用字符串表示的正则表达式
  const regex = new RegExp("^['\"]+|['\"]+$", 'g')
  return str.replace(regex, '')
}

// 选择示例
const selectRecentReport = (recentReport) => {
  currentMessage.value = removeQuotes(recentReport.messageTopic)
  showRecents.value = false
  // nextTick(() => {
  //   const input = document.querySelector('.message-input')
  //   if (input) input.focus()
  // })
  sendRecentReportMessage(recentReport)
}

function generateUUID() {
  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  );
}

// 发送消息
const sendMessage = async () => {
  const message = currentMessage.value.trim()
  if (!message || isLoading.value) return

  const messageTopic = message.length > 10 ? message.substring(0, 10) : message;

  const sessionId = generateUUID();
  currentChat.value = {
    sessionId: sessionId,
    messageTopic: messageTopic,
    messages: [],
    createdAt: Date.now(),
    updatedAt: Date.now()
  }

  // 重置执行步骤
  currentExecutionStep.value = 0

  // 添加用户消息
  const userMessage = {
    id: ++messageId,
    type: 'user',
    content: message,
    timestamp: new Date()
  }
  messages.value.push(userMessage)
  currentMessage.value = ''

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  // 添加AI响应消息（初始加载状态）
  const aiMessage = {
    id: ++messageId,
    type: 'ai',
    content: '正在分析您的需求...',
    timestamp: new Date(),
    messageTopic: messageTopic
  }
  messages.value.push(aiMessage)

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  try {
    showRecents.value = false
    isLoading.value = true
    await executionStep(1, aiMessage.id);
    scrollToBottom()
    await executionStep(2, aiMessage.id);
    // 模拟执行步骤
    // await simulateExecutionSteps()

    // 调用后端生成SQL API
    const generateReportSqlResponse = await generateReportSql({
      text: message,
      modelId: 1,
      platformId: 1,
      sessionId: sessionId
    });
    // console.log("00000----:" + JSON.stringify(generateReportSqlResponse))

    await executionStep(3, aiMessage.id);

    let sendMessages = [];

    sendMessages.push(userMessage);

    const data = {
      messages: sendMessages.map(m => ({role: m.role, content: m.content})),
      carryHistoryFlag: "0",
      modelId: 1,
      sessionId: sessionId,
      sql: generateReportSqlResponse.msg,
      messageTopic: messageTopic
    };

    await geneReport(data, aiMessage.id);

    // 完成最后一步
    currentExecutionStep.value = 4

  } catch (error) {
    console.error('AI报表生成失败:', error)
    updateAiMessage(aiMessage.id, {content: '抱歉，分析过程中出现错误，请重试。'})
  } finally {
    showRecents.value = true
    isLoading.value = false
    loadingProgress.value = 100
    await nextTick()
    scrollToBottom()

    // 3秒后隐藏执行步骤
    setTimeout(() => {
      currentExecutionStep.value = 0
    }, 3000)
  }
}

const geneReport = async (sqlData, messageId) => {
  window.reportData = [];
  const response = await generateReport(sqlData);
  if (response.code === 200) {
    const data = response.data

    window.reportData = data.data;
    // console.log("====" + data.data)
    // console.log("====" + JSON.stringify(data.data))
    //const htmlContent = parseHtmlWithDomParser(data.chartHtml)
    // console.log("----" + data.chartHtml);
    // 更新AI消息
    // console.log("aimessageid:"+aiMessage.id)
    let htmlContent = removeQuotes(data.chartHtml);
    htmlContent = decodeHtmlEntities(htmlContent);
    // htmlContent = htmlContent
    //     .replace(/\\n/g, '\n')  // 先替换转义的\n
    //     .replace(/\n/g, '<br>') // 再替换换行符
    //     .replace(/\\r\\n/g, '<br>') // 处理Windows换行
    // console.log("----" + htmlContent);
    console.log(sqlData.messageTopic)
    updateAiMessage(messageId, {
      content: '分析完成！以下是为您生成的报表：',
      chartHtml: htmlContent,
      sql: sqlData.sql,
    })

  } else {
    updateAiMessage(messageId, {content: '分析失败：' + response.msg})
  }
}


function decodeHtmlEntities(str) {
  return str
    .replace(/\\"/g, '"')
    .replace(/\\'/g, "'")
    .replace(/\\\\/g, '\\');
}


function unescapeHtml(html) {
  const txt = document.createElement('textarea')
  txt.innerHTML = html
  return txt.value
}


// 发送选择最新一条AI生成报表的消息
const sendRecentReportMessage = async (recentReport: AiChatMessageForm) => {
  const sessionId = recentReport.sessionId;
  const messageTopic = removeQuotes(recentReport.messageTopic)
  currentChat.value = {
    sessionId: sessionId,
    messageTopic: messageTopic,
    messages: [],
    createdAt: Date.now(),
    updatedAt: Date.now()
  }

  const message = currentMessage.value.trim()
  if (!message || isLoading.value) return

  // 重置执行步骤
  currentExecutionStep.value = 0

  // 添加用户消息
  const userMessage = {
    id: ++messageId,
    type: 'user',
    content: message,
    timestamp: new Date()
  }
  messages.value.push(userMessage)
  currentMessage.value = ''
  showRecents.value = false

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  // 添加AI响应消息（初始加载状态）
  const aiMessage = {
    id: ++messageId,
    type: 'ai',
    content: '正在分析您的需求...',
    timestamp: new Date(),
    messageTopic: messageTopic
  }
  messages.value.push(aiMessage)

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  try {
    showRecents.value = false
    isLoading.value = true
    await executionStep(1, aiMessage.id);
    scrollToBottom()
    await executionStep(2, aiMessage.id);
    // 模拟执行步骤
    // await simulateExecutionSteps()

    // 调用后端根据sessionId获取SQL
    const generateReportSqlResponse = await getRecentReportInfo({sessionId: sessionId, messageDetailType: '7'});
    console.log("00000----:" + generateReportSqlResponse.data.answerContent)

    await executionStep(3, aiMessage.id);

    let sendMessages = [];

    sendMessages.push(userMessage);

    const data = {
      messages: sendMessages.map(m => ({role: m.role, content: m.content})),
      carryHistoryFlag: "0",
      modelId: 1,
      sessionId: sessionId,
      sql: generateReportSqlResponse.data.answerContent
    };

    // 调用后端根据sessionId或messageId获取SQL
    await geneReport(data, aiMessage.id);

    // 完成最后一步
    currentExecutionStep.value = 4

  } catch (error) {
    console.error('AI报表生成失败:', error)
    updateAiMessage(aiMessage.id, {content: '抱歉，分析过程中出现错误，请重试。'})
  } finally {
    showRecents.value = true
    isLoading.value = false
    loadingProgress.value = 100
    await nextTick()
    scrollToBottom()

    // 3秒后隐藏执行步骤
    setTimeout(() => {
      currentExecutionStep.value = 0
    }, 3000)
  }
}


// 发送消息
const streamSendMessage = async () => {
  const message = currentMessage.value.trim()
  if (!message || isLoading.value) return

  // 重置执行步骤
  currentExecutionStep.value = 0

  // 添加用户消息
  const userMessage = {
    id: ++messageId,
    type: 'user',
    content: message,
    timestamp: new Date()
  }
  messages.value.push(userMessage)
  currentMessage.value = ''
  showRecents.value = false

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  // 添加AI响应消息（初始加载状态）
  const aiMessage = {
    id: ++messageId,
    type: 'ai',
    content: '正在分析您的需求...',
    timestamp: new Date()
  }
  messages.value.push(aiMessage)

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  try {
    isLoading.value = true

    // 模拟执行步骤
    await simulateExecutionSteps()

    // 调用后端API
    const request = {
      prompt: message,
      dataSourceId: 'default',
      chartType: 'auto',
      parameters: {}
    }

    let sendMessages = [];

    sendMessages.push(userMessage);

    const response = await service.post('/ai/aiReport/streamGenerate?provider=' + provider.value, {
      messages: sendMessages.map(m => ({role: m.role, content: m.content})),
      carryHistoryFlag: "0",
      modelId: 1,
      sessionId: activeChatSessionId.value,
    }, {
      responseType: 'text',
      headers: {
        'Authorization': 'Bearer ' + getToken(),
        'Content-Type': 'application/json'
      },
      onDownloadProgress: progress => {
        const raw = progress.event.target.responseText
        processStream(raw)
      }
    })

    // const rawHtml = parseHtmlWithMarkdown();
    // console.log("--=====:"+streamingContent.value);
    const htmlContent = parseHtmlWithDomParser(streamingContent.value)
    // console.log("-====:"+htmlContent)
    // 更新AI消息
    updateAiMessage(aiMessage.id, {
      content: '分析完成！以下是为您生成的报表：',
      chartHtml: htmlContent,
    })

    // 完成最后一步
    currentExecutionStep.value = 4

  } catch (error) {
    console.error('AI报表生成失败:', error)
    updateAiMessage(aiMessage.id, {content: '抱歉，分析过程中出现错误，请重试。'})
  } finally {
    isLoading.value = false
    loadingProgress.value = 100
    await nextTick()
    scrollToBottom()

    // 3秒后隐藏执行步骤
    setTimeout(() => {
      currentExecutionStep.value = 0
    }, 3000)
  }
}


const sendMessage1 = async () => {
  // 使用
  //输入信息。isLoading代表是否正在发送信息
  if (!currentMessage.value.trim() || isLoading.value) {
    return
  }

  const userMsg = currentMessage.value.trim()

  // const model = aiModelList.value.find(m => m.modelId === selectedModel.value)
  // if (model) {
  //   platformIcon.value = model.platformIcon;
  // }

//用户当前发送的内容
  const userMessage: ChatMessage = {
    id: ++messageId,
    type: 'user',
    content: userMsg,
    timestamp: Date.now(),
  }

  // 添加用户消息
  messages.value.push(userMessage)


  currentMessage.value = ''
  isLoading.value = true
  streamingContent.value = ''

  // 添加AI响应消息（初始加载状态）
  const aiMessage = {
    id: ++messageId,
    type: 'ai',
    content: '正在分析您的需求...',
    timestamp: new Date()
  }
  messages.value.push(aiMessage)

  try {
    //判断是否携带历史记录
    let sendMessages = [];

    sendMessages.push(userMessage);


    const response = await service.post('/ai/aiReport/generate?provider=' + provider.value, {
      messages: sendMessages.map(m => ({role: m.role, content: m.content})),
      carryHistoryFlag: "0",
      modelId: 1,
      sessionId: activeChatSessionId.value,
    }, {
      responseType: 'text',
      headers: {
        'Authorization': 'Bearer ' + getToken(),
        'Content-Type': 'application/json'
      },
      onDownloadProgress: progress => {
        const raw = progress.event.target.responseText
        processStream(raw)
      }
    })

    // console.log("----" + streamingContent.value);
    const rawHtml = parseHtmlWithMarkdown();

    const htmlContent = parseHtmlWithDomParser(rawHtml)

    // console.log("-====:"+htmlContent)
    // 更新AI消息
    // console.log("aimessageid:"+aiMessage.id)
    updateAiMessage(aiMessage.id, {
      content: '分析完成！以下是为您生成的报表：',
      chartHtml: htmlContent,

    })

    // 添加用户消息到messages数组
    // messages.value.push({
    //   role: 'assistant',
    //   content: streamingContent.value,
    //   timestamp: Date.now(),
    //   platformIcon: platformIcon.value,
    // })
  } catch (error) {
    // messages.value.push({
    //   role: 'assistant',
    //   content: '出错: ' + (error as Error).message,
    //   timestamp: Date.now(),
    //   platformIcon: platformIcon.value,
    // })
  } finally {
    isLoading.value = false;
    streamingContent.value = ''
  }
}

let i = 1;
let j = 1;
// 处理流数据
const processStream = (raw) => {
  const chunks = raw.split('\n\n').filter(c => c.startsWith('data:'))
  let fullText = streamingContent.value || '' // 从当前内容开始

  chunks.forEach(chunk => {
    let content = chunk.substring(5).trim()

    if (content && content !== '[DONE]') {
      // 移除行首可能存在的data:
      content = content.replace(/^data:\s*/, '')

      // 核心逻辑改进：更准确的startsWith检查
      if (content.startsWith(fullText)) {
        // 新内容完全包含旧内容，直接替换
        fullText = content
      } else if (fullText && content.length > fullText.length) {
        // 检查是否有部分重叠
        // 常见情况：fullText="<html"，content="<html \n>"
        // 这时content不以fullText开头，但包含了fullText

        // 方法1：检查是否包含
        if (content.includes(fullText)) {
          fullText = content
        }
        // 方法2：检查是否只是多了换行符等空白
        else if (content.replace(/\s+/g, '').startsWith(fullText.replace(/\s+/g, ''))) {
          fullText = content
        }
        // 方法3：可能是分段不同
        else {
          // 尝试找到最长匹配前缀
          let matchEnd = 0
          for (let i = 1; i <= Math.min(fullText.length, content.length); i++) {
            if (fullText.substring(0, i) === content.substring(0, i)) {
              matchEnd = i
            }
          }

          if (matchEnd > 0) {
            // 有部分匹配，追加剩余部分
            fullText = content
          } else {
            // 完全不同的内容，追加
            fullText += content
          }
        }
      }
      // 如果内容更短，忽略（除非是第一次）
      else if (fullText === '' && content) {
        fullText = content
      }
    }
  })

  // 只在实际内容变化时更新
  if (fullText !== streamingContent.value) {
    streamingContent.value = fullText
    scrollToBottom()
  }
}


function parseHtmlWithMarkdown() {
  // 预处理：移除 Markdown 代码块标记
  let processedContent = streamingContent.value
    // 移除 ```html 标记
    .replace(/```html\s*/g, '')
    .replace(/```\s*/g, '')
    // 移除 ```javascript 等其他代码块标记
    .replace(/```[a-zA-Z]*\s*/g, '')
    // 移除行内的代码标记
    .replace(/`([^`]+)`/g, '$1');

  // 使用 DOMParser 解析
  const parser = new DOMParser();
  const doc = parser.parseFromString(processedContent, 'text/html');
// console.log("-====2222:"+doc)
  return doc;
}

function parseHtmlWithDomParser(rawHtml) {
  try {
    // 使用 DOMParser 解析 HTML
    const parser = new DOMParser();
    const doc = parser.parseFromString(rawHtml, 'text/html');

    // 获取整个 html 元素
    const htmlElement = doc.documentElement;

    // 方法1：获取 outerHTML（包含<html>标签）
    // console.log("---:::::"+htmlElement.outerHTML)
    // console.log(doc.body.innerHTML)

    return htmlElement.outerHTML;

  } catch (error) {
    return `解析错误: ${error.message}`;
  }
}


const sendTestMessage = async () => {
  const message = currentMessage.value.trim()
  if (!message || isLoading.value) return

  // 重置执行步骤
  currentExecutionStep.value = 0

  // 添加用户消息
  const userMessage = {
    id: ++messageId,
    type: 'user',
    content: message,
    timestamp: new Date()
  }
  messages.value.push(userMessage)
  currentMessage.value = ''
  showRecents.value = false

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  // 添加AI响应消息（初始加载状态）
  const aiMessage = {
    id: ++messageId,
    type: 'ai',
    content: '正在分析您的需求...',
    timestamp: new Date()
  }
  messages.value.push(aiMessage)

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  try {
    isLoading.value = true

    // 模拟执行步骤
    await simulateExecutionSteps()

    // 调用后端API
    const request = {
      prompt: message,
      dataSourceId: 'default',
      chartType: 'auto',
      parameters: {}
    }

    const response = await generateTestReport(request)

    if (response.code === 200) {
      const data = response.data


      const htmlContent = parseHtmlWithDomParser(data.chartHtml)
      // console.log("----" + htmlContent);
      // 更新AI消息
      // console.log("aimessageid:"+aiMessage.id)
      updateAiMessage(aiMessage.id, {
        content: '分析完成！以下是为您生成的报表：',
        chartHtml: htmlContent,

      })


      // 完成最后一步
      currentExecutionStep.value = 4
    } else {
      updateAiMessage(aiMessage.id, {content: '分析失败：' + response.msg})
    }
  } catch (error) {
    console.error('AI报表生成失败:', error)
    updateAiMessage(aiMessage.id, {content: '抱歉，分析过程中出现错误，请重试。'})
  } finally {
    isLoading.value = false
    loadingProgress.value = 100
    await nextTick()
    scrollToBottom()

    // 3秒后隐藏执行步骤
    setTimeout(() => {
      currentExecutionStep.value = 0
    }, 3000)
  }
}

//执行步骤
const steps = [
  {message: '正在解析您的需求...', progress: 25},
  {message: '正在生成SQL语句...', progress: 50},
  {message: '正在生成可视化报表...', progress: 75},
  {message: '正在整理分析结果...', progress: 100}
]
// 模拟执行步骤
const executionStep = async (step: number, aiMessageId: number) => {
  currentExecutionStep.value = step
  loadingMessage.value = steps[step - 1].message
  loadingProgress.value = steps[step - 1].progress

  // 更新加载消息
  updateAiMessage(aiMessageId, {content: steps[step - 1].message})

  await new Promise(resolve => setTimeout(resolve, 800))
}


// 模拟执行步骤
const simulateExecutionSteps = async () => {
  for (let i = 0; i < steps.length; i++) {
    currentExecutionStep.value = i + 1
    loadingMessage.value = steps[i].message
    loadingProgress.value = steps[i].progress

    // 更新加载消息
    const lastMessage = messages.value[messages.value.length - 1]
    if (lastMessage && lastMessage.type === 'ai') {
      updateAiMessage(lastMessage.id, {content: steps[i].message})
    }

    await scrollToBottom()
    await new Promise(resolve => setTimeout(resolve, 800))
  }
}

// 更新AI消息
const updateAiMessage = (messageId, updates) => {
  const message = messages.value.find(m => m.id === messageId)
  if (message) {
    Object.assign(message, updates)
  }
}

// 处理键盘事件
const handleKeyDown = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

// 滚动到消息底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleDateString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 复制到剪贴板
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('复制成功！')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 新增：图表控制相关方法
const toggleChartControls = () => {
  showChartControls.value = !showChartControls.value
}

const toggleTableScroll = () => {
  tableScrollable.value = !tableScrollable.value
}


// 新增：数据统计相关方法
const getDataRowCount = (message) => {
  if (message.tableHtml) {
    const match = message.tableHtml.match(/<tr>/g)
    return match ? match.length - 1 : 0 // 减去表头行
  }
  return 0
}

const getQueryType = (sql) => {
  if (!sql) return '未知'
  const sqlUpper = sql.toUpperCase().trim()
  if (sqlUpper.startsWith('SELECT')) return '查询'
  if (sqlUpper.startsWith('INSERT')) return '插入'
  if (sqlUpper.startsWith('UPDATE')) return '更新'
  if (sqlUpper.startsWith('DELETE')) return '删除'
  return '其他'
}


// iframe加载完成时
const onIframeLoad = (event, message) => {
  // const iframe = iframeRef.value
  const iframe = event.target;
  const height = iframe.contentDocument.body.scrollHeight + 100
  message.messageHeight = height + 'px';

  // const report = reportRef.value;
  // messageContainerHeight.value = messageContainerHeight.value + iframeHeight.value

  // 设置内容变化监听
  // setupIframeResize();
};


// 将iframe内容转换为图片下载
const downloadIframeAsImage = async (message) => {
  try {
    // 找到对应的iframe元素
    const iframeArr = iframeRef.value ? iframeRef.value : [];
    const iframe = iframeArr[0]
    if (!iframe || !iframe.contentWindow || !iframe.contentWindow.document) {
      ElMessage.error('iframe内容未加载完成');
      return;
    }

    const iframeDocument = iframe.contentWindow.document;
    const iframeBody = iframeDocument.body;

    // 使用html2canvas将iframe内容转换为canvas
    const canvas = await html2canvas(iframeBody, {
      scale: 2, // 提高图片质量
      useCORS: true, // 允许跨域图片
      allowTaint: true,
      logging: false
    });

    // 将canvas转换为图片
    const imageDataUrl = canvas.toDataURL('image/png');

    // 创建下载链接
    const link = document.createElement('a');
    link.href = imageDataUrl;
    link.download = message.messageTopic + `_${new Date().getTime()}.png`;
    link.style.display = 'none';

    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success('图表下载成功');
  } catch (error) {
    console.error('下载图表失败:', error);
    ElMessage.error('下载图表失败，请重试');
  }
};

/** 导出按钮操作 */
const handleExport = (message) => {
  console.log(message)
  proxy?.download('ai/aiReport/exportReportData', {
    sql: message.sql,
    text: message.messageTopic,
  }, message.messageTopic + `_${new Date().getTime()}.xlsx`);
};


</script>

<style scoped>
.iframe-container {
  width: 100%;
  overflow: hidden;
}

.html-preview {
  width: 100%;
  border: none;
  display: block;
  transition: height 0.3s ease;
}

.chart-actions {
  margin-top: 2px;
  text-align: left;
}

.chart-actions .el-button {
  font-size: 12px;
}

.ai-report-chat {
  min-height: 91vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  overflow: hidden;
}

/* 页面头部 */
.chat-header {
  background: white;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
  text-align: center;
  height: 100px;
}

.chat-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.chat-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

/* 快速体验示例 - 单行显示 */
.quick-examples-single-line {
  display: flex;
  gap: 8px;
  margin: 0 8px;
  flex-wrap: nowrap;
  overflow: hidden;
}

.example-item {
  padding: 4px 10px;
  background: #f0f9ff;
  border: 1px solid #e1f5fe;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 13px;
  color: #1976d2;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
}

.example-item:hover {
  background: #e3f2fd;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(25, 118, 210, 0.15);
  max-width: none;
  white-space: normal;
  overflow: visible;
  z-index: 10;
  position: relative;
}

/* 调整输入区域布局 */
.input-container {
  display: flex;
  flex-direction: column;
  margin-top: 0;
}

.input-wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.input-header {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.input-tip {
  flex-shrink: 0;
}

/* 聊天容器 */
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin: 6px 6px 0 6px;
  overflow: hidden;
}

/* 消息容器 */
.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.message {
  margin-bottom: 20px;
}

.user-message {
  display: flex;
  justify-content: flex-end;
}

.user-message .message-text {
  max-width: 70%;
  padding: 12px 16px;
  background: #007bff;
  color: white;
  border-radius: 18px 18px 4px 18px;
  word-wrap: break-word;
}

.ai-message {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.ai-avatar {
  width: 36px;
  height: 36px;
  background: #f0f9ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
}

.ai-content {
  flex: 1;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.ai-text {
  margin-bottom: 16px;
  color: #303133;
  line-height: 1.6;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* SQL部分 */
.sql-section {
  margin: 16px 0;
}

.sql-section h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.sql-code {
  position: relative;
  background: #1e1e1e;
  border-radius: 6px;
  padding: 12px;
  overflow-x: auto;
}

.sql-code code {
  color: #d4d4d4;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
  line-height: 1.4;
}

.copy-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  background: #007bff;
  border: none;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.copy-btn:hover {
  background: #0056b3;
}

/* 图表和表格部分 */
.chart-section, .table-section {
  margin: 16px 0;
}

.chart-html, .table-html {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

/* 分析部分 */
.analysis-section {
  margin: 16px 0;
}

.analysis-section h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.analysis-content {
  background: #f0f9ff;
  border: 1px solid #e1f5fe;
  border-radius: 6px;
  padding: 12px;
}

.analysis-content pre {
  margin: 0;
  color: #1976d2;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
}

.execution-time {
  margin-top: 12px;
  padding: 8px 12px;
  background: #f0f9ff;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

/* 加载状态 */
.loading-message {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  justify-content: center;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #e4e7ed;
  border-top: 2px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-progress {
  height: 10px;
  background-color: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background-color: #007bff;
  transition: width 0.3s;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 输入区域 */
.input-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 16px;
  width: 100%;
  height: 160px;
  box-sizing: border-box;
}

.input-wrapper {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.input-main {
  display: flex;
  gap: 12px;
  width: 100%;
}

.message-input {
  flex: 1;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  padding: 12px;
  font-size: 14px;
  resize: none;
  font-family: inherit;
  line-height: 1.5;
  width: calc(100% - 120px);
}

.input-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.message-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.send-button {
  background: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 12px 24px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
  white-space: nowrap;
}

.send-button:hover:not(:disabled) {
  background: #0056b3;
}

.send-button:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-report-chat {
    margin: 0;
  }

  .chat-container {
    margin: 0 8px 8px 8px;
  }

  .user-message .message-text {
    max-width: 85%;
  }

  .examples-grid {
    grid-template-columns: 1fr;
  }
}

/* 新增样式 - 执行步骤指示器 */
.execution-steps {
  margin-bottom: 6px;
  padding: 6px;
}

.step-indicator {
  display: flex;
  align-items: center;
  justify-content: space-between;
  max-width: 600px;
  margin: 0 auto;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  flex: 1;
}

.step-number {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #e4e7ed;
  color: #909399;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  transition: all 0.3s;
}

.step.active .step-number {
  background: #007bff;
  color: white;
}

.step.completed .step-number {
  background: #67c23a;
  color: white;
}

.step-text {
  font-size: 12px;
  color: #909399;
  text-align: center;
}

.step.active .step-text {
  color: #007bff;
  font-weight: 600;
}

.step-line {
  height: 2px;
  background: #e4e7ed;
  flex: 1;
  margin: 0 8px;
  transition: background-color 0.3s;
}

.step-line.active {
  background: #007bff;
}

/* 新增样式 - 图表控制面板 */
.chart-controls-panel {
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  margin: 12px 0;
}

.control-group {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.control-group:last-child {
  margin-bottom: 0;
}

.control-group label {
  font-size: 13px;
  color: #606266;
  min-width: 80px;
}

.slider {
  flex: 1;
  max-width: 200px;
}

.control-select {
  padding: 4px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 13px;
}

.control-value {
  font-size: 12px;
  color: #909399;
  min-width: 50px;
}

.control-btn {
  background: #f0f9ff;
  border: 1px solid #e1f5fe;
  color: #1976d2;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
  margin-left: 8px;
}

.control-btn:hover {
  background: #e3f2fd;
  border-color: #1976d2;
}

/* 新增样式 - 图表包装器，防止超出 */
.chart-wrapper {
  max-width: 100%;
  overflow-x: auto;
  padding: 0;
  margin: 12px 0;
}

.chart-container {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  background: white;
  margin: 0 auto;
  flex-shrink: 0;
}

.chart-html {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

/* 消息容器滚动优化 */
.messages-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 8px;
  max-height: calc(91vh - 280px);
}

/* 确保图表区域不会超出标题 */
.chart-section {
  margin: 16px 0;
  max-width: 100%;
  overflow: hidden;
}

.chart-section .section-header {
  flex-shrink: 0;
}
</style>
