/* eslint-disable react/jsx-no-duplicate-props */
import React, { useState } from 'react';
import * as ReactDOM from 'react-dom';
import { Modal, Button } from 'antd';
import './index.scss';

InitModal.defaultProps = {
  okText: '确认',     //确定按钮的文字
  cancelText: '取消',  //取消按钮的文字
  className: '',         //
  inputId: 'copyText',    //要复制的文本的ID
};

// 使用函数调用删除组件
export default function DelModal(props) {
  renderModal({ ...props, type: 'delete' })
}

// 使用函数调用选择模态框组件
export function Confirm(props) {
  renderModal({ ...props, type: 'confirm' })
}

function renderModal(props) {
  const { type, afterClose } = props;
  const div = document.createElement('div');
  document.body.appendChild(div);

  function destroy() {
    afterClose && afterClose();
    const unmountResult = ReactDOM.unmountComponentAtNode(div);
    if (unmountResult && div.parentNode) {
      div.parentNode.removeChild(div);
    }
  }

  function modalType(type) {
    if (type === 'delete') {
      return <InitModal
        title="删除"
        contentTitle="确定要删除吗？"
        okText="确认删除"
        {...props}

        afterClose={destroy}
        contentTitle={<React.Fragment>
          <i className="red-circle iconfont icon-shanchu_tc_icon mr3"></i>
          {props.contentTitle}
        </React.Fragment>}
      />
    } else if (type === 'confirm') {
      return <InitModal title="选择" afterClose={destroy} {...props} />
    } else {
      return <InitModal title="选择" afterClose={destroy} {...props} />
    }
  }

  function render() {
    setTimeout(() => {
      ReactDOM.render(
        modalType(type),
        div,
      );
    });
  }
  render();
}

// 选择模态框组件
function InitModal({
  onCancel,
  onOk,
  title,
  contentTitle,
  content,
  okText,
  cancelText,
  afterClose,
  className,
}) {

  const [visible, setVisible] = useState(true);

  function onCancelModal() {
    setVisible(false);
    onCancel && onCancel()
  }

  function onSuccess() {
    setVisible(false);
    onOk && onOk();
  }

  return (
    <Modal
      visible={visible}
      onCancel={onCancelModal}
      afterClose={afterClose}
      title={title}
      className={`myself-modal ${className}`}
      centered
      footer={[
        <Button type="default" key="back" onClick={onCancelModal}>
          {cancelText}
        </Button>,
        <Button className="foot-submit" key="submit" onClick={onSuccess}>
          {okText}
        </Button>,
      ]}
    >
      <div>
        {contentTitle && <p className="content-title">{contentTitle}</p>}
        <p className="content-descibe">{content}</p>
      </div>
    </Modal>
  )
}
