import {
  docBigModelHooks,
  docTranslateHooks,
} from '../../../../../documentModel';
import { produce } from 'immer';
import { useMemo } from 'react';

/**
 * @description: 转换章节概览(原文 & 翻译)数据为播放器符合格式
 */
const useMediaAgendas = () => {
  const { currentDocBigModelData } = docBigModelHooks.useDocBigModelData();
  const { docTranslateData } = docTranslateHooks.useDocTranslateData();
  const { translateIsOpen, bigModelTranslate } = docTranslateData || {};

  // 原文摘要数据
  const mediaOriginAgendas = useMemo(() => {
    return (
      currentDocBigModelData?.chapterOverview?.map((item) => {
        const feedbackDetail =
          currentDocBigModelData?.chapterOverviewFeedback?.find(
            (feedback) => feedback.bindId === item.id,
          );
        return {
          id: item.id,
          startTime: item.time,
          endTime: item.endTime,
          title: item.title,
          content: item.content,
          ...(feedbackDetail
            ? {
                star: feedbackDetail.feedbackChoice,
                tag: JSON.parse(feedbackDetail?.feedbackInfo),
              }
            : {}),
        };
      }) || []
    );
  }, [
    currentDocBigModelData?.chapterOverview,
    currentDocBigModelData?.chapterOverviewFeedback,
  ]);
  // 翻译摘要数据
  const mediaTranslateAgendas = useMemo(() => {
    return produce(mediaOriginAgendas, (draft) =>
      draft.forEach((item) => {
        const transTitle = bigModelTranslate?.titleGenerator?.find(
          (translateItem) => translateItem.id === item.id,
        )?.value;
        const translateContent = bigModelTranslate?.agendaSummary?.find(
          (translateItem) => translateItem.id === item.id,
        )?.value;
        if (typeof transTitle === 'string') {
          item.title = transTitle;
        }
        if (typeof translateContent === 'string') {
          item.content = translateContent;
        }
      }),
    );
  }, [
    bigModelTranslate?.agendaSummary,
    bigModelTranslate?.titleGenerator,
    mediaOriginAgendas,
  ]);

  return useMemo(
    () => ({
      mediaAgendas: translateIsOpen
        ? mediaTranslateAgendas
        : mediaOriginAgendas,
    }),
    [mediaOriginAgendas, mediaTranslateAgendas, translateIsOpen],
  );
};

export { useMediaAgendas };
