import React, {useState} from 'react'
import ReactDOM from 'react-dom'
import styles from './style.module.css'


interface Props {
  node: HTMLDivElement,
  children: any,
  stateChange?: Function,
  show?: boolean,
  title?: string
}

function Dialog({node, children, stateChange, show = false, title}: Props) {
  const [ishow, setIShow] = useState(false)
  const showChange = (show: boolean) => {
    setIShow(show)
    stateChange && stateChange(show)
  }

  if (show !== ishow) {
    setIShow(show)
    return null
  }

  const Layer = ishow ? (
    <div className={styles.layer}>
      <div className={styles.content}>
        <span className="icon-cancel" onClick={() => showChange(false)}></span>
        {title && <div className={styles.title}>{title}</div>}
        <div className={styles.content}>
          {children}
        </div>
        <div className={styles.bar}>
          <span onClick={() => showChange(false)} >取消</span>
          <span onClick={() => showChange(true)}>确定</span>
        </div>
      </div>
    </div>
  ) : null

  return ReactDOM.createPortal(Layer, node)
}


const node = document.querySelector('#dialog')
const GDialog = (props: any) => <Dialog node={node} {...props} />

export default GDialog