import React, { useEffect, useRef } from 'react';
import { Modal } from 'antd';

export default (props) => {
  const ref = useRef();

  useEffect(() => {
    let t = null;
    if (props.visible) {
      // 防止 postMessage 的时候 iframe 内容还没有加载完成
      t = setInterval(() => {
        // window.preViewFrame.window.postMessage(props.html, '*')
        if (ref.current) {
          ref.current.contentWindow.postMessage(props.html, '*');
        }
      }, 800);
    }

    return () => t && clearInterval(t);
  }, [props.visible, props.html]);

  return (
    <Modal
      visible={props.visible}
      wrapClassName="editor-preivew-modal-content"
      width={props.width}
      bodyStyle={props.style}
      footer={null}
      closable={false}
      title={null}
      onCancel={props.onCancel}
    >
      <iframe
        ref={ref}
        style={{ width: '100%', height: '100%' }}
        src={`${window.location.origin}/preview-html/index.html`}
        frameBorder={0}
        name="preViewFrame"
      ></iframe>
    </Modal>
  );
};
