import { bluebookAiAgent } from "@/xiaolanbenlib/api/index";
import Taro from "@tarojs/taro";
import { getSimpleHeader } from "@/xiaolanbenlib/module/axios.js";
import ChunkParser, { ICompleteCallback } from "@/utils/ChunkParser";
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 getRecommendPrompt = (data: {agentId: string, sessionId: string}) => {
  return request.get<{questions: string[]}>(
    `${bluebookAiAgent}api/v1/chat/recommend/prompt`,
    { 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 TRequestStream<T> = {
  url: string,
  params: T;
  onStart: () => void;
  onReceived: (m: ICompleteCallback) => void;
  onAudioParsed:  (m: ICompleteCallback) => void;
  onFinished: (m: ICompleteCallback) => void;
  onComplete?: () => void; // 无论失败或成功都会执行
  onError: () => void;
};

export const requestStream = <T>({
  url,
  params,
  onStart,
  onReceived,
  onAudioParsed,
  onFinished,
  onComplete,
  onError,
}: TRequestStream<T>) => {
  onStart();

  let reqTask: Taro.RequestTask<any>|undefined|null = undefined;
  const jsonParser = new ChunkParser();
  jsonParser.onParseComplete((m) => {
    onFinished(m);
  });
  
  const onChunkReceived = (chunk: {data: ArrayBuffer}) => {
    // console.log('chunkReceived: ', chunk);
    const uint8Array = new Uint8Array(chunk.data);
    // console.log('uint8Array: ', uint8Array);
    var string = new TextDecoder("utf-8").decode(uint8Array);
    console.log('chunked:', string, 8888);
    jsonParser.parseChunk(string, (m) => {
      // console.log('parseChunk', m);
      onReceived(m);
    }, onAudioParsed);
  };
  const header = getSimpleHeader()
  
  try {
    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(reqTask)
        console.log("reqTask >>", reqTask, res);
       if(reqTask) {
        onComplete?.()
       }
      },
      fail: function (){
        if(reqTask) {
          onComplete?.()
         }
      }
    });

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

  const stopChunk = () => {
    reqTask?.offChunkReceived(onChunkReceived);
    reqTask?.abort();
    reqTask = null
    console.log('stop reqTask: v1/chat/completions')
  };

  return {reqTask: reqTask, stopChunk};
};



// 文本转语音
export type TTextToSpeechParams = {
  params: {
    agentId: string,
    loginId: string,
    msgUk: string,
    text: string
  };
  onStart: () => void;
  onReceived: (m: ICompleteCallback) => void;
  onAudioParsed: (m: ICompleteCallback) => void;
  onFinished: (m: ICompleteCallback) => void;
  onComplete?: () => void; // 无论失败或成功都会执行
  onError: () => void;
};

export const requestTextToSpeech = ({
  params,
  onStart,
  onReceived,
  onAudioParsed,
  onFinished,
  onComplete,
  onError,
}: TTextToSpeechParams) => {

  const url = `${bluebookAiAgent}api/v1/chat/text/speech`;
  return requestStream<{
    agentId: string,
    loginId: string,
    msgUk: string,
    text: string
  }>({
    url,
    params,
    onStart,
    onReceived,
    onAudioParsed,
    onFinished,
    onComplete,
    onError,
  })
};



// 聊天，流式返回消息
export type TTextChatParams = {
  params: TRequestBody;
  onStart: () => void;
  onReceived: (m: ICompleteCallback) => void;
  onAudioParsed: (m: ICompleteCallback) => void;
  onFinished: (m: ICompleteCallback) => void;
  onComplete?: () => void; // 无论失败或成功都会执行
  onError: () => void;
};

export const requestTextToChat = ({
  params,
  onStart,
  onReceived,
  onAudioParsed,
  onFinished,
  onComplete,
  onError,
}: TTextChatParams) => {
  const url = `${bluebookAiAgent}api/v1/chat/completions`;
  return requestStream<TRequestBody>({
    url,
    params,
    onStart,
    onReceived,
    onAudioParsed,
    onFinished,
    onComplete,
    onError,
  })
};
