/**
 *  *************************************************************
 *  ****************  大模型数据转换层   ***************************
 *  *************************************************************
 */
// *** 类型定义相关 ***
import type {
  iDocBigModelDataBase,
  iDocBigModelDataStatus,
  iPPTInfoContent,
} from '../docBigModel.type';
import { eLabInfoStatus } from '../docBigModel.type';
import type {
  iAgendaSummaryContent,
  iDocBigModelDataAPI,
  iFullSummaryContent,
  iKeywordInfoContent,
  iLabInfoStruct,
  iLabInfoStructWithPPT,
  iPPTSummaryContent,
  iPPTTitleContent,
  iQuestionAnswerLlmContent,
  iRoleSummaryContent,
  iSceneContent,
  iTodoListContent,
  tLabelInfoContent,
} from './docBigModel.services';
import { eLabInfoKey } from './docBigModel.services';

const transTopic = (topic) => {
  const data = topic?.map((child) => {
    const childrenList: any = {
      content: child.title,
      children: [],
    };
    if (child.topic && child.topic.length > 0) {
      childrenList.children = transTopic(child.topic);
    }
    return childrenList;
  });
  return data;
};

const sentenceInfoObj = (id: number, sentenceIdToParagraphInfo: any) => {
  return sentenceIdToParagraphInfo[id];
};

/**
 * @description: 标准化大模型数据
 * @param { iDocBigModelDataAPI } data 服务端返回的大模型数据
 * @return 标准化后的大模型数据
 */
const normalizeBigModelData = (data: any): any => {
  const labelInfo: any[] = [];
  const labSummaryInfo: any[] = [];
  const labPptInfo: any[] = [];
  let customPrompt: any = {};
  const allLoadFinished: boolean =
    !!data?.meetingAssistance?.keywords ||
    !!data?.summarization?.paragraphSummary ||
    !!data?.summarization?.conversationalSummary ||
    !!data?.autoChapters ||
    !!data?.summarization?.questionsAnsweringSummary ||
    !!data?.meetingAssistance?.actions ||
    !!data.pptExtraction ||
    !!data?.customPrompt ||
    !!data?.summarization?.mindMapSummary;

  // 关键词
  if (data?.meetingAssistance?.keywords) {
    labelInfo.push({
      basicInfo: {
        name: '关键词',
      },
      contents: [
        {
          type: 'tag',
          contentValues: data?.meetingAssistance?.keywords?.map(
            (item, index) => ({
              id: index + 1,
              value: item,
            }),
          ),
        },
      ],
      key: 'keyWordsExtractor',
      status: 0,
    });
  }
  // 全文概要
  if (data?.summarization?.paragraphSummary) {
    labSummaryInfo.push({
      basicInfo: {
        name: '全文摘要',
        des: '全文摘要',
      },
      contents: [
        {
          type: 'list',
          contentValues: [
            {
              id: 1,
              value: data?.summarization?.paragraphSummary,
            },
          ],
        },
      ],
      key: 'fullSummary',
      status: 0,
    });
  }
  // 发言总结
  if (data?.summarization?.conversationalSummary) {
    const { conversationalSummary } = data.summarization;
    labSummaryInfo.push({
      basicInfo: {
        name: '角色摘要',
        des: '角色摘要',
      },
      contents: [
        {
          type: 'list',
          contentValues: conversationalSummary.map((item, index) => {
            return {
              id: index + 1,
              speaker: item.speakerId,
              speakerName: item.speakerName,
              value: item.summary,
              status: 0,
            };
          }),
        },
      ],
      key: 'roleSummary',
      status: 0,
    });
  }
  // 章节速览
  if (data?.autoChapters) {
    labSummaryInfo.push({
      basicInfo: {
        name: '议程摘要',
        des: '议程摘要',
      },
      contents: [
        {
          type: 'list',
          contentValues: data?.autoChapters.map((item) => {
            return {
              id: item.id,
              time: item.start,
              endTime: item.end,
              value: item.summary,
              title: item.headline,
            };
          }),
        },
      ],
      key: 'agendaSummary',
      status: 0,
    });
  }
  // 要点回顾(问答回顾)
  if (data?.summarization?.questionsAnsweringSummary) {
    const questionsAnsweringSummary =
      data?.summarization?.questionsAnsweringSummary;
    labelInfo.push({
      basicInfo: {
        des: '问答回顾',
        name: 'qa问答',
      },
      contents: [
        {
          type: 'list',
          contentValues: questionsAnsweringSummary?.map((item, index) => ({
            id: index + 1,
            title: item.question,
            value: item.answer,
            extensions: [
              {
                sentenceIdsOfQuestion: item.sentenceIdsOfQuestion,
                sentenceIdsOfAnswer: item.sentenceIdsOfAnswer,
                sentenceInfoOfQuestion: item.sentenceIdsOfQuestion.map((id) => {
                  const obj = sentenceInfoObj(
                    id,
                    data.consoleInfo?.sentenceIdToParagraphInfo,
                  );
                  return {
                    beginTime: obj.beginTime,
                    endTime: obj.endTime,
                    paragraphId: obj.paragraphId,
                    sentenceId: id,
                  };
                }),
                sentenceInfoOfAnswer: item.sentenceIdsOfAnswer.map((id) => {
                  const obj = sentenceInfoObj(
                    id,
                    data.consoleInfo?.sentenceIdToParagraphInfo,
                  );
                  return {
                    beginTime: obj.beginTime,
                    endTime: obj.endTime,
                    paragraphId: obj.paragraphId,
                    sentenceId: id,
                  };
                }),
              },
            ],
          })),
        },
      ],
      key: 'questionAnswerLlm',
      status: 0,
    });
  }
  // 代办事项
  if (data?.meetingAssistance?.actions) {
    labelInfo.push({
      basicInfo: {
        des: '智能总结待办事项并形成清单',
        name: '智能待办事项',
      },
      contents: [
        {
          type: 'list',
          contentValues: data.meetingAssistance.actions?.map((item, index) => ({
            id: index + 1,
            time: item.start,
            endTime: item.end,
            value: item.text,
            extensions: [
              {
                sentenceId: item.sentenceId,
                ...sentenceInfoObj(
                  item.sentenceId,
                  data.consoleInfo?.sentenceIdToParagraphInfo,
                ),
              },
            ],
          })),
        },
      ],
      key: 'actionExtractor',
      status: 0,
    });
  }
  // 提取ppt
  if (
    data.pptExtraction &&
    data.pptExtraction.availableForSummary &&
    data.pptExtraction.keyFrameList
  ) {
    labPptInfo.push({
      basicInfo: {
        des: 'ppt结果',
        name: 'ppt结果',
      },
      contents: [
        {
          type: 'list',
          contentValues: data.pptExtraction.keyFrameList?.map(
            (item, index) => ({
              id: item.id,
              index: index + 1,
              time: item.start,
              pictureKey: item.fileUrl,
              pictureOssLink: item.fileUrl,
              pictureThumbnailOssLink: item.fileUrl,
              status: 0,
              pptSummary: item.summary,
            }),
          ),
        },
      ],
      key: 'pptExtractor',
      modelType: 'detail',
      hasPic: true,
      status: 0,
    });
  }
  // 思维导图
  if (data?.summarization?.mindMapSummary) {
    labelInfo.push({
      basicInfo: {
        des: '思维导图',
        name: '思维导图',
      },
      contents: [
        {
          type: 'list',
          contentValues: data.summarization.mindMapSummary.map(
            (item, index) => ({
              id: index + 1,
              json: {
                children: transTopic(item.topic),
                content: item.title,
              },
            }),
          ),
        },
      ],
      key: 'mindMapSummary',
      status: 0,
    });
  }
  // 自定义Prompt
  if (data?.customPrompt && data?.customPrompt.length > 0) {
    customPrompt = {
      truncated: data?.customPrompt[0].truncated,
      value: data?.customPrompt[0].result || '',
    };
  }

  // *** 转换关键词数据 ***
  const { keyWordInfo, status: keyWordInfoStatus } =
    transKeyWordInfo(labelInfo) || {};

  // *** 转换全文概要信息 ***
  const { fullTextSummary, status: fullTextSummaryStatus } =
    transFullTextSummary(labSummaryInfo) || {};

  // *** 转换章节速览信息 ***

  const {
    chapterOverview,
    status: chapterOverviewStatus,
    feedbackDetailList: chapterOverviewFeedback,
  } = transChapterOverview(labSummaryInfo) || {};

  // *** 转换发言人总结信息 ***
  const { speakSummary, status: speakSummaryStatus } =
    transSpeakSummary(labSummaryInfo) || {};

  // *** 转换要点回顾信息 ***
  const { keyPointsReview, status: keyPointsReviewStatus } =
    transKeyPointsReview(labelInfo) || {};
  const { todoList, status: todoListStatus } = transTodoList(labelInfo) || {};

  // *** 转换PPT标题信息 ***
  const { pptTitleInfos, status: pptTitleInfosStatus } =
    transPPTTitleInfo(labelInfo) || {};

  // *** 转换PPT概要信息 ***
  const { pptSummaryInfos, status: pptSummaryInfosStatus } =
    transPPTSummaryInfos(labPptInfo) || {};

  // *** 转换场景信息 ***
  const { bigModelSceneInfo, status: bigModelSceneInfoStatus } =
    transSceneInfo(labelInfo);

  // *** 转换脑图信息 ***
  const { bigModelXmindInfo, status: bigModelXmindInfoStatus } =
    transXmindInfo(labelInfo);

  return {
    ...(keyWordInfo ? { keyWordInfo } : {}),
    ...(fullTextSummary ? { fullTextSummary } : {}),
    ...(chapterOverview ? { chapterOverview } : {}),
    ...(chapterOverviewFeedback ? { chapterOverviewFeedback } : {}),
    ...(speakSummary ? { speakSummary } : {}),
    ...(keyPointsReview ? { keyPointsReview } : {}),
    ...(todoList ? { todoList } : {}),
    ...(pptTitleInfos ? { pptTitleInfos } : {}),
    ...(pptSummaryInfos ? { pptSummaryInfos } : {}),
    ...(bigModelSceneInfo ? { bigModelSceneInfo } : {}),
    ...(bigModelXmindInfo ? { bigModelXmindInfo } : {}),
    ...(customPrompt ? { customPrompt } : {}),
    ...(typeof keyWordInfoStatus === 'number' ? { keyWordInfoStatus } : {}),
    ...(typeof fullTextSummaryStatus === 'number'
      ? { fullTextSummaryStatus }
      : {}),
    ...(typeof chapterOverviewStatus === 'number'
      ? { chapterOverviewStatus }
      : {}),
    ...(typeof speakSummaryStatus === 'number' ? { speakSummaryStatus } : {}),
    ...(typeof keyPointsReviewStatus === 'number'
      ? { keyPointsReviewStatus }
      : {}),
    ...(typeof todoListStatus === 'number' ? { todoListStatus } : {}),
    ...(typeof pptTitleInfosStatus === 'number' ? { pptTitleInfosStatus } : {}),
    ...(typeof pptSummaryInfosStatus === 'number'
      ? { pptSummaryInfosStatus }
      : {}),
    ...(typeof bigModelSceneInfoStatus === 'number'
      ? { bigModelSceneInfoStatus }
      : {}),

    ...(typeof bigModelXmindInfoStatus === 'number'
      ? { bigModelXmindInfoStatus }
      : {}),
    allLoadFinished,
  };
};

/**
 * @description: 转换关键词信息
 */
function transKeyWordInfo(data: Array<iLabInfoStruct<tLabelInfoContent[]>>) {
  const originKeyWordInfo = data.find(
    (item) => item.key === eLabInfoKey.KEY_WORD_INFO,
  );
  const keyWordInfo = (
    originKeyWordInfo?.contents as iKeywordInfoContent[]
  )?.[0]?.contentValues;
  if (!originKeyWordInfo) return;
  return {
    keyWordInfo,
    status: originKeyWordInfo?.status,
  };
}

/**
 * @description: 转换全文概要信息
 */
function transFullTextSummary(
  data: Array<iLabInfoStruct<tLabelInfoContent[]>>,
) {
  const originFullTextSummary = data.find(
    (item) => item.key === eLabInfoKey.FULL_TEXT_SUMMARY_INFO,
  );
  const fullTextSummary = (
    originFullTextSummary?.contents as iFullSummaryContent[]
  )?.[0]?.contentValues?.[0];
  if (!originFullTextSummary) return;
  return {
    fullTextSummary,
    status: originFullTextSummary?.status,
  };
}

/**
 * @description: 转换章节速览信息
 */
function transChapterOverview(
  labSummaryInfo: Array<iLabInfoStruct<tLabelInfoContent[]>>,
) {
  const originAgendaSummary = labSummaryInfo.find(
    (item) => item.key === eLabInfoKey.AGENDA_SUMMARY_INFO,
  );

  const agendaSummary =
    (originAgendaSummary?.contents as iAgendaSummaryContent[])?.[0]
      ?.contentValues || [];

  const chapterOverview = agendaSummary.map((item) => {
    const { title, value, ...otherProps } = item;

    return {
      ...otherProps,
      title,
      content: value,
    };
  });
  if (!originAgendaSummary) return;

  const status = [originAgendaSummary.status].includes(eLabInfoStatus.LOADING)
    ? eLabInfoStatus.LOADING
    : originAgendaSummary.status;
  return {
    chapterOverview,
    status,
    feedbackDetailList: originAgendaSummary.feedbackDetailList,
  };
}

/**
 * @description: 转换发言人总结信息
 */
function transSpeakSummary(data: Array<iLabInfoStruct<tLabelInfoContent[]>>) {
  const originSpeakSummary = data.find(
    (item) => item.key === eLabInfoKey.SPEAK_SUMMARY_INFO,
  );
  const speakSummary = (
    originSpeakSummary?.contents as iRoleSummaryContent[]
  )?.[0]?.contentValues;
  if (!originSpeakSummary) return;
  return {
    speakSummary,
    status: originSpeakSummary.status,
  };
}

/**
 * @description: 转换要点回顾信息
 */
function transKeyPointsReview(
  data: Array<iLabInfoStruct<tLabelInfoContent[]>>,
) {
  const originKeyPointsReview = data.find(
    (item) => item.key === eLabInfoKey.KEY_POINT_REVIEWS_INFO,
  );
  const keyPointsReview =
    (originKeyPointsReview?.contents as iQuestionAnswerLlmContent[])?.[0]
      ?.contentValues || [];
  if (!originKeyPointsReview) return;
  return {
    keyPointsReview,
    status: originKeyPointsReview.status,
  };
}

/**
 * @description: 转换待办事项信息
 */
function transTodoList(data: Array<iLabInfoStruct<tLabelInfoContent[]>>) {
  const originTodoList = data.find(
    (item) => item.key === eLabInfoKey.TODO_LIST_INFO,
  );
  const todoList =
    (originTodoList?.contents as iTodoListContent[])?.[0]?.contentValues || [];
  if (!originTodoList) return;
  return {
    todoList,
    status: originTodoList.status,
  };
}
/**
 * @description: 转换PPT标题信息
 */
function transPPTTitleInfo(data: Array<iLabInfoStruct<tLabelInfoContent[]>>) {
  const originPPTTitle =
    data.find((item) => item.key === eLabInfoKey.PPT_TITLE_INFO) ||
    data.find((item) => item.key === eLabInfoKey.CHAPTER_OVERVIEW_INFO); // 兼容历史数据
  const pptTitleInfos =
    (originPPTTitle?.contents as iPPTTitleContent[])?.[0]?.contentValues?.map(
      (item) => {
        const { value, ...otherProps } = item;
        return {
          title: value,
          ...otherProps,
        };
      },
    ) || [];
  if (!originPPTTitle) return;
  return {
    pptTitleInfos,
    status: originPPTTitle?.status,
  };
}

/**
 * @description: 转换PPT概要信息
 */
function transPPTSummaryInfos(data: iLabInfoStructWithPPT[]) {
  const contents = (
    (
      data.find((item) => item.key === eLabInfoKey.PPT__SUMMARY_INFO)
        ?.contents as iPPTSummaryContent[]
    )?.[0]?.contentValues || []
  ).map((pptInfo): iPPTInfoContent => {
    const content: string[] | undefined =
      pptInfo?.pptSummary && !Array.isArray(pptInfo?.pptSummary)
        ? pptInfo?.pptSummary?.split('\n')
        : undefined;
    return {
      id: pptInfo.id,
      pictureKey: pptInfo.pictureKey,
      pictureOssLink: pptInfo.pictureOssLink,
      pictureThumbnailOssLink: pptInfo.pictureThumbnailOssLink,
      beginTime: pptInfo.time,
      index: pptInfo.index,
      isFailed: pptInfo.status === eLabInfoStatus.FAILED,
      isLoadingContent: pptInfo.status === eLabInfoStatus.LOADING,
      isTextTooShort: pptInfo.status === eLabInfoStatus.TEXT_TOO_SHORT,
      ...(content ? { content } : {}),
    };
  });
  const pptSummaryInfos = data?.[0]
    ? {
        modelType: data?.[0]?.modelType,
        hasPic: data?.[0]?.hasPic,
        contents,
      }
    : undefined;
  return {
    pptSummaryInfos,
    status: data?.[0]?.status,
  };
}

/**
 * @description: 转换场景信息
 */
function transSceneInfo(data: Array<iLabInfoStruct<tLabelInfoContent[]>>) {
  const bigModelSceneInfo = (
    data.find((item) => item.key === eLabInfoKey.SCENE_INFO)
      ?.contents as iSceneContent[]
  )?.[0]?.contentValues?.[0];
  return {
    bigModelSceneInfo,
    status: data?.[0]?.status,
  };
}

/**
 * @description: 转换脑图信息
 */
function transXmindInfo(data: Array<iLabInfoStruct<tLabelInfoContent[]>>) {
  const bigModelXmindInfoData = data.find(
    (item) => item.key === eLabInfoKey.MIND_MAP_SUMMARY,
  );
  const bigModelXmindInfo =
    bigModelXmindInfoData?.contents?.[0]?.contentValues?.[0];
  return {
    bigModelXmindInfo,
    status: bigModelXmindInfoData?.status, // 0完成，1处理中
  };
}

export { normalizeBigModelData };
