import React, { useCallback, useEffect, useMemo, useRef } from 'react';
// *** 三方包相关 ***
import { Exception, message } from '@tingwujs/design';
import { useRecoilState, useRecoilValue } from 'recoil';
import useForceUpdate from 'use-force-update';
// *** 二方包相关 ***
import { myLocalStorage } from '@tingwujs/common';
import { Icon } from '@tingwujs/meeting-icon';
import { SummaryAnimation, SummaryErrorText } from '@tingwujs/sphere';
// *** Model 层数据引用相关 ***
import {
  docBaseHooks,
  docBigModelHooks,
  docSpeakerHooks,
  docTagHooks,
  documentHooks,
} from '../../../../../../documentModel';
import { eLabInfoStatus } from '../../../../../../documentModel/docBigModel';
// *** Recoil 层数据引用相关 ***
import { currentBigModelTabState } from '../../../../../../recoils/docFile/bigModuleRelated';
import { gistQAReviewIdState } from '../../../../../../recoils/docFile/reviewContent';

import { videoHState } from '../../../../../../recoils/docFile/player';
import {
  oneHour,
  ON_PPT_VISIBLE,
  OPEN_PTT_ALLS,
  SHOWBIGMODEL_ERROR_MESSAGE,
  tabsLangs,
} from '../../../../../../pages/docASR/utils/config';
// *** 工具相关 ***
import bus from '../../../../../../utils/bus';
import { headerH } from '../BigModel/utils/const';
import { useDataHooks } from '../../../businessCommon/separateHooks/dataShare';
// *** 页面业务组件
import AdendaTimeItemInput from '../Agenda/AgendaTimeItemInput';
import { TitleTabs } from '../BigModel/components/TitleTabs';
import PPTSummaryMap from '../PPTSummaryCard/PPTSummaryMap';
import GistSummary from '../QA/GistQASummaryCard/GistSummary';
import QASummary from '../QA/GistQASummaryCard/QASummary';
import { SpeakerSummaryList } from '../speakerSummaryList';
import { ToDoList as ToDoListCom } from '../ToDoList';
// *** 页面业务 hooks ***
import { useInitAgenda } from '../Agenda/hooks/useInitAgenda.hooks';
import { useInitPPT } from '../PPTSummaryCard/hooks/useInitPPT.hooks';
import { useInitQA } from '../QA/hooks/useInitQA.hooks';
import { useInitToDoList } from '../ToDoList/hooks/useInitToDoList.hooks';
// *** 类型定义文件相关 ***
import { FileMessageKey } from '../../../../../../pages/docASR/utils/constants';
import { eEventTitle, Tabs } from '../BigModel';

// *** 样式文件相关 ***
import {
  AgendaContainer,
  SwitchAnimationContainer,
  WulabContainer,
} from '../Agenda/styled';
import { dataAutologs } from '../../../../../../pages/docASR/utils/dataAutologs';
import {
  HeadingExtraContainer,
  HeadingOperates,
  Title,
  TitleHeading,
  TitleWrapper,
} from '../BigModel/style';
import DirtyMeetingSummaryCard from '../Fragmented/DirtyMeetingSummaryCard';
import { useReview } from '../hooks/useReview.hook';

const pptInitTimer: NodeJS.Timeout | null = null;
let agendaMesTimer: NodeJS.Timeout | null = null;
const boxTabsTimer: NodeJS.Timeout | null = null;

enum eTheme {
  QA = 'QA',
  GIST = 'GIST',
}

const BigModelTabs = () => {
  const forceUpdate = useForceUpdate();
  const { agendaSummaryController } = useDataHooks();
  const { documentData } = documentHooks.useDocumentData();
  const { docId } = documentData || {};
  const { docSpeakerData } = docSpeakerHooks.useDocSpeakerData();
  const { currentDocBigModelData } = docBigModelHooks.useDocBigModelData();
  const { pptSummaryInfos, speakSummaryStatus } = currentDocBigModelData || {};
  const { docTagData } = docTagHooks.useDocTagData();
  const { docBaseData } = docBaseHooks.useDocBaseData() as any;
  const { shortMode, isVideo, tag } = docBaseData || {};
  const { lang } = tag || {};

  const pptMessageVisibleRef = useRef<number | undefined>();
  const pptDotVisibleRef = useRef<number | undefined>();
  useEffect(() => {
    if (!docTagData) return;
    if (pptMessageVisibleRef.current !== 0) {
      pptMessageVisibleRef.current =
        docTagData.pptMessageVisible !== undefined
          ? docTagData.pptMessageVisible
          : 1;
    }
    if (pptDotVisibleRef.current !== 0) {
      pptDotVisibleRef.current =
        docTagData.pptDotVisible !== undefined ? docTagData.pptDotVisible : 1;
    }
  }, [docTagData, pptMessageVisibleRef, pptDotVisibleRef]);

  // 当前选中 TAB
  const [currentTab, _setCurrentTab] = useRecoilState(currentBigModelTabState);
  const [gistQAReviewId] = useRecoilState(gistQAReviewIdState);
  // 章节速览

  const agendaDotVisible = !myLocalStorage.isHasId(
    'showedAgendaSummaryExpanderV2',
    String(docId),
  );

  const videoH = useRecoilValue(videoHState);
  const extraHeight = headerH + (isVideo > 0 ? videoH : 0);

  const { todoList } = useInitToDoList();
  const { agendaSummaryStatus, agendaList } = useInitAgenda();
  const { QAList } = useInitQA();
  const { pptAgendas, pptsMap, pptlist } = useInitPPT(true);

  const containerRef = useRef<HTMLDivElement>(null);

  const tabInitCurrentIndexRef = useRef<number | undefined>(5);

  const tabs = useMemo(() => {
    const _tabs: Array<{
      label: any;
      value: Tabs;
      dot?: any;
      dataAutolog?: string;
    }> = [];
    if (
      lang &&
      tabsLangs.FullSummary.includes(lang) &&
      currentDocBigModelData?.fullTextSummaryStatus !== undefined &&
      currentDocBigModelData?.fullTextSummaryStatus !== eLabInfoStatus.LOADING
    ) {
      _tabs.push({
        label: '全文概要',
        value: Tabs.Summary,
        dataAutolog: dataAutologs.summarization,
      });
      if (
        tabInitCurrentIndexRef.current === undefined ||
        tabInitCurrentIndexRef.current > 0
      ) {
        tabInitCurrentIndexRef.current = 0;
      }
    }
    if (
      tabsLangs[Tabs.Agenda].includes(lang) &&
      currentDocBigModelData?.chapterOverviewStatus !==
        eLabInfoStatus.LOADING &&
      currentDocBigModelData?.chapterOverviewStatus !== undefined
    ) {
      _tabs.push({
        label: '章节速览',
        value: Tabs.Agenda,
        dataAutolog: dataAutologs.agenda,
      });
      if (
        tabInitCurrentIndexRef.current === undefined ||
        tabInitCurrentIndexRef.current > 1
      ) {
        tabInitCurrentIndexRef.current = 1;
      }
    }
    if (
      tabsLangs[Tabs.SpeakerSummary].includes(lang) &&
      currentDocBigModelData?.speakSummaryStatus !== undefined &&
      currentDocBigModelData?.speakSummaryStatus !== undefined &&
      currentDocBigModelData?.speakSummaryStatus !== eLabInfoStatus.LOADING
    ) {
      _tabs.push({
        label: '发言总结',
        value: Tabs.SpeakerSummary,
        dataAutolog: dataAutologs.speakerSummary,
      });
      if (
        tabInitCurrentIndexRef.current === undefined ||
        tabInitCurrentIndexRef.current > 2
      ) {
        tabInitCurrentIndexRef.current = 2;
      }
    }

    if (
      currentDocBigModelData?.keyPointsReviewStatus !==
        eLabInfoStatus.LOADING &&
      currentDocBigModelData?.keyPointsReviewStatus !== undefined &&
      tabsLangs[Tabs.QNAReview].includes(lang)
    ) {
      _tabs.push({
        label: '要点回顾',
        value: Tabs.Highlights,
        dataAutolog: dataAutologs.questions,
      });
      if (
        tabInitCurrentIndexRef.current === undefined ||
        tabInitCurrentIndexRef.current > 3
      ) {
        tabInitCurrentIndexRef.current = 3;
      }
    }

    if (
      tabsLangs[Tabs.ToDoList].includes(lang) &&
      todoList &&
      todoList.length > 0
    ) {
      _tabs.push({
        label: '待办事项',
        value: Tabs.ToDoList,
        dataAutolog: dataAutologs.todoList,
      });
      if (
        tabInitCurrentIndexRef.current === undefined ||
        tabInitCurrentIndexRef.current > 4
      ) {
        tabInitCurrentIndexRef.current = 4;
      }
    }

    if (
      pptSummaryInfos &&
      pptSummaryInfos.hasPic &&
      tabsLangs[Tabs.PPT].includes(lang)
    ) {
      _tabs.push({
        label: (
          <span>
            提取
            <span className="ppt_icon">PPT</span>
          </span>
        ),
        value: Tabs.PPT,
        dot: true,
        dataAutolog: dataAutologs.ppt,
      });
      if (tabInitCurrentIndexRef.current === undefined) {
        tabInitCurrentIndexRef.current = 5;
      }
    }
    return _tabs;
  }, [
    lang,
    currentDocBigModelData?.fullTextSummaryStatus,
    currentDocBigModelData?.chapterOverviewStatus,
    currentDocBigModelData?.speakSummaryStatus,
    currentDocBigModelData?.keyPointsReviewStatus,
    todoList,
    pptSummaryInfos,
  ]);

  const setCurrentTab = useCallback(
    (e) => {
      _setCurrentTab(e);
    },
    [_setCurrentTab],
  );

  // 本地存储的内容
  const qaLocalStorage =
    localStorage.getItem('TINGWU-SDK-SHOWED-QA-GIST-SUMMARY-EXPANDER-V2') || '';
  // 问答|要点 回顾部分是否点击过
  const haveClicked = useMemo(() => {
    return qaLocalStorage.split(',').includes(docId as string);
  }, [docId, qaLocalStorage]);

  // 更新问答|要点回顾的 状态
  const changeGistQAUnfold = useCallback(
    (unfold) => {
      const eTitle =
        currentTab === Tabs.QNAReview
          ? eEventTitle.REVIEW_QNA_REVIEW_TAB
          : eEventTitle.REVIEW_HIGHLIGHTS_TAB;
      if (!haveClicked) {
        // 未点击过
        const valArr = qaLocalStorage ? qaLocalStorage.split(',') : [];
        valArr.push(docId as string);
        localStorage.setItem(
          'TINGWU-SDK-SHOWED-QA-GIST-SUMMARY-EXPANDER-V2',
          valArr.join(','),
        );
      }
    },
    [currentTab, docId, qaLocalStorage, haveClicked],
  );

  const changePPTInitMessageVisibel = useCallback(() => {
    pptDotVisibleRef.current = 0;
    setpptDotVisible(false);
    message.destroy(FileMessageKey.TINGWU2_PPT_INIT);
    if (!docId) return '';
  }, [docId]);

  const scrollIntoViewForTop = useCallback(() => {
    // 滚动到顶部
    const bigModelTabsBeforeDom = document.getElementById(
      'tingwu2_bigModelTabsBeforeRef',
    );
    const bigModelDom = document.getElementById(
      'tingwu2_editorContentBottomLeftContent',
    );
    const bigModelScrollDom = document.getElementById(
      'tingwu_paragraphs_scrollContainer',
    );

    const bigModelTopDom = document.getElementById('tingwu2-bigmodel-top');

    if (
      bigModelTabsBeforeDom &&
      bigModelDom &&
      bigModelScrollDom &&
      bigModelTopDom
    ) {
      const { top } = bigModelTabsBeforeDom.getBoundingClientRect();
      const { top: oTop } = bigModelDom.getBoundingClientRect();
      const { top: sTop } = bigModelTopDom.getBoundingClientRect();
      const docInner = document.getElementById(
        'tingwu_paragraphs_scrollContainerInner',
      );
      if (top < oTop && docInner) {
        const observer = new ResizeObserver(() => {
          bigModelScrollDom.scrollTo({
            top: top - sTop,
          });
          observer.disconnect();
        });
        observer.observe(docInner);
      }
    }
  }, []);

  React.useEffect(() => {
    return () => {
      message.destroy(FileMessageKey.TINGWU2_PPT_INIT);
    };
  }, []);

  useEffect(() => {
    return () => {
      pptInitTimer && clearTimeout(pptInitTimer);
    };
  }, []);

  React.useEffect(() => {
    if (lang === 'yue') {
      agendaMesTimer && clearTimeout(agendaMesTimer);
      return;
    }
    if (
      agendaSummaryStatus !== undefined &&
      agendaList?.length &&
      agendaSummaryStatus !== eLabInfoStatus.LOADING
    ) {
      const isShowed = myLocalStorage.isHasId(
        'showedNoAgendaSummaryTip',
        String(docId as string),
      );
      if (!agendaList.find((i) => i.content) && !isShowed) {
        agendaMesTimer && clearTimeout(agendaMesTimer);
        agendaMesTimer = setTimeout(() => {
          myLocalStorage.setItemById(
            'showedNoAgendaSummaryTip',
            String(docId as string),
          );
          message.warning('没有章节速览总结内容哦');
        }, 300);
      } else {
        agendaMesTimer && clearTimeout(agendaMesTimer);
      }
    }
  }, [agendaList, agendaSummaryStatus, docId, lang]);

  React.useEffect(() => {
    return agendaSummaryController?.onStateChange((event) => {
      if (event.key === 'isThreeUnitTime') {
        forceUpdate();
      }
    });
  }, [agendaSummaryController, forceUpdate]);

  const onOpenPPT = useCallback(
    (screenshotTime?: number) => {
      if (!tabRef.current) return '';
      tabInitCurrentIndexRef.current = -1;
      setCurrentTab(Tabs.PPT);
      changePPTInitMessageVisibel();
      if (screenshotTime !== undefined) {
        scrollIntoViewPPT(screenshotTime);
        message.destroy(FileMessageKey.TINGWU2_SCREENSHOT_PPT_LOADING);
        message.success({
          content: '截图成功，已插入PPT中',
          key: 'add_ppt_success',
        });
        // scrollIntoViewForTop();
      } else {
        // 滚动到顶部
        scrollIntoViewForTop();
      }
    },
    [
      changePPTInitMessageVisibel,
      docId,
      tabs,
      scrollIntoViewForTop,
      setCurrentTab,
      tabInitCurrentIndexRef,
    ],
  );

  useEffect(() => {
    bus.on(OPEN_PTT_ALLS, onOpenPPT);
    return () => {
      bus.off(OPEN_PTT_ALLS, onOpenPPT);
    };
  }, [onOpenPPT]);

  const onPPTVisible = useCallback(() => {
    message.success({
      icon: <span />,
      duration: 10,
      content: (
        <span
          style={{
            fontSize: 14,
            color: 'rgba(39,38,77,0.65)',
            letterSpacing: 0,
            lineHeight: '24px',
            display: 'flex',
            alignItems: 'center',
          }}
        >
          <Icon
            style={{ color: '#615ced', marginRight: 8 }}
            type={'tingwu-AI'}
            size={20}
          />
          PPT提取成功，
          <span
            style={{
              color: '#615ced',
              cursor: 'pointer',
            }}
            onClick={() => {
              pptDotVisibleRef.current = 0;
              onOpenPPT();
            }}
          >
            点击查看
          </span>
        </span>
      ),
      key: FileMessageKey.TINGWU2_PPT_INIT,
    });
  }, [onOpenPPT]);

  useEffect(() => {
    if (
      pptMessageVisibleRef.current === 1 &&
      pptSummaryInfos &&
      pptSummaryInfos.hasPic &&
      tabsLangs[Tabs.PPT].includes(lang) &&
      tabs.find((i) => i.value === Tabs.PPT)
    ) {
      pptInitTimer && clearTimeout(pptInitTimer);
    }
  }, [pptMessageVisibleRef, docId, tabs, pptSummaryInfos, lang]);

  const handleSetCurrentTab = () => {
    if (
      tabInitCurrentIndexRef.current !== undefined &&
      tabInitCurrentIndexRef.current > -1
    ) {
      switch (tabInitCurrentIndexRef.current) {
        case 1:
          setCurrentTab(Tabs.Agenda);
          tabInitCurrentIndexRef.current = -1;
          break;
        case 2:
          setCurrentTab(Tabs.SpeakerSummary);
          break;
        case 3:
          setCurrentTab(Tabs.Highlights);
          break;
        case 4:
          setCurrentTab(Tabs.ToDoList);
          break;
        case 5:
          setCurrentTab(Tabs.PPT);
          if (lang === 'ja') {
            tabInitCurrentIndexRef.current = -1;
          }
          break;
        case 0:
          setCurrentTab(Tabs.Summary);
          break;
        default:
          break;
      }
    }
  };

  useEffect(() => {
    handleSetCurrentTab();
  }, [tabs]);

  const tabRef: any = React.useRef();
  const [pptdotVisible, setpptDotVisible] = React.useState(false);

  React.useEffect(() => {
    if (Number(pptDotVisibleRef.current) !== 0 && pptlist?.length) {
      setpptDotVisible(true);
    } else {
      setpptDotVisible(false);
    }
  }, [pptDotVisibleRef.current, pptlist]);

  React.useEffect(() => {
    bus.on(ON_PPT_VISIBLE, onPPTVisible);
    return () => {
      bus.on(ON_PPT_VISIBLE, onPPTVisible);
    };
  }, [onPPTVisible]);

  const scrollIntoViewPPTRef: any = React.useRef(-1);
  const scrollIntoViewPPT = (screenshotTime?: number) => {
    scrollIntoViewPPTRef.current = screenshotTime;
  };

  const titleHeadingRef: any = useRef();

  const scrollContainerRef: any = useRef();
  useEffect(() => {
    scrollContainerRef.current = document.getElementById(
      'tingwu_paragraphs_scrollContainer',
    );
  }, [scrollContainerRef]);

  const onClickTab = (tabId) => {
    tabInitCurrentIndexRef.current = -1;
    if (tabId === Tabs.PPT) {
      changePPTInitMessageVisibel();
    }
    setCurrentTab(tabId);
  };

  const { onAgendaReviewHandler } = useReview();

  // 获取章节速览内容
  const getRenderContentForAgendaContent = useCallback(() => {
    const isAgendaReady =
      agendaSummaryStatus !== undefined &&
      agendaSummaryStatus !== eLabInfoStatus.LOADING;
    if (
      agendaSummaryStatus === eLabInfoStatus.TEXT_TOO_SHORT &&
      agendaList &&
      agendaList.length === 0
    ) {
      return (
        <div>
          <SummaryErrorText text={'抱歉，全文内容太短了，无总结内容哦'} />
        </div>
      );
    } else if (
      agendaSummaryStatus === eLabInfoStatus.FAILED &&
      agendaList &&
      agendaList.length === 0
    ) {
      return (
        <div>
          <SummaryErrorText isFail />
        </div>
      );
    } else {
      let isOverOneHour = false;
      if (agendaList && agendaList.length > 0) {
        agendaList.some((agenda: any) => {
          if (Number(agenda.time) >= oneHour) {
            isOverOneHour = true;
            return true;
          }
          return false;
        });
      }
      return (
        <>
          {agendaList && agendaList.length > 0 && (docId as string)
            ? agendaList.map((item, index) => {
                return (
                  <AdendaTimeItemInput
                    reView={onAgendaReviewHandler}
                    info={item}
                    lang={lang}
                    index={index}
                    key={item.id}
                    lastIndex={index === agendaList.length - 1}
                    alls
                    count={agendaList.length}
                    transId={docId as string}
                    isOverOneHour={isOverOneHour}
                  />
                );
              })
            : null}
          {agendaList && agendaList.length === 0 && isAgendaReady ? (
            <div>
              <SummaryErrorText isEmpty />
            </div>
          ) : null}
        </>
      );
    }
  }, [agendaSummaryStatus, agendaList, lang, docId, onAgendaReviewHandler]);

  const isLoadingSplitSpeaker = useMemo(
    () =>
      speakSummaryStatus === eLabInfoStatus.LOADING ||
      docSpeakerData?.speakersSplitIsLoading,
    [docSpeakerData?.speakersSplitIsLoading, speakSummaryStatus],
  );
  const getSpeakerSummaryRrrorText = useCallback(() => {
    const isFail =
      currentDocBigModelData?.speakSummaryStatus === eLabInfoStatus.FAILED;
    const isTextToolShort =
      currentDocBigModelData?.speakSummaryStatus ===
      eLabInfoStatus.TEXT_TOO_SHORT;
    if (isTextToolShort) {
      return '抱歉，全文内容太短了，无总结内容哦';
    }
    // 这个文案组件里面带了
    if (isFail) {
      return '';
    }
    return (currentDocBigModelData?.speakSummary?.length || 0) > 0
      ? ''
      : '没有总结内容哦';
  }, [
    currentDocBigModelData?.speakSummaryStatus,
    currentDocBigModelData?.speakSummary?.length,
  ]);

  // 发言总结内容
  const renderSpeakerSummary = useMemo(() => {
    const isFail =
      currentDocBigModelData?.speakSummaryStatus === eLabInfoStatus.FAILED;
    if (
      [
        eLabInfoStatus.FINISH,
        eLabInfoStatus.FAILED,
        eLabInfoStatus.TEXT_TOO_SHORT,
      ].includes(
        currentDocBigModelData?.speakSummaryStatus as eLabInfoStatus,
      ) &&
      !isLoadingSplitSpeaker
    ) {
      return (
        <div
          id="speakerSummary"
          // style={isTextToolShort ? { marginTop: 20 } : {}}
        >
          <SpeakerSummaryList
            maxShowCount={1}
            isFail={isFail}
            short={false}
            isSpeakerSummaryExpand
            errorText={getSpeakerSummaryRrrorText()}
          />
        </div>
      );
    }
    return null;
  }, [
    currentDocBigModelData?.speakSummaryStatus,
    getSpeakerSummaryRrrorText,
    isLoadingSplitSpeaker,
    docSpeakerData?.speakersSplitType,
    shortMode,
  ]);

  // PPT内容
  const getRenderContentForPPTSummary = useCallback(() => {
    return (
      <div id="tignwu2-PPTcontainer" className="tignwu2-PPTcontainer">
        {pptlist.length === 0 ? (
          <div
            style={{
              fontWeight: 400,
              fontSize: 12,
              color: 'var(--Text_Caption)',
              userSelect: 'none',
            }}
          >
            没有PPT哦
          </div>
        ) : (
          <PPTSummaryMap
            pptAgendas={pptAgendas}
            pptsMap={pptsMap}
            alls
            pptlist={pptlist}
            shortMode={shortMode}
            transId={docId as string}
            scrollIntoViewPPTRef={scrollIntoViewPPTRef}
          />
        )}
      </div>
    );
  }, [pptlist, pptAgendas, pptsMap, shortMode, docId]);

  /**
   * 渲染 要点 | 问答回顾 内容
   */
  const getRenderContentForQAGistSummaryCard = useCallback(
    (_tag: Tabs) => {
      let renderEle;
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      const [title, paddingTop, theme, summary] =
        _tag === Tabs.Highlights
          ? ['要点', 50, eTheme.GIST, <GistSummary key={_tag} data={QAList} />]
          : [
              '问答',
              22,
              eTheme.QA,
              <QASummary key={_tag} data={QAList} unfold />,
            ];
      switch (currentDocBigModelData?.keyPointsReviewStatus) {
        case eLabInfoStatus.FAILED:
          renderEle = (
            <div>
              <SummaryErrorText isFail />
            </div>
          );
          break;
        case eLabInfoStatus.TEXT_TOO_SHORT:
          renderEle = (
            <div>
              <SummaryErrorText text={'抱歉，全文内容太短了，无总结内容哦'} />
            </div>
          );
          break;
        case eLabInfoStatus.FINISH:
          renderEle = QAList.length ? (
            summary
          ) : (
            <div style={{ color: '#c8cad9' }}>
              <SummaryErrorText text={'没有总结内容哦'} />
            </div>
          );
          break;
        default:
          break;
      }
      return renderEle;
    },
    [
      QAList,
      currentDocBigModelData?.keyPointsReviewStatus,
      gistQAReviewId,
      haveClicked,
      changeGistQAUnfold,
      docId,
    ],
  );

  // 渲染待办事项 内容
  const getRenderContentForToDoList = useCallback(() => {
    if (!todoList) return null;

    return <ToDoListCom data={todoList} expanded />;
  }, [todoList, docId]);

  const timerMessage = useRef();
  const showMessageError = () => {
    timerMessage.current && clearTimeout(timerMessage.current);
    timerMessage.current = setTimeout(() => {
      message.warning({
        content: `内容不能为空，请补充内容`,
        key: 'agenda_title_valueNull',
      });
    }, 300);
  };
  useEffect(() => {
    bus.on(SHOWBIGMODEL_ERROR_MESSAGE, showMessageError);
    return () => {
      bus.off(SHOWBIGMODEL_ERROR_MESSAGE, showMessageError);
      boxTabsTimer && clearTimeout(boxTabsTimer);
    };
  }, []);

  const onExpandHandler = useCallback(() => {
    const scrollDom = document.getElementById(
      'tingwu_paragraphs_scrollContainer',
    );
    if (scrollDom && containerRef.current) {
      const { top } = containerRef.current.getBoundingClientRect();
      if (top < extraHeight) {
        scrollDom.scrollTo({
          top: scrollDom.scrollTop + top - extraHeight,
        });
      }
    }

    if (currentTab === Tabs.Agenda) {
      myLocalStorage.setItemById(
        'showedAgendaSummaryExpanderV2',
        String(docId as string),
      );
    } else if (currentTab === Tabs.SpeakerSummary) {
      myLocalStorage.setItemById(
        'showedSpeakerSummaryExpanderV2',
        String(docId as string),
      );
    }
  }, [currentTab, extraHeight, docId]);

  const renderDirtyMeetingSummaryCard = useMemo(() => {
    return <DirtyMeetingSummaryCard />;
  }, []);

  // 总渲染
  const renderedContent = useMemo(() => {
    let renderContent: JSX.Element | null = null;
    switch (currentTab) {
      case Tabs.Agenda: {
        const isAgendaReady =
          agendaSummaryStatus !== undefined &&
          agendaSummaryStatus !== eLabInfoStatus.LOADING;
        if (!agendaList) return;
        if (!isAgendaReady) return;
        renderContent = getRenderContentForAgendaContent();
        break;
      }
      case Tabs.SpeakerSummary: {
        renderContent = renderSpeakerSummary;
        break;
      }
      case Tabs.PPT: {
        renderContent = getRenderContentForPPTSummary();
        break;
      }
      case Tabs.Highlights:
      case Tabs.QNAReview:
        renderContent = getRenderContentForQAGistSummaryCard(currentTab);
        break;
      case Tabs.ToDoList: {
        renderContent = getRenderContentForToDoList();
        break;
      }
      case Tabs.Summary: {
        renderContent = renderDirtyMeetingSummaryCard;
        break;
      }
      default: {
        renderContent = null;
        break;
      }
    }

    return (
      <WulabContainer
        style={{
          marginTop: currentTab === Tabs.QNAReview ? '2px' : '0px',
          marginBottom: currentTab === Tabs.PPT ? '24px' : '0px',
        }}
      >
        <SwitchAnimationContainer key={currentTab}>
          {renderContent}
        </SwitchAnimationContainer>
      </WulabContainer>
    );
  }, [
    currentTab,
    onExpandHandler,
    getRenderContentForQAGistSummaryCard,
    agendaList,
    agendaDotVisible,
    getRenderContentForAgendaContent,
    currentDocBigModelData?.speakSummary,
    currentDocBigModelData?.speakSummaryStatus,
    docId,
    renderSpeakerSummary,
    pptlist,
    pptAgendas.length,
    getRenderContentForPPTSummary,
    todoList,
    getRenderContentForToDoList,
    agendaSummaryStatus,
  ]);

  const renderNoData = useCallback(() => {
    return (
      <div style={{ height: '80vh', width: '100%', marginTop: 16 }}>
        <Exception
          fullScreen
          showBtn={false}
          type="noData"
          title=""
          description={'暂无数据'}
        />
      </div>
    );
  }, []);
  if (!tabs.length) {
    return renderNoData();
  }
  // PPT 加载完成或者议程加载完成，才展示tab（这里有点问题，但是之前就是这么判断的）
  if (tabs.length) {
    return (
      <AgendaContainer ref={containerRef}>
        <SummaryAnimation>
          <TitleWrapper>
            <TitleHeading ref={titleHeadingRef as any}>
              <Title>
                <TitleTabs
                  tabs={tabs}
                  tabRef={tabRef}
                  shortMode={shortMode}
                  currentTab={currentTab}
                  pptDotVisible={pptdotVisible}
                  onClickTab={onClickTab}
                />
              </Title>
              <HeadingExtraContainer>
                <HeadingOperates
                  className={'sphereCard-headingOperates'}
                ></HeadingOperates>
              </HeadingExtraContainer>
            </TitleHeading>
            {renderedContent}
          </TitleWrapper>
        </SummaryAnimation>
      </AgendaContainer>
    );
  }

  return renderNoData();
};

export default BigModelTabs;
