import React, { useContext, memo } from 'react';
import Group from './Group';
import { ComponentDataContext, CallbackContext, PanelDataContext, InteractionContext } from './Context';
import { getGroupDimension, getGroupChildren, getComponentDimension } from 'utils/component';
import { getValueByKey, isGeneralPanel, isComponent } from 'utils/utils';
import { getState, getId } from 'utils/interaction';

function GroupWrap({
  id,
  components,
  movable,
  leftKey,
  topKey,
  topOffset,
  leftOffset,
  transitionTime,
  transitionDelay,
  transitionTimingFunction,
  opacity,
  hideDefault,
  transform,
  mountAnimation
}) {
  const { componentsById = {} } = useContext(ComponentDataContext);
  const { callbackValues = {} } = useContext(CallbackContext);
  const { panelsById = {} } = useContext(PanelDataContext);
  const { interactions = [] } = useContext(InteractionContext);

  const { iState, iActiveState } = getState({ id, interactions });
  const allComponentsId = getGroupChildren({ components }).map((d) => d.id);
  const dimensions = allComponentsId
    .map((id) => {
      if (isComponent(id)) {
        const component = componentsById[id];
        if (component) {
          return { id, ...getComponentDimension(component.config) };
        } else {
          return null;
        }
      } else if (isGeneralPanel(id)) {
        const panel = panelsById[getId(id) as number];
        if (panel) {
          const { config } = panel;
          const { width, height, left, top } = config;
          if (panel) {
            return {
              id,
              left,
              top,
              width,
              height
            };
          }
        }
      }
    })
    .filter((d) => d);
  const groupDimension = getGroupDimension(dimensions);
  const { left, top, width, height } = groupDimension;
  let dynamicTop;
  let dynamicLeft;

  if (movable) {
    dynamicTop = getValueByKey(callbackValues, topKey);
    dynamicLeft = getValueByKey(callbackValues, leftKey);
  }

  return (
    <Group
      id={id}
      width={width}
      height={height}
      left={left}
      top={top}
      components={components}
      movable={movable} // 编辑不应用movable属性
      dynamicLeft={dynamicLeft}
      dynamicTop={dynamicTop}
      topOffset={topOffset}
      leftOffset={leftOffset}
      transitionTime={transitionTime}
      transitionDelay={transitionDelay}
      transitionTimingFunction={transitionTimingFunction}
      opacity={opacity}
      hideDefault={hideDefault}
      transform={transform}
      mountAnimation={mountAnimation}
      iState={iState}
      iActiveState={iActiveState}
    />
  );
}

export default memo(GroupWrap);
