import React, { memo, useEffect, useState, createContext } from 'react';
import Components from './Components';
import { connect } from 'react-redux';
import { screenOperator } from 'utils/screen';
import {getAssetsUrl} from 'utils/utils';
export const ScreenContext = createContext<Set<number | string> | null>(new Set());

function Screen({
  focusLayers,
  id,
  edit,
  layers = [],
  active,
  width,
  height,
  allowScroll,
  backgroundColor,
  useBackgroundImage = true,
  backgroundImage,
  initLoad,
  globalFilter,
  parentScreens
}: {
  focusLayers?: (string | number)[];
  id: number;
  edit: boolean;
  layers: any[];
  active: boolean;
  width?: number;
  height?: number;
  allowScroll?: boolean;
  backgroundColor: string;
  useBackgroundImage: boolean;
  backgroundImage: string;
  initLoad: boolean;
  globalFilter: {
    open: boolean;
    hue: number;
    brightness: number;
    contrast: number;
    grayscale: number;
    opacity: number;
    saturate: number;
  };
  parentScreens;
}) {
  const [load, setLoad] = useState(false);
  const { open, hue, brightness, contrast, grayscale, opacity, saturate } = globalFilter;

  const focusSet = screenOperator.computeFocusLayers(layers, focusLayers);

  useEffect(() => {
    if ((active || initLoad) && !load) {
      // 当前项或者初始化需要加载，并且是未加载过的，需要加载
      setLoad(true);
    }
  }, [initLoad, active]);

  if (load) {
    let filter = '';
    filter = hue ? `${filter} hue-rotate(${hue}deg)` : filter;
    filter = brightness ? `${filter} brightness(${brightness + 100}%)` : filter;
    filter = contrast ? `${filter} contrast(${contrast + 100}%)` : filter;
    filter = grayscale ? `${filter} grayscale(${grayscale}%)` : filter;
    filter = opacity != null && opacity !== 100 ? `${filter} opacity(${opacity}%)` : filter;
    filter = saturate ? `${filter} saturate(${saturate + 100}%)` : filter;

    return (
      <ScreenContext.Provider value={focusSet}>
        <div
          id={`screen_${id}`}
          style={{
            position: 'absolute',
            pointerEvents: allowScroll ? 'auto' : 'none',
            width,
            height,
            backgroundColor,
            backgroundImage: useBackgroundImage
              ? backgroundImage
                ? `url(${getAssetsUrl(backgroundImage)})`
                : undefined
              : undefined,
            backgroundSize: 'cover',
            backgroundPosition: 'center center',
            overflow: edit ? 'unset' : allowScroll ? 'auto' : 'hidden',
            filter: open ? filter : 'unset'
          }}>
          <Components layers={layers} edit={edit} parentScreens={parentScreens} screenId={id} />
        </div>
      </ScreenContext.Provider>
    );
  } else {
    return null;
  }
}

const mapStateToProps = ({ createApp }) => ({ focusLayers: createApp.focusLayers });

export default connect(mapStateToProps, null)(memo(Screen));
