import {
  CUR_PAGE_AI_REVIEW,
  langValueMap,
} from '../../../../../pages/docASR/utils/config';
import bus from '../../../../../utils/bus';

import { createParagraphChangeThrottler } from '@tingwujs/util';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { AgendaSummaryBean } from '../WuLab/Agenda/types/AgendaBean';

/** 新数据结构 引用 */
import Content from './Fragmented/Content';

import { ParagraphsContainer } from './styled';

import {
  CHOOSEAGENDA_TINGWU2,
  CHOOSETODOLIST_TINGWU2,
  CURRENTTIME_TINGWU2,
} from '../../../../../pages/docASR/utils/constants';
import { getTransRefData } from '../../businessCommon/constVariable';
import { DocPlayerEvts } from '../../businessCommon/DocMediaPlayer';
import { useDataHooks } from '../../businessCommon/separateHooks/dataShare';

import {
  docBaseHooks,
  docPlayerHooks,
  docSpeakerHooks,
  docTranslateHooks,
  // docTranslateHooks,
  documentHooks,
} from '../../../../../documentModel';
import { iDocTransResult } from '../../../../../documentModel/docBase/docBase.type';

import { setParagraphsData } from '../../../../../pages/docASR/components/businessCommon/constVariable/paragraphsData';

import { iChapterOverview } from '../../../../../documentModel/docBigModel';
import { isEqual } from 'lodash-es';
import { CHANGE_AUDIO_TIME } from '../TWAudioPlayer/AudioPlayer/audioEvents';
import { useInitAgenda } from '../WuLab/Agenda/hooks/useInitAgenda.hooks';

/** 新数据 引用 */
import { useSpeakerSplitFinish } from '../../../../../pages/docASR/components/businessCommon/separateHooks';

import { useInitToDoList } from '../WuLab/ToDoList/hooks/useInitToDoList.hooks';
let startAgendaTime = { agendaStart: -1, extensionStart: -1 };

// let numAva = 0;

/**
 * 此页面跟盒子共用，新增样式，请进行模式区分
 * @param param0
 * @returns
 */

const Paragraphs = () => {
  const { docBaseData } = docBaseHooks.useDocBaseData();
  const { docPlayerData } = docPlayerHooks.useDocPlayerData();
  // const { docTranslateData } = docTranslateHooks.useDocTranslateData();
  const {
    controller,
    // qnaController,
    agendaSummaryController,
    // speakerSummaryController,
    aiAssistantController,
  } = useDataHooks();

  /** 接口数据加工抽取区域 */
  // agendas
  const {
    documentData: { docId },
  } = documentHooks.useDocumentData();

  const containerRef = React.useRef<HTMLDivElement>(null);
  const { agendaList, chapterOverviewFeedback } = useInitAgenda();

  /** 翻译相关 */
  const localSourceLanguageRef = getTransRefData('localSourceLanguageRef');

  const { docTranslateData } = docTranslateHooks.useDocTranslateData();
  const { docSpeakerData } = docSpeakerHooks.useDocSpeakerData();
  const [playIsFist, setPlayIsFist] = useState(true); // 播放器 播放态 只执行一次

  // 文本格式不能回溯
  const isTextType = useMemo(() => {
    if (
      ['TEXT_FILE', 'TEXT_FILE_REUSE'].includes(
        docBaseData?.consoleInfo?.taskSourceType,
      )
    )
      return true;
    return false;
  }, [docBaseData?.consoleInfo?.taskSourceType]);

  React.useEffect(() => {
    return () => {
      setParagraphsData('commonUseSpeakersData', []);
      setParagraphsData('speakerList', []);
    };
  }, []);

  /**
   *  *************************************************************
   *  ******************   更新原文区数据 --- 起始   *****************
   *  *************************************************************
   */
  const isHasInitParagraphData = React.useRef<boolean>(false); // 是否已经初始化原文区数据标识避免重复执行

  // 强制更新翻译数据
  const setTranslateData = React.useCallback(() => {
    if (docTranslateData) {
      if (
        docTranslateData?.originTranslate &&
        docTranslateData?.translateIsOpen &&
        docTranslateData?.translateTargetLanguage !==
          docTranslateData?.translateSourceLanguage
      ) {
        docTranslateData?.originTranslate?.pg?.map((item: any) => {
          const value = item.ts.map((_item: any) => {
            const _value: any = { ..._item };
            _value.tc = _item.txt;
            delete _value.txt;
            return _value;
          });
          controller.setTranslate(`${item.pi}`, value);
          return value;
        });
      }
    }
  }, [docTranslateData, controller]);

  /** 统一更新原文区数据公共函数 */
  const handleUpdateParagraphData = useCallback(
    (docParagraphDataOrigin: string) => {
      if (typeof docParagraphDataOrigin !== 'string') return;
      try {
        // 解析原文数据
        const docParagraphData: iDocTransResult =
          typeof docParagraphDataOrigin === 'string'
            ? JSON.parse(docParagraphDataOrigin)
            : docParagraphDataOrigin;
        if (!docParagraphData.pg) return;

        // 重复 PIT 上报
        setTimeout(() => {
          const pidArray: string[] = [];
          docParagraphData.pg.forEach((item: { pi: string }) => {
            if (pidArray.indexOf(item.pi) < 0) {
              pidArray.push(item.pi);
            }
          });
        });
        controller.setModelValue(docParagraphData);
        // 更新翻译
        setTranslateData();
      } catch (error) {
        console.error(`handleUpdateParagraphData-error:${error}`);
      }
    },
    [controller, setTranslateData, docId],
  );

  // *** 情况1: 初始化时更新原文区数据
  React.useEffect(() => {
    if (!docBaseData?.result) return;
    handleUpdateParagraphData(docBaseData?.result);
  }, [
    docBaseData?.result,
    handleUpdateParagraphData,
    docSpeakerData?.speakersData,
  ]);

  // *** 情况2: 发言人区分完成后更新原文区数据

  // 发言人区分成功后是否更新过原文区数据标识
  const isSplitFinishedHasUpdateParagraphData = React.useRef<boolean>(false);
  const cacheDocBaseData = React.useRef<string | null>();
  const [isOpenSpeakerSplitAndFinished, setIsOpenSpeakerSplitFinish] =
    useState<boolean>(false);

  useSpeakerSplitFinish(() => {
    setIsOpenSpeakerSplitFinish(true);
  });

  useEffect(() => {
    if (
      isOpenSpeakerSplitAndFinished &&
      !isEqual(cacheDocBaseData.current, docBaseData?.result) &&
      !isSplitFinishedHasUpdateParagraphData.current
    ) {
      docBaseData?.result && handleUpdateParagraphData(docBaseData?.result);
      isSplitFinishedHasUpdateParagraphData.current = true;
      cacheDocBaseData.current = docBaseData?.result;
    }
  }, [
    controller,
    docBaseData?.result,
    handleUpdateParagraphData,
    isOpenSpeakerSplitAndFinished,
    docTranslateData?.originTranslate,
  ]);

  /**
   *  *************************************************************
   *  ******************   更新原文区数据 --- 结束   *****************
   *  *************************************************************
   */

  React.useEffect(() => {
    controller.setReadonly(true);
    controller.setShowHeaderTime(!isTextType);
  }, [controller, isTextType]);

  useEffect(() => {
    if (docPlayerData) {
      const { playerIsPlaying } = docPlayerData;
      // 播放器 播放态 只执行一次
      if (playerIsPlaying && playIsFist) {
        controller.startPlayingVoiceWord();
        setPlayIsFist(false);
      }
      if (!playerIsPlaying) {
        setPlayIsFist(false);
      }
    }
  }, [docPlayerData, aiAssistantController, playIsFist, controller]);
  // 监听小悟指定回顾到对应时间
  React.useEffect(() => {
    bus.on(CUR_PAGE_AI_REVIEW, (data) => {
      aiAssistantController.setReviewTime(data.time, true); // 设置小悟回顾时间
      controller.setPlayingVoiceWordByTime(data.time);
      bus.emit(DocPlayerEvts.PLAYER_TO_TIME, data.time);
      // 抽屉盒子音频
      bus.emit(CHANGE_AUDIO_TIME, data.time / 1000, '');
      setPlayIsFist(true);
    });

    return () => {
      bus.off(CUR_PAGE_AI_REVIEW);
    };
  }, []);

  const onChooseAgenge = (id?: string) => {
    if (id && controller) {
      controller.setActiveAgendaById(`${id}`);
      // const info = agendas?.find((item) => Number(item.id) === Number(id));
      // startAgendaTime = {
      //   agendaStart: info.time,
      //   extensionStart: info.extensions?.[0]?.startTime || -1,
      // };
    } else {
      controller.clearActiveAgenda();
      // startAgendaTime = { agendaStart: -1, extensionStart: -1 };
    }
  };

  const onTimeUpdate = (currentTime: number, forceDisplay?: boolean) => {
    if (
      controller &&
      currentTime !== startAgendaTime.agendaStart &&
      currentTime !== startAgendaTime.extensionStart
    ) {
      controller.setPlayingVoiceWordByTime(currentTime, forceDisplay);
      // controller.getActiveAgenda();
      startAgendaTime = { agendaStart: -1, extensionStart: -1 };
    }
  };

  const onChooseTodoList = (id?: string) => {
    if (id && controller) {
      controller.setActiveTodoListById(`${id}`);
    } else {
      controller.clearActiveTodoList();
    }
  };

  // 处理 AI 助理点击回顾到指定时间
  React.useEffect(() => {
    if (controller) {
      // 数据订阅
      bus.on(CURRENTTIME_TINGWU2, onTimeUpdate);
      bus.on(CHOOSEAGENDA_TINGWU2, onChooseAgenge);
    }
    const initAgendas = () => {
      if (
        controller &&
        controller.getPids().length > 0 &&
        agendaList &&
        agendaList.length
      ) {
        controller.setAgendasFromJSON(agendaList as any[]);
      }
    };
    initAgendas();
    return () => {
      bus.off(CURRENTTIME_TINGWU2, onTimeUpdate);
      bus.off(CHOOSEAGENDA_TINGWU2, onChooseAgenge);
      controller.on('modelValueChange', () => {
        initAgendas();
      });
    };
  }, [agendaList, controller]);

  const { todoList } = useInitToDoList();

  React.useEffect(() => {
    if (controller) {
      // 数据订阅
      bus.on(CHOOSETODOLIST_TINGWU2, onChooseTodoList);
    }
    const initAgendas = () => {
      if (
        controller &&
        controller.getPids().length > 0 &&
        todoList &&
        todoList.length
      ) {
        controller.setTodoListsFromJSON(todoList as any[]);
      }
    };
    initAgendas();

    return () => {
      bus.off(CHOOSETODOLIST_TINGWU2, onChooseTodoList);
      controller.on('modelValueChange', () => {
        initAgendas();
      });
    };
  }, [todoList, controller]);

  React.useEffect(() => {
    return () => {
      startAgendaTime = { agendaStart: -1, extensionStart: -1 };
    };
  }, []);

  React.useEffect(() => {
    // 判断离线打开才会翻译
    if (docTranslateData?.translateIsOpen) {
      return createParagraphChangeThrottler(controller, (store) => {
        const firstPid = Object.keys(store.toAdd)[0];
        const firstParagraph: any = firstPid && controller.getPByPid(firstPid);
        const condition =
          firstParagraph?.sc?.length === 1 && firstParagraph.sc[0].tc === '';

        // 标记不重新翻译
        const update = Object.keys(store.toUpdate).reduce((_res, pid) => {
          if (store.toUpdateWithoutTranslate?.[pid]) return _res;
          return { ..._res, [pid]: true };
        }, {});
        return new Promise((resolve) => {
          setTimeout(resolve, 1000);
        });
      });
    }
  }, [
    docTranslateData?.originTranslate,
    docTranslateData?.translateTargetLanguage,
    docTranslateData?.translateIsOpen,
    langValueMap[localSourceLanguageRef],
  ]);

  React.useEffect(() => {
    if (controller) {
      // 原文区引起的音视频时间变化
      return controller.startListenSelectWord((words) => {
        if (words && words.length > 0 && words[0].beginTime !== undefined) {
          // 非抽屉盒子音视频
          bus.emit(DocPlayerEvts.PLAYER_TO_TIME, words[0].beginTime, true);
          // 抽屉盒子音频
          bus.emit(CHANGE_AUDIO_TIME, words[0].beginTime / 1000, '');
        }
      });
    }
  }, [aiAssistantController, controller]);

  const getAgendaSummer = useCallback(
    (data: { agendas: iChapterOverview[]; feedbackDetailList?: any[] }) => {
      const _agendasSummary: AgendaSummaryBean[] = data.agendas.map((item) => {
        let feedbackDetail;
        if (data.feedbackDetailList) {
          feedbackDetail = data.feedbackDetailList.find(
            (i) => i.bindId === item.id,
          );
        }
        const _item: AgendaSummaryBean = {
          id: `${item.id}`,
          agendaHeading: item.title,
          beginTime: item.time,
          endTime: item.endTime,
          content: item.content,
          star: feedbackDetail ? feedbackDetail.feedbackChoice : undefined,
          tag: feedbackDetail
            ? JSON.parse(feedbackDetail.feedbackInfo)
            : undefined,
        };
        return _item;
      });
      return _agendasSummary;
    },
    [],
  );

  useEffect(() => {
    if (!agendaList?.length) return;
    if (!agendaSummaryController) return;

    const summaries = getAgendaSummer({
      agendas: agendaList,
      feedbackDetailList: chapterOverviewFeedback,
    });
    agendaSummaryController.setSummaries(summaries);
  }, [agendaList, agendaSummaryController, chapterOverviewFeedback]);

  const paragraphs = (
    <ParagraphsContainer
      ref={containerRef}
      id="paragraphs-container"
      data-e2e-test-id="trans_paragraphs_div"
    >
      <Content />
    </ParagraphsContainer>
  );

  /** 普通原文区 */
  return <>{paragraphs}</>;
};

export default Paragraphs;
