import React, { memo, useEffect, useMemo } from 'react';
import ScreenWrap from './index';
import Animation from './Animation';
import styles from './Panel.less';

const MAX_DELAY = 2147483;

function Panel({
  id,
  config,
  states,
  iState,
  iActiveState,
  switchPanelState,
  parentScreens,
  screenId
}: {
  id: number;
  screenId: number;
  config: {
    left: number;
    top: number;
    width: number;
    height: number;
    allowScroll: boolean;
    autoCarousel: boolean;
    interval: number;
  };
  states: number[];
  iState: any;
  iActiveState: any;
  parentScreens: number[];
  switchPanelState?: (id: number) => void;
}) {
  const { left, top, width, height, allowScroll, autoCarousel, interval } = config;

  useEffect(() => {
    let timer;
    if (autoCarousel && states.length > 1) {
      timer = setInterval(() => {
        switchPanelState && switchPanelState(id);
      }, (interval >= MAX_DELAY ? MAX_DELAY : interval) * 1000);
    }
    return () => {
      timer && clearInterval(timer);
    };
  }, []);

  const current = (iState && iState.stateId) || states[0];
  const nextParentScreens = useMemo(() => parentScreens.concat(screenId), [parentScreens, screenId]);

  return (
    <Animation id={id} iState={iState} iActiveState={iActiveState} width={width} height={height} top={top} left={left}>
      <div
        id={'' + id}
        className={styles.panel}
        style={{
          width,
          height,
          top,
          left,
          overflow: allowScroll ? 'auto' : 'hidden',
          pointerEvents: allowScroll ? 'auto' : 'none'
        }}>
        {states.map((d, i) => {
          if (nextParentScreens.includes(d)) {
            return (
              <div
                key={i}
                style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24 }}>
                大屏 (id: {d})被循环引用
              </div>
            );
          } else {
            return (
              <Animation
                key={i}
                id={d}
                iState={{ show: current === d ? true : false, unmount: iState && iState.unmount }}
                width={width}
                height={height}
                iActiveState={iActiveState}
                top={0}
                left={0}>
                <ScreenWrap
                  id={d}
                  active={current === d}
                  width={width}
                  height={height}
                  allowScroll={allowScroll}
                  parentScreens={nextParentScreens}
                />
              </Animation>
            );
          }
        })}
      </div>
    </Animation>
  );
}

export default memo(Panel);
