import React, {
  useCallback,
  useEffect,
  useState,
  forwardRef,
  useImperativeHandle,
} from 'react';
import { CnMessage as UICnMessage } from '@cainiaofe/cn-ui-m';
import { calculateTextExprValue, executeFunction } from '@/common/util/util';
import { CnDataSourceChange, onEvent } from '@/common/util/event-name';

const CnMessage = forwardRef((props, ref) => {
  if (!UICnMessage) {
    return null;
  }

  const {
    title = '',
    _context,
    getContext,
    _getFormValue,
    visible,
    type,
    closable,
    ...rest
  } = props;
  const { needMargin } = rest || {};
  let realTitle = title;
  let state = _context?.state;
  const [forceUpdate, setForceUpdate] = useState();
  if (!state && typeof getContext === 'function') {
    state = getContext()?.state || {};
  }
  const formValue = _getFormValue?.();

  useEffect(() => {
    if (typeof title === 'function') {
      onEvent(CnDataSourceChange, () => {
        setForceUpdate(Date.now());
      });
    }
  }, []);

  if (typeof title === 'function') {
    realTitle = title(state, formValue || {});
  }

  const realVisible = calculateTextExprValue(visible, {
    recordDataSource: {},
    state,
  });

  const extraProps = {
    closable,
  };
  // if(needMargin === true) {
  //   extraProps.style = {
  //     margin: '12px 0'
  //   }
  // }else if(isArrayNotEmpty(needMargin)) {
  //   extraProps.style = {
  //   }
  //   needMargin.forEach(item=>{
  //     if(item === true) {
  //       extraProps.style.margin = '12px 0'
  //     }else if(typeof item === 'string') {
  //       extraProps.style[`margin-${item}`] = '12px'
  //     }
  //   })
  // }
  extraProps.type = type;
  if (typeof type === 'function') {
    extraProps.type = executeFunction(type, formValue || {}, state);
  }
  return realVisible !== false ? (
    <UICnMessage {...rest} {...extraProps}>
      {realTitle}
    </UICnMessage>
  ) : (
    ''
  );
});
CnMessage.displayName = 'CnMessage';
export default CnMessage;
