import { getDetailsData } from '@tingwujs/service';
import { SentenceInfo, Transcription } from '../docBase.type';

const transfromResult = (datas: any[]) => {
  const newResult = datas?.map((item) => {
    return {
      pi: item.paragraphId,
      ui: item.speakerId,
      sc: item.words?.map((word: any) => {
        return {
          bt: word.start,
          et: word.end,
          id: word.id,
          tc: word.text,
          si: word.sentenceId,
        };
      }),
    };
  });
  return JSON.stringify({ pg: newResult || [] });
};

const getSentencesMapForMeeting = (transcription: Transcription | null) => {
  const sentenceIdToParagraphInfo: Record<string, SentenceInfo> = {};
  if (!transcription?.paragraphs) {
    return { sentenceIdToParagraphInfo };
  }
  for (const paragraph of transcription.paragraphs) {
    const { words } = paragraph;
    if (!words || words.length === 0) continue;
    let left = 0;
    let right = 0;
    const sentenceInfoList: SentenceInfo[] = [];
    let paragraphId = paragraph.paragraphId;
    while (right < words.length) {
      const sentenceId = words[left].sentenceId;
      let beginTime = words[left].start != null ? Number(words[left].start) : 0;
      let endTime = beginTime;
      let sentenceText = '';

      while (right < words.length && words[right].sentenceId === sentenceId) {
        sentenceText += words[right].text;
        if (words[right].end != null) {
          endTime = Number(words[right].end);
        }
        right++;
      }

      const info: SentenceInfo = {
        beginTime,
        endTime,
        paragraphId: paragraphId, // 注意：这里先用原始 paragraphId
        sentenceText,
      };

      sentenceIdToParagraphInfo[String(sentenceId)] = info;
      sentenceInfoList.push(info);
      left = right;
    }
  }
  return { sentenceIdToParagraphInfo };
};

const buildResponseResult = async (result) => {
  const resultData: any = {};
  resultData.status = result.status;
  // playbackUrl
  if (result.playbackUrl) {
    resultData.playbackUrl = result.playbackUrl;
  }
  // transcription
  if (result.transcriptionPath) {
    resultData.transcription = await getDetailsData(result.transcriptionPath);
  }
  // translation
  if (result.translationsPath) {
    resultData.translations = await getDetailsData(result.translationsPath);
  }
  // textPolishPath
  if (result.textPolishPath) {
    resultData.textPolish = await getDetailsData(result.textPolishPath);
  }
  // summarization
  if (result.summarizationPath) {
    const summarization = await getDetailsData(result.summarizationPath);
    resultData.summarization = {
      ...summarization,
      paragraphSummary:
        summarization?.paragraphSummary?.replaceAll('@#', '') || '',
    };
  }
  // auto chapters
  if (result.autoChaptersPath) {
    resultData.autoChapters = await getDetailsData(result.autoChaptersPath);
  }
  // customPrompt
  if (result.customPromptPath) {
    resultData.customPrompt = await getDetailsData(result.customPromptPath);
  }
  // meetingAssistance
  if (result.meetingAssistancePath) {
    resultData.meetingAssistance = await getDetailsData(
      result.meetingAssistancePath,
    );
  }
  // ppt
  if (result.pptExtractionPath) {
    resultData.pptExtraction = await getDetailsData(result.pptExtractionPath);
  }
  if (result.errorCode) {
    resultData.errorCode = result.errorCode;
  }
  resultData.consoleInfo = {
    ...getSentencesMapForMeeting(resultData.transcription),
    // TODO 任务类型(主要区分是否是文本格式，文本格式不支持发言人区分和回溯功能)
    // taskSourceType:
  };
  return resultData;
};

// DocBae API 数据转换层
export const docBaseAPIToLocalDataTransfer = async (
  result: any,
  transId: any,
) => {
  const resultData = await buildResponseResult(result);
  const tmpResultData = {
    transId,
    errorCode: resultData.errorCode,
    status: resultData.status, // 状态 0: 成功； 1: 进行中； 2: 失败 3: 录音转写中
    transcriptionLoading:
      [1, 3].includes(resultData.status) &&
      Object.keys(resultData.transcription || {})?.length === 0,
    playVideoUrl: resultData.playbackUrl, // 回听音频url，有效期是24h
    isVideo: false,
    duration: resultData.transcription?.audioInfo?.duration || 0, // 时长
    fileSize: resultData.transcription?.audioInfo?.size || 0, // 文件大小
    playback: resultData.playbackUrl, // 音频回放地址
    audioSegments: resultData.transcription?.audioSegments, // 音频片段(跳过空白片段)
    result: transfromResult(resultData.transcription?.paragraphs), // 原文数据
    scene: 0, // 纪要查看场景: 0[个人编辑]、1[登录查看分享]、2[未登录查看分享]
    username: '', // 创作者用户名
    taskId: '',
    collectStatus: 0,
    allowSave: false,
    contentCheck: 1,
    shareContentCheck: 1, // 分享是否通过绿网检测
    dir: 0, // 目录
    tag: {
      read: 1, // 是否已读; string -> number
      showName: '智能纪要', // 展示名称
      fileType: 'meeting', // 转写文件类型
      hasPPT: 'false', // 是否有 PPT; string -> number
      hasNote: 'false', // 是否有 笔记; string -> boolean
      // 发言人
      enableSpokenToWritten: 1, // TODO发言人区分是否开启
      roleSplitNum: 0, // TODO 发言人区分数量
      roleSplitTip: 1,
      // 翻译
      lang: 'cn', // TODO 源语言，可根据实际配置修改
      translateSwitch: resultData.translations ? 1 : 0, // 翻译是否开启;
      originLanguageValue: 'cn', // 翻译源语言; "[1|2|3|4|5]", 内容盒子无; string -> number
      transTargetValue: 'en', // TODO 翻译目标语言，翻译开启时必须有值，不影响实际设置的翻译语言
      translateLanguageConf: 2,
      // AI原文改写
      textPolishSwitch: resultData.textPolish ? 1 : 0, // TODO 是否打开了AI改写标签
      textPolishLanguageConf: 2,
      translateLoading: 1,
      // 暂未用到
      client: 'web',
    },
    translatedDoc: resultData.translations,
    textPolishedDoc: resultData.textPolish,
    bigModelData: {
      summarization: resultData.summarization,
      autoChapters: resultData.autoChapters,
      meetingAssistance: resultData.meetingAssistance,
      pptExtraction: resultData.pptExtraction,
      customPrompt: resultData.customPrompt,
      consoleInfo: resultData.consoleInfo,
    },
    consoleInfo: resultData.consoleInfo,
  };
  // 返回数据
  return tmpResultData;
};

// 从 获取到的 TransModelData 里面解析 视频播放链接
const resolvePlayVideoUrl = (data: any): string => {
  let resolveVideoUrl = '';
  // 如果是阿里云盘导入的视频纪要
  const { aliyunDriveVideoPreviewPlayInfo } = data as any;
  if (data.tag.fileType === 'aliyun_drive' && aliyunDriveVideoPreviewPlayInfo) {
    // 视频清晰度优先级
    const template_ids = ['HD', 'SD', 'LD', 'FDH', 'QHD'];
    for (let i = 0; i < template_ids.length; i++) {
      const task = (
        aliyunDriveVideoPreviewPlayInfo?.live_transcoding_task_list || []
      ).find(({ template_id }: any) => template_id === template_ids[i]);

      resolveVideoUrl = task?.url;
      if (resolveVideoUrl) break;
    }
  }
  // 有提供云盘 m3u8 播放链接
  if (resolveVideoUrl !== '') {
    return resolveVideoUrl;
  }

  // 播放链接不存在时，(使用错误链接)展示播放错误；没有链接不会初始化视频播放器
  const { playVideoUrl } = data;
  return playVideoUrl || 'null_video_url';
};
