import { documentHooks } from '../../../../../../documentModel';
import {
  CHANGE_BOX_TAB_TINGWU2,
  CHOOSEAGENDA_TINGWU2,
  CHOOSETODOLIST_TINGWU2,
} from '../../../../../../pages/docASR/utils/constants';
import {
  gistQAReviewIdState,
  reviewIdState,
  toDoReIdState,
} from '../../../../../../recoils/docFile/reviewContent';
import bus from '../../../../../../utils/bus';
import { message } from '@tingwujs/design';
import { useCallback } from 'react';
import { useSetRecoilState } from 'recoil';
import { DocPlayerEvts } from '../../../businessCommon/DocMediaPlayer';
import { useDataHooks } from '../../../businessCommon/separateHooks/dataShare';

const checkVisibleParagraphBySectionTimes = (
  controller,
  time,
  endTime,
  cb,
  key,
) => {
  if (time !== undefined) {
    if (!controller.getVisibleParagraphBySectionTimes(time, endTime)) {
      message.warning({
        content: '对应原文内容已删除或被隐藏，无法回顾',
        key,
      });
    } else {
      cb();
    }
  } else {
    message.warning('自定义内容不支持回顾');
  }
};

const useReview = () => {
  const {
    documentData: { docScene, docId: transId },
  } = documentHooks.useDocumentData() || {};
  const { controller, aiAssistantController, qnaController } = useDataHooks();
  const setReviewId = useSetRecoilState(reviewIdState);
  const setToDoReId = useSetRecoilState(toDoReIdState);
  const setGistQAReviewId = useSetRecoilState(gistQAReviewIdState);

  const clearQA = useCallback(() => {
    qnaController?.setActiveQnaIndex(-1);
  }, [qnaController]);

  const checkVisibleParagraphBySids = useCallback(
    (info, sids, cb) => {
      if (info && controller && !controller.getVisibleParagraphBySids(sids)) {
        message.warning({
          content: '该问题与原文内容已无法对应，回顾失败',
          key: 'QAReview',
        });
      } else {
        cb();
      }
    },
    [controller],
  );

  const review = useCallback(
    (id: number, info: any) => {
      controller.startPlayingVoiceWord();
      aiAssistantController.setTranslateMode();
      bus.emit(CHOOSEAGENDA_TINGWU2, id);
      bus.emit(DocPlayerEvts.PLAYER_TO_TIME, info.time);
      setReviewId(id);
    },
    [controller, aiAssistantController, docScene, setReviewId],
  );

  const onAgendaReviewForFile = useCallback(
    (info) => {
      if (!controller) return;
      const { time, id, endTime } = info;
      checkVisibleParagraphBySectionTimes(
        controller,
        time,
        endTime,
        () => {
          review(id, info);
        },
        'onAgendaReviewForFile',
      );
    },
    [docScene, controller, review],
  );

  const onAgendaReviewForBox = useCallback(
    (info) => {
      bus.emit(CHANGE_BOX_TAB_TINGWU2, 'paragraphs');
      onAgendaReviewForFile(info);
    },
    [docScene, onAgendaReviewForFile],
  );

  const toTodoList = useCallback(
    (id: number, time: number) => {
      if (!controller) return;
      if (id > -1 && controller) {
        controller.startPlayingVoiceWord();
      }
      bus.emit(CHOOSETODOLIST_TINGWU2, id);
      bus.emit(DocPlayerEvts.PLAYER_TO_TIME, time);
    },
    [controller],
  );

  /**
   * 章节速览回顾
   */
  const onAgendaReviewHandler = useCallback(
    (info) => {
      clearQA();
      onAgendaReviewForFile(info);
    },
    [onAgendaReviewForBox, onAgendaReviewForFile],
  );

  /**
   * 代办回顾
   */
  const onToDoListReviewHandler = useCallback(
    (info) => {
      if (!info) return;
      if (!controller) return;
      clearQA();
      const { time, id, endTime } = info;
      checkVisibleParagraphBySectionTimes(
        controller,
        time,
        endTime,
        () => {
          setToDoReId(id);
          toTodoList(id, time);
        },
        'onToDoListReviewHandler',
      );
    },
    [controller, setToDoReId, toTodoList],
  );

  /**
   * 要点/问答回顾
   */
  const onGistQAReviewHandle = useCallback(
    (
      query: {
        isQA?: boolean;
        eTitle: any;
        info: any;
        sids: any;
        id: string;
        index: number;
      },
      taskSourceType: string,
    ) => {
      if (!qnaController) return;
      clearQA();
      if (
        controller &&
        !['TEXT_FILE', 'TEXT_FILE_REUSE'].includes(taskSourceType)
      ) {
        controller.startPlayingVoiceWord();
      }
      setTimeout(() => {
        checkVisibleParagraphBySids(query.info, query.sids, () => {
          const time = query.isQA
            ? query.info?.question?.sentenceInfoOfAnswer?.[0]?.beginTime
            : query.info?.answer?.sentenceInfoOfAnswer?.[0]?.beginTime;
          if (
            time !== undefined &&
            controller &&
            !['TEXT_FILE', 'TEXT_FILE_REUSE'].includes(taskSourceType)
          ) {
            controller.setPlayingVoiceWordByTime(time);
          }
          setGistQAReviewId?.(query.id);
          qnaController?.setActiveQnaIndex(query.index); // 更新原文区，更新下标
        });
      }, 0);
    },
    [
      transId,
      qnaController,
      controller,
      setGistQAReviewId,
      checkVisibleParagraphBySids,
    ],
  );

  /**
   * PPT 回顾
   * @param
   */
  const onPPTReviewHandler = useCallback(
    (info) => {
      clearQA();
      if (controller) {
        controller.startPlayingVoiceWord();
      }
      bus.emit(DocPlayerEvts.PLAYER_TO_TIME, info.beginTime);
      controller.setPlayingVoiceWordByTime(info.beginTime);
      aiAssistantController.setTranslateMode();
    },
    [controller, aiAssistantController],
  );

  const onAiReviewHandler = useCallback(
    (info) => {
      if (!info) return;
      if (!controller) return;
      clearQA();
      const { time, endTime } = info;

      checkVisibleParagraphBySectionTimes(
        controller,
        time,
        endTime,
        () => {
          clearQA();
          if (controller) {
            controller.startPlayingVoiceWord();
          }
          bus.emit(DocPlayerEvts.PLAYER_TO_TIME, info.time);
          controller.setPlayingVoiceWordByTime(info.time);
          aiAssistantController.setTranslateMode();
        },
        'onAiReviewHandler',
      );
    },
    [controller, aiAssistantController],
  );

  return {
    onAgendaReviewHandler,
    onToDoListReviewHandler,
    onGistQAReviewHandle,
    onPPTReviewHandler,
    onAiReviewHandler,
  };
};

/**
 * 实时回顾
 * @param controller
 * @returns
 */
const useMeetingReview = (controller: any) => {
  /**
   * 章节速览回顾
   */
  const onAgendaReviewHandler = useCallback(
    (info) => {
      const { time, id, endTime } = info;
      checkVisibleParagraphBySectionTimes(
        controller,
        time,
        endTime,
        () => {
          controller.setMeetingActiveAgendaById(id);
        },
        'onAgendaReviewForMeeting',
      );
    },
    [controller],
  );

  return {
    onAgendaReviewHandler,
  };
};

export { useReview, useMeetingReview };
