const Loading = (($) => {
    const TPL = '<div id="J_PageLoader" class="cd-loader"><div class="cd-loader-body"><img src="//img11.360buyimg.com/cms/jfs/t17101/342/958383994/30745/6cc39ad1/5ab492f1N4aef5f59.gif">{{text}}</div></div>',
        areaTpl = '<div id="J_PageLoader" class="cd-loader"><div class="lds-spinner"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div></div>',
        defaultConfig = {
            outTime: 0,
            text:'加载中，请稍候…',
        };
    class Loading {
        constructor(config) {
            this.config = this._getConfig(config);
            if (this.config.node) {
                this.loader = $(areaTpl);
                let _element = $(this.config.node);
                let _size = {width: '100%', height: '100%'};
                this._setPosition({
                    left: 0,
                    top: 0
                });
                this._setSize(_size);
                if (_element.css("position") === 'static') _element.css('position', 'relative');
                _element.append(this.loader);
            } else {
                this.loader = $(template.render(TPL, {text: this.config.text}));
                this._setPosition({position: 'fixed', left: 0, top: 0});
                this._setSize({width: '100%', height: '100%'});
                $('body').append(this.loader);
            }
            if (this.config.zIndex) {
                this.loader.css({
                    zIndex: this.config.zIndex
                });
            }
            this.loader.on('click', function (ev) {
                ev.stopPropagation();
            });
        }
        
        _getConfig(config) {
            return $.extend({}, defaultConfig, config);
        }
        show() {
            this.loader.fadeIn();
            if (this.config.outTime !== 0) {
                setTimeout(this.dispose.bind(this), this.config.outTime);
            }
        }
        hide() {
            this.loader.fadeOut();
        }
        
        dispose() {
            let _this = this;
            _this.loader && _this.loader.off("click");
            _this.loader && _this.loader.fadeOut('normal', function () {
                _this.loader.remove();
                _this.config = null;
                _this.loader = null;
            });
        }
        
        _setSize(size) {
            this.loader.css({
                width: size.width,
                height: size.height
            });
        }
        
        _setPosition(pos) {
            let _pos = pos || {};
            this.loader.css({
                position: _pos.position || 'absolute',
                left: _pos.left || 0,
                top: _pos.top || 0
            });
        }
        
    }
    return Loading;
})($);
export default Loading;