import React from 'react'
import ReactDOM from 'react-dom'
import Notify from './notify'

/***
 * 信息提示框组件
 * author: zxc@2018-11-28
 * 接收参数：
 * type: 信息提示框类型, 包括success、error、info。
 * content: 信息提示框文本内容
 * duration: 自动关闭的延时,单位毫秒。默认2000毫秒,设为 0 时不自动关闭。
 * 用法如下：
 * Notify.success('删除成功')
***/

function createNotification() {
    const div = document.createElement('div')
    document.body.appendChild(div)
    const notification = ReactDOM.render(<Notify />, div)
    return {
        addNotice(notice) {
            return notification.addNotice(notice)
        },
        destroy() {
            ReactDOM.unmountComponentAtNode(div)
            document.body.removeChild(div)
        }
    }
}

let notification
const notice = (type, content, duration=2000, onClose) => {
    if (!notification) notification = createNotification()
    return notification.addNotice({ type, content, duration, onClose })
}

export default {
    info(content, duration, onClose) {
        return notice('info', content, duration, onClose)
    },
    success(content = '操作成功', duration, onClose) {
        return notice('success', content, duration, onClose)
    },
    error(content, duration , onClose) {
        return notice('error', content, duration, onClose)
    }
}