import { makeAutoObservable, runInAction } from "mobx"
import {
  getBotInfo,
  createConversation,
  startChatStream,
  deleteConversation,
  interruptChat,
} from "@/server/api"
import { XStream } from "@ant-design/x"
import dayjs from "dayjs"
import { uid } from "uid"
import { BubbleListRef } from "@ant-design/x/es/bubble/BubbleList"
import { createRef } from "react"
interface IConversation {
  content: string
  createDate: number
  id: string
}
interface IBotInfo {
  name: string
  description: string
  suggestedQuestions: string[]
}
type GroupedResult = { label: string; list: IConversation[] }[]
class ChatStore {
  siderNavCollapsed = false
  botInfo: IBotInfo | null = null
  currentBotId: string = ""
  conversationID = ""
  conversationList: IConversation[] = []
  hasMore = true
  fileId = ""
  isLoading = false
  page = 1
  messageList: any[] = []
  chatId = ""
  controller: AbortController | null = null
  uploading = false
  fileArr: any[] = []
  messageContent = ""
  msgPage = 1
  msgHasMore = true
  msgLoading = false
  containerRef = createRef<BubbleListRef>()
  
  constructor() {
    makeAutoObservable(this) // 自动将字段和方法转为响应式
  }

  setBotId = (botId: string) => {
    this.currentBotId = botId
    this.getBotInfo()
  }

  getBotInfo = async () => {
    if (!this.currentBotId) return
    
    try {
      const res = await getBotInfo(this.currentBotId)
      runInAction(() => {
        if (res.code === 10000) {
          this.botInfo = {
            ...res.data.bot,
            suggestedQuestions:
              res.data.bot.onboarding_info?.suggested_questions || [],
          }
          // 重置对话列表状态
          this.page = 1
          this.hasMore = true
          this.conversationList = []
          // 加载对话历史
          this.getConversationList()
        }
      })
    } catch (error) {
      console.error("获取智能体信息失败:", error)
    }
  }

  onAddConversation = async () => {
    if (this.isLoading) {
      await this.abortChat()
    }
    runInAction(() => {
      this.msgPage = 1
      this.msgHasMore = true
      this.messageList = []
      this.messageContent = ""
      this.conversationID = ""
      this.fileArr = []
      localStorage.removeItem("conversation_id")
    })
  }

  streamingChat = (query: string) => {
    if (this.isLoading) {
      return
    }
    runInAction(() => {
      this.messageList.unshift({
        id: uid(32),
        role: "user",
        content: query,
        file_url: this.fileArr.map((item) => item.path),
      })
      this.messageList.unshift({
        id: uid(32),
        role: "assistant",
        content: "",
        loading: true,
        is_answer: 1,
      })
    })
    this.creatChat(query)
  }
  // 创建一个辅助函数来更新消息内容
  updateMessageContent = (content: string) => {
    runInAction(() => {
      if (this.messageList.length > 0 && this.messageList[0].role === "assistant") {
        // 更新消息内容，保持与ExamStore一致的逻辑
        this.messageList[0] = {
          ...this.messageList[0],
          content: content,
          loading: false,
        }
      }
    })
  }

  creatChat = async (query: string, id?: string) => {
    if (!this.currentBotId) {
      throw new Error("未选择智能体")
    }
    
    this.controller = new AbortController()
    const fileIds = this.fileArr.length
      ? this.fileArr.map((item) => item.id)
      : []
    try {
      runInAction(() => {
        this.isLoading = true
        this.fileArr = []
      })
      
      // 如果没有对话ID，先创建对话
      if (!this.conversationID) {
        const conversationRes = await createConversation({ bot_id: this.currentBotId })
        if (conversationRes.code === 10000) {
          this.conversationID = conversationRes.data.id
        }
      }
      
      const response = await startChatStream(
        {
          content: query,
          bot_id: this.currentBotId,
          conversation_id: this.conversationID,
          user_id: "default_user",
          file_ids: fileIds,
        },
        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 === "conversation.chat.created" ||
          eventName === "conversation.message.delta" ||
          eventName === "conversation.message.completed" ||
          eventName === "conversation.chat.completed" ||
          eventName === "conversation.chat.failed"
        ) {
          part.data = JSON.parse(part.data)
        }
        console.log("🔄 SSE Event received:", `"${part.event}"`, "->", `"${eventName}"`, part.data)
        runInAction(() => {
          if (eventName === "conversation.chat.created") {
            if (!this.conversationID) {
              const newConversation = {
                id: part.data.conversation_id,
                content: query,
                createDate: dayjs().valueOf(),
              }
              this.conversationList.unshift(newConversation)
              
              // 保存到本地存储
              if (this.currentBotId) {
                const savedConversations = localStorage.getItem(`conversations_${this.currentBotId}`)
                const conversations = savedConversations ? JSON.parse(savedConversations) : []
                conversations.unshift(newConversation)
                // 只保留最近50个对话
                if (conversations.length > 50) {
                  conversations.splice(50)
                }
                localStorage.setItem(`conversations_${this.currentBotId}`, JSON.stringify(conversations))
              }
            }
            this.conversationID = part.data.conversation_id
            localStorage.setItem("conversation_id", part.data.conversation_id)
          } else if (eventName === "conversation.message.delta") {
            currentContent += part.data.content
            chatId = part.data.chat_id
            console.log("delta content length:", currentContent.length)
            // 流式输出：更新内容
            this.updateMessageContent(currentContent)
            if (chatId && this.chatId !== chatId) {
              this.chatId = chatId
            }
          } else if (eventName === "conversation.message.completed") {
            // 处理答题卡消息
            if (part.data.content_type === "card") {
              console.log("🃏 ChatStore收到卡片消息，开始解析...")
              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("✅ ChatStore卡片设置完成")
                } else {
                  console.warn("⚠️ ChatStore无法解析卡片数据结构，保持原始内容")
                  // 保持原始内容但停止加载
                  this.messageList[0].loading = false
                }
              } catch (e) {
                console.error("❌ ChatStore卡片解析失败:", e, "原始数据:", part.data.content)
                // 即使解析失败，也要停止加载状态
                this.messageList[0].loading = false
              }
            } else {
              // 处理普通文本消息
              const contentType = part.data?.content_type
              const completedContent = part.data?.content || ""
              // 过滤掉不需要显示的消息类型，只显示真正的回答
              const readableTypes = ["answer", "text"]
              if (completedContent && readableTypes.includes(contentType)) {
                console.log("completed content length:", completedContent.length, "type:", contentType)
                // 完成消息
                this.updateMessageContent(completedContent)
              }
            }
            
            chatId = part.data.chat_id
            if (chatId && this.chatId !== chatId) {
              this.chatId = chatId
            }
          } else if (eventName === "conversation.chat.completed") {
            // 对话完成，停止加载状态
            this.complateChat()
          } else if (eventName === "conversation.chat.failed") {
            // 对话失败，显示错误
            console.error("Chat failed:", part.data)
            this.updateMessageContent("抱歉，请求出错了，请重试。")
            this.complateChat()
          }
        })
      }
    } catch (error) {
      console.error("Error during chat stream:", error)
      if ((error as Error).name === "CanceledError") {
        runInAction(() => {
          if (this.messageList[0] && this.messageList[0].role === "assistant") {
            // 如果内容为空，添加中断消息
            if (!this.messageList[0].content) {
              this.messageList[0].content = "会话已中断。"
            }
            this.messageList[0] = {
              ...this.messageList[0],
              loading: false,
            }
          }
        })
      } else {
        // 只有在真正的网络错误时才显示错误消息
        runInAction(() => {
          if (this.messageList[0] && this.messageList[0].role === "assistant") {
            // 如果内容为空，添加错误消息
            if (!this.messageList[0].content) {
              this.messageList[0].content = "抱歉，网络请求失败，请重试。"
            }
            this.messageList[0] = {
              ...this.messageList[0],
              loading: false,
            }
          }
        })
      }
    } finally {
      this.complateChat()
      this.controller = null
    }
  }

  setCollapsed = (collapsed: boolean) => {
    this.siderNavCollapsed = collapsed
  }

  getConversationList = async () => {
    if (!this.hasMore || !this.currentBotId) return
    
    try {
      // 调用后端API获取对话列表
      const { getConversationList: apiGetConversationList } = await import("@/server/global")
      const response = await apiGetConversationList({
        page: this.page,
        size: 20,
        modelEnum: this.getModelEnumByBotId(this.currentBotId)
      })
      
      if (response.code === 10000 && response.data) {
        runInAction(() => {
          if (this.page === 1) {
            this.conversationList = response.data.list || []
          } else {
            this.conversationList = [...this.conversationList, ...(response.data.list || [])]
          }
          this.hasMore = response.data.hasMore || false
          this.page += 1
        })
      } else {
        console.error("获取对话列表失败:", response.message)
        this.hasMore = false
      }
    } catch (error) {
      console.error("获取对话列表失败:", error)
      this.hasMore = false
    }
  }

  onClickConversation = async (conversationId: string) => {
    this.msgHasMore = true
    this.msgPage = 1
    this.getMessageList(conversationId)
  }

  getMessageList = async (conversationId?: string) => {
    // 暂时简化消息历史功能，专注于实时聊天
    // 后续可以根据需要添加消息历史功能
  }

  getGroupConversationList = (data: IConversation[]): GroupedResult => {
    const todayStr = dayjs().format("YYYY-MM-DD")
    const yesterdayStr = dayjs().subtract(1, "day").format("YYYY-MM-DD")

    const today: IConversation[] = []
    const yesterday: IConversation[] = []
    const others: Record<string, IConversation[]> = {}

    data.forEach((item) => {
      const itemDateStr = dayjs(item.createDate).format("YYYY-MM-DD")

      if (itemDateStr === todayStr) {
        today.push(item)
      } else if (itemDateStr === yesterdayStr) {
        yesterday.push(item)
      } else {
        if (!others[itemDateStr]) {
          others[itemDateStr] = []
        }
        others[itemDateStr].push(item)
      }
    })

    const result: GroupedResult = []

    if (today.length > 0) {
      result.push({ label: "今天", list: today })
    }

    if (yesterday.length > 0) {
      result.push({ label: "昨天", list: yesterday })
    }

    const sortedDates = Object.keys(others).sort(
      (a, b) => dayjs(b).unix() - dayjs(a).unix()
    )

    sortedDates.forEach((dateStr) => {
      result.push({ label: dateStr, list: others[dateStr] })
    })

    return result
  }

  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
      const assistantMessage = this.messageList[0]
      if (assistantMessage && assistantMessage.role === "assistant") {
        // 直接修改属性
        assistantMessage.loading = false
        assistantMessage.is_answer = 0
      }
    })
  }

  onDeleteConversation = async (conversationId: string) => {
    try {
      const res = await deleteConversation(conversationId)
      runInAction(() => {
        if (res.code === 10000) {
          this.conversationList = this.conversationList.filter(
            (item) => item.id !== conversationId
          )
          // 如果当前活动的 conversationID 是被删除的这个，则清空
          if (this.conversationID === conversationId) {
            this.conversationID = ""
            localStorage.removeItem("conversation_id")
            this.messageList = [] // 清空消息列表
          }
        }
      })
    } catch (error) {
      console.error("删除对话失败:", error)
    }
  }

  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)
  }

  handleUploadFile = async (file?: any) => {
    // 暂时简化文件上传功能
    if (!file) {
      this.fileArr = []
      return
    }
    // 后续可以添加文件上传到Coze的功能
    this.uploading = false
  }

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

  setMessageContent = (content: string) => {
    this.messageContent = content
  }

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