import { BIG_MODEL_LOADED } from '../../../../../../../pages/docASR/utils/config';
import bus from '../../../../../../../utils/bus';
import React, {
  forwardRef,
  memo,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';
import {
  AnimationColor,
  BackgroundColor,
  Container,
  GlobalStyle,
} from './styled';

/** 新版数据 引用 */
import {
  docBigModelHooks,
  docSpeakerHooks,
} from '../../../../../../../documentModel';
import { eLabInfoStatus } from '../../../../../../../documentModel/docBigModel/docBigModel.type';
// import { IntelligenceLoadingContentProps } from '..';

export const IntelligenceLoading = React.memo(
  (props: { style?: React.CSSProperties }) => {
    const { style } = props;

    const { currentDocBigModelData } = docBigModelHooks.useDocBigModelData();
    const {
      keyWordInfoStatus,
      fullTextSummaryStatus,
      chapterOverviewStatus,
      speakSummaryStatus,
      keyPointsReviewStatus,
    } = currentDocBigModelData || {};

    const { docSpeakerData } = docSpeakerHooks.useDocSpeakerData();
    const { speakersSplitIsLoading } = docSpeakerData || {};

    const [visible, setVisible] = useState<boolean>(false);
    const [textArray, setTextArray] = useState<string[]>([]);
    const statusArr = useRef<Array<number | boolean>>([]);

    useEffect(() => {
      const _textArray: any = [];
      statusArr.current = [];
      const ObjVal = {
        speakersSplitIsLoading: '发言人区分处理中，请稍后查看...',
        keyWordInfoStatus: '关键词处理中，请稍后查看...',
        fullTextSummaryStatus: '全文概要处理中，请稍后查看...',
        chapterOverviewStatus: '章节速览摘要处理中，请稍后查看...',
        speakSummaryStatus: '发言总结处理中，请稍后查看...',
        keyPointsReviewStatus: '回顾处理中，请稍后查看...',
      };
      const _status = {
        keyWordInfoStatus,
        fullTextSummaryStatus,
        chapterOverviewStatus,
        speakSummaryStatus,
        keyPointsReviewStatus,
        speakersSplitIsLoading,
      };
      Object.keys(_status).forEach((item) => {
        if (item === 'speakersSplitIsLoading' && speakersSplitIsLoading) {
          _textArray.push(ObjVal[item]);
        } else if (_status[item] === eLabInfoStatus.LOADING) {
          _textArray.push(ObjVal[item]);
        }
        statusArr.current.push(_status[item]);
      });
      setTextArray(_textArray);
      setVisible(
        !!statusArr.current.find(
          (status) =>
            status === eLabInfoStatus.LOADING ||
            (typeof status === 'boolean' && status === true),
        ),
      );
    }, [
      keyWordInfoStatus,
      fullTextSummaryStatus,
      chapterOverviewStatus,
      speakSummaryStatus,
      keyPointsReviewStatus,
      speakersSplitIsLoading,
    ]);

    const [animationClass, setAnimationClass] = useState<
      'intelligence-loading-show' | 'intelligence-loading-hide'
    >('intelligence-loading-show');
    const containerRef = useRef<HTMLDivElement>(null);
    const loadingTextRef = useRef<any>();
    const isTextAnimationStarted = useRef(false);
    const isLoadResultRef = useRef(false);
    const wulabLoadStatus = useRef(false);

    const changeWulabLoading = (load) => {
      if (load) {
        wulabLoadStatus.current = true;
        bus.emit(BIG_MODEL_LOADED, true);
      } else {
        if (wulabLoadStatus.current) {
          console.log('debug:onWulabTrans-false');

          bus.emit(BIG_MODEL_LOADED, false);
        }
        wulabLoadStatus.current = false;
      }
    };
    const onAnimationEnd = () => {
      if (!containerRef.current) return;

      if (visible) {
        if (!isTextAnimationStarted.current) {
          isTextAnimationStarted.current = true;
          loadingTextRef.current.startAnimation();
        }
      } else {
        containerRef.current.style.display = 'none';
        changeWulabLoading(false);
      }
    };

    useEffect(() => {
      if (!containerRef.current) return;
      if (visible) {
        // loading延时展示
        setTimeout(() => {
          if (isLoadResultRef.current) {
            isLoadResultRef.current = false;
            return;
          }

          if (containerRef.current) {
            setAnimationClass('intelligence-loading-show');
            containerRef.current.style.display = 'flex';
            changeWulabLoading(true);
          }
        }, 300);
      } else {
        isLoadResultRef.current = true;
        setAnimationClass('intelligence-loading-hide');
        containerRef.current.style.display = 'none';
        changeWulabLoading(false);
      }
    }, [visible, containerRef.current, isLoadResultRef.current]);

    return (
      <div>
        <GlobalStyle />
        <Container
          ref={containerRef}
          className={animationClass}
          style={style}
          onAnimationEnd={onAnimationEnd}
        >
          <div className={'contentDiv'}>
            <IntelligenceLoadingContent
              ref={loadingTextRef}
              textArray={textArray}
            />
          </div>
          <AnimationColor />
          <BackgroundColor />
        </Container>
      </div>
    );
  },
);
export const IntelligenceLoadingContent: React.FC<any> = memo(
  forwardRef((props, ref) => {
    const { textArray } = props;
    const [animationClass, setAnimationClass] = useState<
      'animation-loading-text-show' | 'animation-loading-text-hide' | ''
    >('');
    const contentRef = useRef<HTMLDivElement>(null);
    const textRef = useRef<HTMLDivElement>(null);
    const textIndex = useRef(0);

    const onAnimationStart = () => {
      if (!contentRef.current) return;

      if (animationClass === 'animation-loading-text-show') {
        contentRef.current.style.visibility = 'visible';
      }
    };

    const onAnimationEnd = () => {
      if (!textRef.current || !contentRef.current) {
        return;
      }

      if (animationClass === 'animation-loading-text-hide') {
        contentRef.current.style.visibility = 'hidden';
        if (textArray.length > 0) {
          textIndex.current++;
          textRef.current.innerText =
            textArray[textIndex.current % textArray.length];
        }
        setAnimationClass('animation-loading-text-show');
      } else if (animationClass === 'animation-loading-text-show') {
        setAnimationClass('animation-loading-text-hide');
      }
    };

    useImperativeHandle(ref, () => ({
      startAnimation: () => {
        setAnimationClass('animation-loading-text-show');
      },
    }));

    return (
      <div
        ref={contentRef}
        className={`loading-content ${animationClass}`}
        onAnimationStart={onAnimationStart}
        onAnimationEnd={onAnimationEnd}
      >
        <div ref={textRef}>{textArray[0] || ''}</div>
      </div>
    );
  }),
);
