import React from 'react';
import ReactDOM from 'react-dom';

export function asyncGet(asyncDom, props, cb, confirm = 'onConfirm', cancel = 'onCancel') {
  const NODE = document.createElement('div');
  document.body.appendChild(NODE);
  function remove(node) {
    setTimeout(() => {
      ReactDOM.unmountComponentAtNode(node);
      document.body.removeChild(node);
    }, 100);
  }
  const params = {
    [confirm]: data => {
      return cb(data);
    },
    [cancel]: () => {
      remove(NODE);
    },
  };
  return asyncDom().then(({ default: C }) => {
    return new Promise(resolve => {
      ReactDOM.render(<C ref={ref => ref && resolve(ref)} {...props} {...params} />, NODE);
    });
  });
}

export function asyncForm(title, itemList, data, cb) {
  return asyncGet(() => import('../layouts/FormLayout'), { title, itemList, data, modal: true }, cb);
}

export function asyncDrawerForm(title, itemList, data, cb, drawer = 'right') {
  return asyncGet(() => import('../layouts/FormLayout'), { title, itemList, data, drawer }, cb);
}

function getAsyncAntd() {
  return import('../components/AsyncAntd');
}

export function asyncModalConfirm(props, cb) {
  const params = {
    onOk: () => {
      cb();
    },
    destroyOnClose: true,
  };
  getAsyncAntd().then(({ Modal }) => {
    Modal.confirm(Object.assign(params, props));
  });
}

export function asyncConfirm(title, content, cb) {
  return asyncModalConfirm({ title, content, maskClosable: true }, cb);
}

export function asyncDelConfirm(title, content, cb) {
  return asyncModalConfirm({ title, content, okType: 'danger', maskClosable: true }, cb);
}

export function asyncSMessage(title, type = 'success') {
  return getAsyncAntd().then(({ Message }) => {
    switch (type) {
      case 'warn':
      case 'warning':
        Message.warning(title);
        break;
      case 'error':
        Message.error(title);
        break;
      case 'success':
      default:
        Message.success(title);
        break;
    }
  });
}
