import React, { Component } from 'react';
import ReactDom from 'react-dom';
import hocImmutable, { imShallowEqual } from '../../utils/HOC/hocImmutable';
import { Alert, Icon } from 'antd';
import FlexBox from '../grid/FlexBox';
import './style.less';

const _Alert = class extends Component {
    constructor(props) {
        super(props);
    }
    state = {
        visible: true
    }
    store = {
        onCloseCalled: false
    }
    componentWillMount() {
        const { duration = 5, onClose, ...props } = this.props;
        if (duration > 0) {
            setTimeout(() => {
                this.setState({ visible: false });
                this.onClose();
            }, duration * 1000);
        }
    }
    onClose = () => {
        if (!this.store.onCloseCalled) {
            this.store.onCloseCalled = true;
            const { onClose } = this.props;
            onClose && onClose();
        }
    }
    render() {
        let { type = 'warn', content = '', duration = 5, onClose, closable = true, style = {}, ...props } = this.props;
        if (type === 'warn') {
            type = 'warning';
        }
        if (type === 'loading') {
            type = 'info';
            if (props.showIcon || props.showIcon === undefined) {
                props.showIcon = false;
                style.paddingLeft = 38;
                content = <span><Icon className='ant-alert-icon' type='loading' />{content}</span>
            }
        }
        return <Alert {...props}
            banner
            style={Object.assign(style, { display: this.state.visible ? 'block' : 'none' })}
            type={type}
            message={content}
            closable={closable}
            onClose={this.onClose}
        />
    }
}

const Comp = class extends Component {
    constructor(props) {
        super(props);
    }
    state = {
        children: []
    }
    show(options = {}) {
        const children = this.state.children.slice(0);
        children.push(<_Alert {...options} style={{ marginBottom: 14 }} />)
        this.setState({ children });
    }
    render() {
        return <FlexBox fullW justify='center'>
            <FlexBox xs={24} sm={16} md={12} lg={10} xl={8} block>
                {this.state.children}
            </FlexBox>
        </FlexBox>
    }
}

let instance = null;
const show = (options) => {
    if (instance === null) {
        const div = document.createElement('div');
        document.body.appendChild(div);
        div.classList.add('message-banner-container');
        instance = ReactDom.render(<Comp />, div);
    }
    instance.show(options)
}
export default {
    show
}