import { userStore } from "@/stores/user";
import { realApi } from "@/utils/request.ts";
import axios from "axios";

// 定义 API 响应的接口
interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
}

// 请求参数接口
interface ConversationData {
  conversationId?: string;
  userMessage?: string;
  Authorization?: string;
}

export interface Conversation {
  conversationId: string;
  userId: number;
  startedAt: string;
  endedAt: string | null;
  messageId: number;
  status: "ongoing" | "completed" | "cancelled";
  messages: string;
  messageList: Message[] | null;
}
export interface SSEData {
  // event: string;
  // conversation_id: string;
  // message_id: string;
  // created_at: number;
  // task_id: string;
  // id: string;
  // answer: string;
  // from_variable_selector: string | null;
  id:string;//消息id
  conversationId:string;//会话ID
  content:string;//内容,json格式的字符串
  role:1|2;//角色,1用户,2ai
  timestamp:string;//时间戳
  status:number;//状态,0最终状态,1分析涉及的数据表,2组织sql,3查询数据,4处理数据
}

// 消息类型
export interface Message {
  text: string;
  sender: "user" | "ai"; // 消息发送者
  sentAt: string; // ISO 8601 格式的字符串表示日期和时间
}

/**
 * 获取单个会话的所有信息
 */
export const getConversationHistory = (conversationId: string) => {
  return axios.get(import.meta.env.VITE_API_BASE_URL + "/ai/message",{
    headers:{
      Authorization:"Bearer " + userStore().token,
      clientid:"e5cd7e4891bf95d1d19206ce24a7b32e"
    },
    params:{
      conversationId
    }
  }).then(res=>{
    let list = res.data.data.data.list;
    return list;
  });
  // return realApi.get({
  //   url: "/message/getList",
  //   params: { conversationId },
  // });
};

/**
 * 文生文，发送消息
 * @param conversationId string
 * @param userMessage string
 * @param onMessage function
 * @returns Promise<string | undefined>
 */
export const sendMessage = async (
  conversationId: string,
  userMessage: string,
  onMessage: (text: string) => void,
  getId: (taskId: string, conversationId: string) => void
): Promise<string | undefined> => {
  const token = userStore().token;
  const response = await fetch(
    import.meta.env.VITE_API_BASE_URL + `/ai?conversationId=${conversationId}&content=${userMessage}`,
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Accept: "text/event-stream",
        Authorization: `Bearer ${token}`,
        clientid:'e5cd7e4891bf95d1d19206ce24a7b32e'
      },
      // body: JSON.stringify({
      //   inputs: {},
      //   query: userMessage,
      //   response_mode: "streaming",
      //   conversation_id: conversationId,
      // }),
    }
  );

  const reader = response.body?.getReader();
  const decoder = new TextDecoder();

  if (!reader) return;

  let buffer = "";
  let taskIdAssigned = false; // 标志位，确保只赋值一次

  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    console.log(buffer)
    buffer += decoder.decode(value, { stream: true });
    
    // 按行解析 SSE
    const lines = buffer.split("\n");
    buffer = lines.pop() || ""; // 保留未完整解析的部分

    for (const line of lines) {
      // onMessage(line.replace("data:", "").trim());
      if (line.startsWith("data:")) {
        let data = line.replace("data:", "").trim();
        try {
          const jsonData: SSEData = JSON.parse(data);
          onMessage(data);
          // if (jsonData.content) {
          //   onMessage(jsonData.content); // 逐步更新 UI
          // }

          // 只在第一次遇到 conversation_id 时赋值
          if (jsonData.conversationId && !taskIdAssigned) {
            taskIdAssigned = true; // 赋值后标记为已赋值
            getId(jsonData.task_id, jsonData.conversationId); // 获取 taskId 和 conversationId
          }
        } catch (error) {
          console.error("JSON 解析失败", error);
        }
      }
    }
  }
};

// 删除会话消息 (DELETE /api/conversations/delete/messages)
export const deleteMessages = (conversationId: string) => {
  return realApi.del({
    url: "/api/conversations/delete/messages?conversationId=" + conversationId,
  });
};

/**
 * 获取所有的会话
 *
 */
export const getConversationList = async (): Promise<Conversation[]> => {
  return axios.get(import.meta.env.VITE_API_BASE_URL + "/ai/conversation/history",{
    headers:{
      Authorization:"Bearer " + userStore().token,
      clientid:"e5cd7e4891bf95d1d19206ce24a7b32e"
    }
  }).then(res=>{
    let list  =res.data.data.data.list;
    return list;
  });
  // return await realApi.get({
  //   url: "/api/conversations/history/messages",
  // });
};

/**
 * 终止会话
 * @param taskId string
 */
export const abortConversation = (taskId: string) => {
  return realApi.put({
    url: "/api/conversations/stop",
    params: { taskId },
  });
};

export const updateConversationTitle = (messageId: number, message: string) => {
  return realApi.put({
    url: "/message/edit",
    data: { messageId, message },
  });
};
