import { bluebookAiAgent } from "@/xiaolanbenlib/api/index";
import Taro from "@tarojs/taro";
import { getSimpleHeader } from "@/xiaolanbenlib/module/axios.js";
import JsonChunkParser from "@/utils/jsonChunkParser";
import request from "@/xiaolanbenlib/module/axios.js";
import type { TMessageHistories, TRequestBody, TAppendMessages } from "@/types/bot";
import { TextDecoder } from "text-encoding-shim";
import { getTempFileContent } from "@/utils";



// 获取与指定智能体的历史会话记录--按智能体维度倒序返回
export type TGetMessageHistoriesParams = {
  agentId: string;
  startId?: string; // 起始ID, 如果未传入则获取最新的N条
  pageSize: number;
};
export const getMessageHistories = (data: TGetMessageHistoriesParams) => {
  return request.get<TMessageHistories>(
    `${bluebookAiAgent}api/v1/chat/messages`,
    { params: data }
  );
};

// 保存消息--追加覆盖保存模式


export const appendMessages = (data: TAppendMessages) => {
  return request.post(`${bluebookAiAgent}api/v1/chat/messages/append`, data)
}


// 消息差评或取消差评
type TDislikeMessage = {
  agentId: string,
  dislikeReason: string,
  isDislike: boolean,
  msgUk: string
  loginId: string
}
export const dislikeMessage = (data: TDislikeMessage) => {
  return request.put(`${bluebookAiAgent}api/v1/chat/messages/dislike`, data)
}

// 消息点赞或取消点赞
type TLikeMessage = {
  agentId: string,
  isLike: boolean,
  msgUk: string
  loginId: string
}
export const likeMessage = (data: TLikeMessage) => {
  return request.put(`${bluebookAiAgent}api/v1/chat/messages/like`, data)
}


export const speechToText = async (agentId: string, tempFilePath: string) => {
  const content = await getTempFileContent<string>(tempFilePath, 'base64')
  return request.post<{
    emotions: string[],
    text: string
  }>(`${bluebookAiAgent}api/v1/chat/speech/text`, {
    agentId,
    speechBase64: content,
  })
}





// 文本聊天，流式返回消息

export type TTextChatParams = {
  params: TRequestBody;
  onStart: () => void;
  onReceived: (m: { content: string; reasoningContent: string }) => void;
  onFinished: () => void;
  onError: () => void;
};

export const textChat = ({
  params,
  onStart,
  onReceived,
  onFinished,
  onError,
}: TTextChatParams) => {
  onStart();

  let reqTask: Taro.RequestTask<any>;
  const jsonParser = new JsonChunkParser();
  jsonParser.onParseComplete((m) => {
    onFinished();
  });
  const onChunkReceived = (chunk: any) => {
    console.log('chunkReceived: ', chunk);
    const uint8Array = new Uint8Array(chunk.data);
    console.log('uint8Array: ', uint8Array);
    var string = new TextDecoder("utf-8").decode(uint8Array);
    console.log(string);
    jsonParser.parseChunk(string, (m) => {
      console.log('parseChunk', m);
      onReceived(m);
    });
  };
  const header = getSimpleHeader()
  
  try {
    const url = `${bluebookAiAgent}api/v1/chat/completions`;
    reqTask = Taro.request({
      url: url,
      data: params,
      enableChunked: true,
      method: "POST",
      header: {
        ...header
      },
      responseType: "arraybuffer",
      success: function (res) {
        console.log("服务端响应 >>", res);
      },
      complete: function(res) {
        console.log(res,4444)
      }
    });

    // reqTask.
    reqTask.onChunkReceived(onChunkReceived);
  } catch (e) {
    onError();
  }

  const stopChunk = () => {
    reqTask.offChunkReceived(onChunkReceived);
  };

  return stopChunk;
};
