import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Button } from 'antd';
import QueueAnim from 'rc-queue-anim';
import IconFont from '../../themeComponents/IconFont';
import './index.less';

const divEle = document.createElement('div');

let changeVisibel = undefined;

function Message(options) {
  return ReactDOM.render(<View {...options} key="message" />, divEle);
}

function View({ onOk, content, title = '温馨提示', width = 380, height = 256, closable = true }) {
  const [visible, setVisibel] = useState(true);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    changeVisibel = setVisibel;
    return () => (changeVisibel = undefined);
  }, []);

  const onSubmit = function () {
    setLoading(true);
    onOk().then(() => {
      setLoading(false);
      setVisibel(false);
    });
  };

  return (
    <QueueAnim animConfig={{ opacity: [1, 0] }} duration={200}>
      {visible && (
        <div key="message" className="message-wrapper">
          <QueueAnim type="top">
            {visible && (
              <div className="message-layout" key="message-content" style={{ width, height }}>
                <div className="message-title">
                  {title}
                  {closable && <IconFont className="close-icon" onClick={() => setVisibel(false)} type="icon-S_Edit_Close" />}
                </div>
                <div className="message-content">
                  {content}
                  <div className="message-footer">
                    {closable && <Button>取消</Button>}
                    <Button loading={loading} type="primary" onClick={onSubmit}>
                      确认
                    </Button>
                  </div>
                </div>
              </div>
            )}
          </QueueAnim>
        </div>
      )}
    </QueueAnim>
  );
}

function notify({ onOk, content, title, width, closable }) {
  document.body.appendChild(divEle);
  Message({ onOk, content, title, width, closable });
  changeVisibel && changeVisibel(true);
}

function destory() {
  ReactDOM.unmountComponentAtNode(divEle);
  document.body.removeChild(divEle);
}

const MessageNotice = { notify, destory };

export default MessageNotice;
