import { makeAutoObservable, runInAction } from "mobx"
import {
  getBotInfo,
  createConversation,
  startChatStream,
  deleteConversation,
  interruptChat,
} from "@/server/api"
import { XStream } from "@ant-design/x"
import { uid } from "uid"
import { BubbleListRef } from "@ant-design/x/es/bubble/BubbleList"
import { createRef } from "react"

interface IBotInfo {
  name: string
  description: string
  suggestedQuestions: string[]
}
class ExamStore {
  botInfo: IBotInfo | null = null
  conversationID = ""
  isLoading = false
  messageList: any[] = []
  chatId = ""
  controller: AbortController | null = null
  uploading = false
  fileArr: any[] = []
  containerRef = createRef<BubbleListRef>()
  documentTitle = ""
  userId = ""
  constructor() {
    makeAutoObservable(this) // 自动将字段和方法转为响应式
  }

  getBotInfo = async () => {
    // 使用动态考题的固定 bot_id
    const botId = "7509379046204162074"
    const res = await getBotInfo(botId)
    runInAction(() => {
      if (res.code === 10000) {
        this.userId = uid(32)
        document.title = res.data.bot.name
        this.botInfo = {
          ...res.data.bot,
          suggestedQuestions:
            res.data.bot.onboarding_info?.suggested_questions || [],
        }
        this.messageList = [
          {
            id: uid(32),
            content: res.data.bot.onboarding_info?.prologue || "你好，我是你的AI助手，有什么可以帮助你的吗？",
            role: "assistant",
            prologue: "true",
          },
        ]
      }
    })
  }

  streamingChat = (query: string) => {
    if (this.isLoading) {
      return
    }
    runInAction(() => {
      this.messageList.unshift({
        id: uid(32),
        role: "user",
        content: query,
        file_url: this.fileArr,
      })
      this.messageList.unshift({
        id: uid(32),
        role: "assistant",
        content: "",
        loading: true,
        is_answer: 1,
        content_type: "text",
      })
    })
    this.creatChat(query)
  }
  // 创建一个辅助函数来更新消息内容
  updateMessageContent = (content: string) => {
    runInAction(() => {
      this.messageList[0] = {
        ...this.messageList[0],
        content: content,
        loading: false,
      }
    })
  }

  creatChat = async (query: string, id?: string) => {
    this.controller = new AbortController()
    const fileIds = this.fileArr.map((item) => item.id)
    try {
      runInAction(() => {
        this.isLoading = true
        this.fileArr = []
      })
      
      // 如果没有对话ID，先创建对话
      if (!this.conversationID) {
        const conversationRes = await createConversation({ bot_id: "7509379046204162074" })
        if (conversationRes.code === 10000) {
          this.conversationID = conversationRes.data.id
        }
      }
      
      const historyMessages = this.messageList
        .filter((val) => val.content !== "" && !val.prologue)
        .map((item) => {
          return {
            role: item.role,
            content: item.content,
            file_ids:
              item.file_url && item.file_url.length
                ? item.file_url.map((item: any) => item.id)
                : [],
          }
        })
      const response = await startChatStream(
        {
          conversation_id: this.conversationID,
          content: query,
          bot_id: "7509379046204162074",
          file_ids: fileIds,
          user_id: this.userId,
          history_messages: historyMessages,
        },
        this.controller.signal
      )
      let currentContent = ""
      let chatId = ""
      for await (const part of XStream({
        readableStream: response,
      })) {
        if (this.controller?.signal.aborted) {
          // Check if aborted during iteration
          break
        }
        if (typeof part === "string") {
          continue
        }
        // 去除事件名称前后的空格
        const eventName = part.event?.trim() || ""
        if (eventName !== "done") {
          part.data = JSON.parse(part.data)
        }
        console.log("🔄 SSE Event received:", `"${part.event}"`, "->", `"${eventName}"`, "Type:", part.data?.content_type, "Content:", part.data?.content?.substring(0, 100))
        runInAction(() => {
          switch (eventName) {
            case "conversation.chat.created":
              this.conversationID = part.data.conversation_id
              break
            case "conversation.message.delta":
              currentContent += part.data.content
              chatId = part.data.chat_id
              this.updateMessageContent(currentContent)
              if (chatId && this.chatId !== chatId) {
                this.chatId = chatId
              }
              break
            case "conversation.message.completed":
              if (part.data.content_type === "card") {
                console.log("🃏 收到卡片消息，开始解析...")
                console.log("📋 原始卡片内容:", part.data.content)
                
                try {
                  const cardInfo = JSON.parse(part.data.content)
                  console.log("📋 解析后的卡片信息:", cardInfo)
                  
                  let cardData = null
                  
                  // 尝试多种解析方式
                  if (cardInfo.x_properties && cardInfo.x_properties.workflow_card_info) {
                    // 睿美云格式：从 workflow_card_info 中解析
                    const workflowData = JSON.parse(cardInfo.x_properties.workflow_card_info)
                    cardData = workflowData.question_card_data || workflowData
                  } else if (cardInfo.card_content) {
                    // 直接包含 card_content
                    cardData = cardInfo.card_content
                  } else if (cardInfo.Title && cardInfo.Options) {
                    // 直接就是卡片数据格式
                    cardData = cardInfo
                  } else if (cardInfo.card_type) {
                    // 新的卡片格式：包含card_type和template_url
                    console.log("🆕 检测到新的卡片格式，尝试获取完整数据...")
                    
                    // 如果有template_url，可能需要进一步解析
                    if (cardInfo.template_url) {
                      // 创建一个模拟的答题卡数据用于测试
                      cardData = {
                        Title: "请选择你需要的考试类型：",
                        Options: [
                          { name: "超声炮基础方案" },
                          { name: "激光美容技术" },
                          { name: "微整形注射" },
                          { name: "皮肤护理基础" }
                        ]
                      }
                      console.log("🎯 使用模拟答题卡数据:", cardData)
                    }
                  } else {
                    // 尝试从其他可能的字段解析
                    cardData = cardInfo
                  }
                  
                  console.log("🎯 最终解析的卡片数据:", cardData)
                  
                  if (cardData && cardData.Title && cardData.Options) {
                    this.messageList[0].content_type = part.data.content_type
                    this.messageList[0].card_content = cardData
                    this.messageList[0].is_answer = 0
                    this.messageList[0].loading = false
                    console.log("✅ 卡片设置完成")
                  } else {
                    console.warn("⚠️ 无法解析卡片数据结构，保持原始内容")
                    // 保持原始内容但停止加载
                    this.messageList[0].loading = false
                  }
                } catch (e) {
                  console.error("❌ 卡片解析失败:", e, "原始数据:", part.data.content)
                  // 即使解析失败，也要停止加载状态
                  this.messageList[0].loading = false
                }
              }
              break
            case "error":
            case "conversation.chat.failed":
              if (this.messageList[0].role === "assistant") {
                // 如果内容为空，添加错误消息
                if (!this.messageList[0].content) {
                  this.messageList[0].content = "抱歉，请求出错了，请重试。"
                }
                this.messageList[0].loading = false
              }
              break
            default:
              break
          }
        })
      }
    } catch (error) {
      if ((error as Error).name === "CanceledError") {
        runInAction(() => {
          if (this.messageList[0].role === "assistant") {
            // 如果内容为空，添加错误消息
            if (!this.messageList[0].content) {
              this.messageList[0].content = "会话已中断。"
            }
            this.messageList[0].loading = false
          }
        })
      } else {
        console.error("Error during chat stream:", error)
        // 在错误情况下更新UI状态
        runInAction(() => {
          if (this.messageList[0].role === "assistant") {
            // 如果内容为空，添加错误消息
            if (!this.messageList[0].content) {
              this.messageList[0].content = "抱歉，请求出错了，请重试。"
            }
            this.messageList[0].loading = false
          }
        })
      }
    } finally {
      this.complateChat()
      this.controller = null
    }
  }

  abortChat = async () => {
    if (this.chatId && this.conversationID) {
      await interruptChat({
        chat_id: this.chatId,
        conversation_id: this.conversationID,
      })
    }
    this.controller?.abort()
    this.complateChat()
  }

  complateChat = () => {
    runInAction(() => {
      this.isLoading = false
      if (
        this.messageList[0] &&
        !this.messageList[0].content &&
        !this.messageList[0].card_content
      ) {
        this.messageList = this.messageList.slice(1)
        return
      }
      if (this.messageList[0] && this.messageList[0].is_answer) {
        this.messageList[0].is_answer = 0
        this.messageList[0].loading = false
      }
    })
  }

  deleteMessage = async (id: string) => {
    // 暂时简化消息删除功能
    runInAction(() => {
      if (this.messageList.length > 0) {
        this.messageList = this.messageList.filter((item) => item.id !== id)
      }
    })
  }

  reGenerate = () => {
    const content = this.messageList[1]?.content
    const chatId = this.chatId || this.messageList[0]?.chat_id
    this.messageList[0] = {
      id: uid(32),
      role: "assistant",
      content: "",
      loading: true,
      is_answer: 1,
    }
    this.creatChat(content, chatId)
  }

  getBase64(img: any, callback: any) {
    const reader = new FileReader()
    reader.addEventListener("load", () => callback(reader.result))
    reader.readAsDataURL(img)
  }

  onRemoveFile = (fileId: string) => {
    const fileList = this.fileArr.filter((file: any) => file.id !== fileId)
    this.fileArr = fileList
  }

  handleUploadFile = async (file?: any) => {
    if (!file) {
      this.fileArr = []
      return
    }
    // 暂时简化文件上传功能
    this.uploading = false
  }

  scrollToBottom = () => {
    requestAnimationFrame(() => {
      this.containerRef.current?.scrollTo({
        offset: this.containerRef.current?.nativeElement.scrollHeight + 100,
        block: "nearest",
        behavior: "smooth",
      })
    })
  }
}
export default new ExamStore()