import { XStream } from "@ant-design/x";


const baseUrl = process.env.NODE_ENV === "production" ? "" : "/api";
/**
 * ai请求封装
 * @param chat_query 
 * @param options 
 * @param chat_name 
 */
export const aiRequest = async (
  chat_query: string,
  options: {
    onUpdate: (data: any) => void;
    onSuccess: (data: any) => void;
    onError: (err: Error) => void;
  },
  chat_name: string
) => {
  // const abortController = new AbortController();
  // const signal = abortController.signal;
  const enterpriseCode = sessionStorage.getItem("enterpriseCode");
  const token = localStorage.getItem("token_" + enterpriseCode) || "";
  const { onUpdate, onSuccess, onError } = options;

  try {
    const response = await fetch(baseUrl + "/api/ai/chat-message", {
      method: "POST",
      body: JSON.stringify({
        app_name: 'system_design',
        chat_query,
        chat_name,
        conversation_id: undefined,
      }),
      headers: {
        Authorization: token,
        "Content-Type": "application/json",
      },
      // signal,
    });

    // 判断当前是否流式返回
    if (response.headers.get("content-type")?.includes("text/event-stream")) {
      if (response.body) {
        for await (const chunk of XStream({
          readableStream: response.body,
        })) {
          const data = JSON.parse(chunk.data);
          if (data?.event === "message") {
            onUpdate(data);
          } else if (data?.event === "message_end") {
            onSuccess(data);
          } else if (data?.event === "message_error") {
            onError(data);
          } else if (data?.event === "ping") {
            console.log(">>>> stream start <<<<");
          } else {
            console.log(">>>> stream error <<<<");
            onError(Error(data?.message || "请求失败"));
          }
        }
      }
    } else {
      // 接口异常处理
      response.json().then((res) => {
        onError?.(Error(res?.error || "请求失败"));
      });
    }
  } catch (error) {
    onError(error as Error);
  }
};