<template>
  <div class="ai-assistant">
    <a-row :gutter="16">
      <!-- 左侧代码编辑器 -->
      <a-col :span="12">
        <a-card class="editor-card" title="代码编辑器">
          <div class="editor-container" ref="editorContainer"></div>
          <div class="editor-actions">
            <a-button type="primary" @click="sendMessage" :loading="loading">
              发送到 AI 助手
            </a-button>
            <a-button @click="clearCode">清空代码</a-button>
          </div>
        </a-card>
      </a-col>

      <!-- 右侧对话界面保持不变 -->
      <a-col :span="12">
        <a-card class="chat-card" title="AI 助手对话">
          <div class="chat-container" ref="chatContainer">
            <div
              v-for="(message, index) in chatHistory"
              :key="index"
              :class="['message', message.type]"
            >
              <div class="message-avatar">
                <a-avatar
                  :src="message.type === 'user' ? userAvatar : aiAvatar"
                />
              </div>
              <div class="message-content">
                <div
                  class="message-text"
                  v-html="formatMessage(message.content)"
                ></div>
                <div class="message-time">{{ message.time }}</div>
              </div>
            </div>
          </div>
          <div class="chat-input">
            <a-input-search
              v-model:value="inputMessage"
              placeholder="输入问题或直接发送代码"
              enter-button="发送"
              :loading="loading"
              @search="sendTextMessage"
            />
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import * as monaco from "monaco-editor";
import hljs from "highlight.js";
import "highlight.js/styles/github.css";
import { marked } from "marked";
import { AiChat } from "@/api";

export default {
  name: "AiAssistant",
  data() {
    return {
      code: "// 在这里输入你的代码\n",
      inputMessage: "",
      loading: false,
      chatHistory: [],
      editor: null,
      userAvatar:
        "https://onlinephoto.oss-cn-chengdu.aliyuncs.com/hangtian/touxiang.jpg",
      aiAvatar: "https://avatars.githubusercontent.com/u/2?v=4",
    };
  },
  mounted() {
    this.initEditor();
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.dispose();
    }
    window.removeEventListener("resize", this.handleResize);
  },
  methods: {
    initEditor() {
      this.editor = monaco.editor.create(this.$refs.editorContainer, {
        value: this.code,
        language: "javascript",
        theme: "vs-dark",
        fontSize: 14,
        lineNumbers: "on",
        minimap: { enabled: false },
        scrollBeyondLastLine: false,
        automaticLayout: true,
      });

      // 监听编辑器内容变化
      this.editor.onDidChangeModelContent(() => {
        this.code = this.editor.getValue();
      });
    },
    handleResize() {
      if (this.editor) {
        this.editor.layout();
      }
    },
    formatMessage(content) {
      return marked(content, {
        highlight: (code, lang) => {
          if (lang && hljs.getLanguage(lang)) {
            return hljs.highlight(code, { language: lang }).value;
          }
          return hljs.highlightAuto(code).value;
        },
      });
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },
    addMessage(content, type = "user") {
      this.chatHistory.push({
        content,
        type,
        time: new Date().toLocaleTimeString(),
      });
      this.scrollToBottom();
    },
    async sendMessage() {
      if (!this.code.trim()) return;

      this.loading = true;
      this.addMessage("```javascript\n" + this.code + "\n```");

      try {
        const response = await AiChat({
          userId: this.$store.state.user.userId,
          question: this.code,
          competitionType: "编程",
        });

        if (
          response.code === 200 &&
          response.data &&
          response.data.code === 200
        ) {
          this.addMessage(response.data.data, "ai");
        } else {
          this.addMessage("AI 助手暂时无法回复，请稍后再试。", "ai");
        }
      } catch (error) {
        console.error("AI 响应错误:", error);
        this.addMessage("发生错误，请稍后重试。", "ai");
      } finally {
        this.loading = false;
      }
    },

    async sendTextMessage() {
      if (!this.inputMessage.trim()) return;

      this.loading = true;
      this.addMessage(this.inputMessage);

      try {
        const response = await AiChat({
          userId: this.$store.state.user.userId,
          question: this.inputMessage,
          competitionType: "编程",
        });

        if (
          response.code === 200 &&
          response.data &&
          response.data.code === 200
        ) {
          this.addMessage(response.data.data, "ai");
        } else {
          this.addMessage("AI 助手暂时无法回复，请稍后再试。", "ai");
        }
        this.inputMessage = "";
      } catch (error) {
        console.error("AI 响应错误:", error);
        this.addMessage("发生错误，请稍后重试。", "ai");
      } finally {
        this.loading = false;
      }
    },
    clearCode() {
      if (this.editor) {
        this.editor.setValue("// 在这里输入你的代码\n");
      }
    },
  },
};
</script>

<style scoped>
.ai-assistant {
  /* padding: 24px; */
  background: #f0f2f5;
  min-height: calc(100vh - 64px);
}

.editor-card,
.chat-card {
  height: calc(100vh - 112px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin-bottom: 16px;
  max-height: calc(100vh - 200px); /* 添加最大高度 */
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.3) transparent;
}

/* 滚动条样式 */
.chat-container::-webkit-scrollbar {
  width: 6px;
}

.chat-container::-webkit-scrollbar-track {
  background: transparent;
}

.chat-container::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 3px;
}

.chat-container::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.5);
}

.editor-container {
  height: calc(100% - 60px);
  min-height: 70vh;
}

.editor-actions {
  margin-top: 16px;
  display: flex;
  gap: 8px;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin-bottom: 16px;
}

.message {
  display: flex;
  margin-bottom: 16px;
}

.message.ai {
  flex-direction: row;
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 12px;
}

.message-content {
  max-width: 70%;
  background: #e6f7ff;
  padding: 12px;
  border-radius: 8px;
  word-break: break-word;
}

.message.user .message-content {
  background: #000; /* 修改用户消息背景色 */
  color: #ffffff; /* 修改用户消息文字颜色 */
}

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

.message.user .message-time {
  color: rgba(255, 255, 255, 0.8); /* 修改用户消息时间颜色 */
}

:deep(.message-text pre) {
  background: #f6f8fa;
  padding: 16px;
  border-radius: 4px;
  overflow-x: auto;
  margin: 8px 0; /* 添加上下间距 */
}

/* 修改用户消息中的代码块样式 */
.message.user :deep(.message-text pre) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #ffffff; /* 修改代码文字颜色 */
}

/* 修改用户消息中的行内代码样式 */
.message.user :deep(.message-text code) {
  background: rgba(255, 255, 255, 0.15);
  color: #ffffff;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 修改用户消息中的链接样式 */
.message.user :deep(.message-text a) {
  color: #ffffff;
  text-decoration: underline;
}

.chat-input {
  padding: 16px;
  background: #fff;
  border-top: 1px solid #e8e8e8;
}

:deep(.ant-card-head) {
  background: #1890ff;
  color: white;
}

:deep(.ant-card-head-title) {
  color: white;
}
</style>
