import { Presentation, PresentationAgenda } from '@tingwu/sphere';
import React, { memo, useEffect, useRef } from 'react';
import PPTSummaryAdenda from './PPTSummaryAdenda';
import PPTSummaryItem from './PPTSummaryItem';

const PPTSummaryList = memo(
  ({
    pptList,
    titleInfo,
    preValue,
    index,
    lastIndex,
    shortMode,
    isAgendaNull,
    lastPPTIndex,
    transId,
    isMergeList = true,
    scrollIntoViewPPTRef,
    isOverOneHour,
  }: {
    pptList: Presentation[];
    titleInfo?: PresentationAgenda;
    preValue?: boolean;
    index: number;
    lastIndex?: boolean;
    shortMode?: boolean;
    isAgendaNull?: boolean;
    lastPPTIndex?: boolean;
    transId: string;
    isMergeList?: boolean;
    scrollIntoViewPPTRef?: { current: any };
    isOverOneHour: boolean;
  }) => {
    const foldUpRef = useRef(false);
    const [list, setList] = React.useState<Presentation[]>([]);

    // 合并PPT，向下合并，最后一组向上合并，不支持跨章节
    const pptListListener = () => {
      if (pptList.findIndex((item) => item.isLoadingContent) > -1) return '';

      let startIndex = 0;
      let endIndex = 0;
      const map: number[][] = [];
      for (let i = 0; i < pptList.length; i++) {
        const ppt: any = { ...pptList[i] };
        if (typeof ppt.content === 'string') {
          ppt.content = ppt.content.trim();
        }
        // 没有content 需要合并
        if (!ppt.content) {
          endIndex = i;
          if (!ppt.index) {
            if (startIndex !== i) {
              endIndex = i - 1;
              map.push([startIndex, endIndex]);
            }
            endIndex = i;
            startIndex = i;
            map.push([startIndex, endIndex]);
            startIndex = endIndex + 1;
          }
          if (i === pptList.length - 1) {
            const item = map.length > 0 ? map[map.length - 1] : undefined;
            if (item) {
              map[map.length - 1] = [item[0], endIndex];
            }
          }
        } else {
          // 有content
          endIndex = i;
          map.push([startIndex, endIndex]);
          startIndex = endIndex + 1;
        }
      }
      if (pptList.length > 0 && map.length === 0) {
        // 全部的：有图片，没有描述
        map.push([0, pptList.length - 1]);
      }
      const _list: Presentation[] = [];
      for (let i = 0; i < map.length; i++) {
        const pptIndex = map[i];
        const ppt: any = { ...pptList[pptIndex[0]] };
        if (pptIndex[0] !== pptIndex[1]) {
          ppt.radius = pptIndex;
        }
        _list.push(ppt);
      }
      setList([..._list]);
    };

    React.useEffect(() => {
      setList([...pptList]);
      if (!location.search.includes('debug') && isMergeList) {
        foldUpRef.current = true;
        // 非编辑状态，PPT进行折叠；编辑状态不折叠
        pptListListener();
      } else {
        foldUpRef.current = false;
      }
    }, [pptList, isMergeList]);
    let timer: any;
    useEffect(() => {
      if (lastPPTIndex) {
        if (!scrollIntoViewPPTRef) return;
        if (scrollIntoViewPPTRef.current < 0) return;
        // 最后一个元素初始化完成
        const divs = document.getElementsByClassName('tingwu2_ppt_item');
        if (!divs?.length) return;
        Array.from(divs).forEach((element: any) => {
          const { time, custom } = element.dataset;

          if (
            scrollIntoViewPPTRef?.current !== undefined &&
            `${scrollIntoViewPPTRef?.current}` === `${time}` &&
            custom
          ) {
            scrollIntoViewPPTRef.current = -1;
            const { top: tops } = element.getBoundingClientRect();
            const doc = document.getElementById('tingwu_wulab_scrollContainer');
            const topDiv = document.getElementById('tingwu2-bigmodel-top');
            if (!doc || !topDiv) return;
            const { top } = topDiv?.getBoundingClientRect();
            timer && clearTimeout(timer);
            timer = setTimeout(() => {
              console.log('tops - top - 38', tops - top - 38);
              doc.scrollTo({ top: tops - top - 38 });
            }, 500);
          }
        });
      }
    }, [list, lastPPTIndex, scrollIntoViewPPTRef]);

    return (
      <div>
        {titleInfo ? (
          <PPTSummaryAdenda
            isOverOneHour={isOverOneHour}
            lastIndex={lastIndex}
            index={index}
            info={titleInfo}
            preValue={preValue}
            transId={transId}
            type="detail"
          />
        ) : null}

        {list.map((ppt, i) => {
          const _ppt: any = { ...ppt };
          if (_ppt && _ppt.content !== undefined) {
            _ppt.content =
              typeof _ppt.content === 'string'
                ? _ppt.content?.trim()
                : _ppt.content;
          }
          if (_ppt.radius && !_ppt.content) {
            const _pptIndexs = _ppt.radius;
            if (_pptIndexs && _pptIndexs.length === 2) {
              // 获取有值的数据
              _ppt.content =
                pptList.find(
                  (ppti, idx) =>
                    idx >= _ppt.radius[0] &&
                    idx <= _ppt.radius[1] &&
                    ppti.content,
                )?.content || '';
            }
          }
          const lastListIndex = i === pptList.length - 1;
          const _lastIndex =
            isAgendaNull || lastPPTIndex ? lastListIndex : false;

          return (
            <PPTSummaryItem
              isOverOneHour={isOverOneHour}
              custom={_ppt.index}
              key={_ppt}
              shortMode={shortMode}
              info={_ppt}
              index={i}
              isAgendaNull={isAgendaNull}
              titleInfo={titleInfo}
              lastIndex={_lastIndex}
              transId={transId}
            />
          );
        })}
      </div>
    );
  },
);

export default PPTSummaryList;
