import React from 'react';
import { Modal } from 'antd';
import { isJSON } from '@/webPublic/one_stop_public/copy';

const formatProps = (ModalFuncProps) => {
	ModalFuncProps.getContainer = ModalFuncProps.getContainer || false;
	return ModalFuncProps;
};

window.addEventListener('message', (event) => {
	if (event.data && event.data.indexOf) {
		if (event.data.indexOf('iframeGetScrollHeight') > -1) {
			const height = event.data.split('-')[1];
			// console.log('父页面向子iframe页面发送滚动高度: ', event.data);
			let dom = document.getElementsByClassName('ant-modal-wrap');
			if (dom && dom.length) {
				dom[0].style.top = height + 'px';
			}
		}

    if (event.data.indexOf('setAuthorityLocalStorage') > -1) {
      const info = event.data.split('-');
      // console.log('父页面告知子页面localStorage信息: antd-pro-authority');
      if (info && info.length > 1) {
        localStorage.setItem('antd-pro-authority', info[1]);
      }
    }
	}
});

const sendMessageAndGetHeight = () => {
	// 获取当前屏幕滚动的高度 并将Modal 弹窗的高度绝对定位到屏幕以内
	window.top.postMessage('iframeGetScrollHeight', '*');
};

const DiyIframeModal = (props) => {
	return <Modal {...props} />;
};

const ModalFuncs = function(ModalFuncProps, type = 'info') {
	sendMessageAndGetHeight();

	return Modal[type](formatProps(ModalFuncProps));
};

DiyIframeModal.info = function(ModalFuncProps) {
	return ModalFuncs(ModalFuncProps, 'info');
};

DiyIframeModal.success = function(ModalFuncProps) {
	return ModalFuncs(ModalFuncProps, 'success');
};

DiyIframeModal.error = function(ModalFuncProps) {
	return ModalFuncs(ModalFuncProps, 'error');
};

DiyIframeModal.warning = function(ModalFuncProps) {
	return ModalFuncs(ModalFuncProps, 'warning');
};

DiyIframeModal.confirm = function(ModalFuncProps) {
	return ModalFuncs(ModalFuncProps, 'confirm');
};

DiyIframeModal.warn = function(ModalFuncProps) {
	return ModalFuncs(ModalFuncProps, 'warn');
};

DiyIframeModal.destroyAll = function() {
	return Modal.destroyAll();
};

export default DiyIframeModal;
