import { snackbar } from 'neatui';
import xhr from 'SERVICE/xhr';
import './index.scss';
import { error } from 'UTIL/notification';
import BaseComponent from 'COMPONENT/common/BaseComponent';
import { withRouter } from 'react-router-dom';
import { getSearchParams } from 'UTIL/util';
import projectConfig from 'CONFIG/projectConfig.json';

const localHost = projectConfig.localhost || [];
localHost.push('localhost');

class Loopsnackbar extends BaseComponent {
    constructor(props, context) {
        super(props, context);
        this.env = localHost.indexOf(window.location.hostname) > -1 ? 'local.' : '';
        const { getInstance } = props;
        if (typeof getInstance === 'function') {
            getInstance(this);
        }
        this.searchParams = getSearchParams();
        this.config = this.props.config;
        this.state = {
            intervalID: ''
        };
    }

    componentDidMount() {
        this.fetchDataHandler();
        const id = setInterval(() => {this.fetchDataHandler()}, 10000);
        this.setState({
            intervalID: id
        });
    }

    componentWillUnmount() {
        clearInterval(this.state.intervalID);
    }

    fetchDataHandler = () => {
        const mine = this;
        const url = mine.config.basic[`${this.env}url`];
        xhr({
            url,
            method: mine.config.basic.method || 'get',
            data: {},
            type: 'json',
            contentType: mine.config.basic.contentType,
            notSwitchArrToStr: mine.config.basic.notSwitchArrToStr,
            complete: () => {
                mine.setState({
                    loading: false
                });
            }
        }).then((rs) => {
            if (rs[projectConfig.codeKey] === projectConfig.code) {
                snackbar.open({
                    content: rs.data || '',
                });
            } else {
                error(rs[projectConfig.msg]);
            }
        });
    }
    
    render() {
        return ('');
    }
}

export default withRouter(Loopsnackbar);
