import {tpl, noDataRendererTpl} from './scrollListTpl';
import PageBase from '../pageTable/PageBase';
import "./scrollList.scss";
const ScrollList = (($) => {
    const DefaultConfig = {
        nodataRenderer: noDataRendererTpl,
        dataRenderType: 'append',
        className: "cd-common-list"
    };
    class ScrollList extends PageBase{
        constructor(config) {
            super(config);
            this.__name = "ScrollList";
        }
        renderContent(){
            const {itemRenderer, nodataRenderer, loadingText} = this._config;
            if(itemRenderer == null){
                throw Error("PageTable error: itemRenderer 不能为空");
            }
            if(this.state.loading){
                return template.render(nodataRenderer, {text:loadingText});
            }
            else{
                let pageData = this.state.pageData;
                typeof this._config.renderContentBefore === 'function' && this._config.renderContentBefore(pageData);
                if (pageData && pageData.length > 0) {
                    let _renderList = pageData.map((item, index) => {
                        return template.render(itemRenderer, item);
                    })
                    return _renderList.join("");
                }
                else{
                    return template.render(nodataRenderer, {text:"没有查询到合适的数据"});
                }
            }
        }
        
        _getConfig(config){
            config = $.extend(true, {}, DefaultConfig, config);
            return super._getConfig(config);
        }
        
        initUI(){
            let _content = this.renderContent() || "";
            let renderData = {
                className: this._config.className,
                content:_content
            };
            let renderText = template.render(tpl, renderData);
            this._$ui = $(renderText);
            this._$contentWrapper = this._$ui;
            this._bindEvent();
        }
        
        open(){
            if(this._isShown==false){
                this._isShown = true;
                if(this._$ui && this._parent){
                    this._$ui.css('height', $(this._parent).height());
                    this._$ui.appendTo(this._parent);
                }
            }
        }
        
        _bindEvent(){
            let lastTop = 0;
            this._$ui.on('scroll', (e) => {
                let target = e.target;
                if(target.scrollHeight - target.scrollTop - 30 <= target.offsetHeight && target.scrollTop > lastTop){
                    if(this._config.totalPage > this.state.currentPage && this.state.loading === false){
                        this._loadData(++this.state.currentPage, this._config.pageSize);
                    }
                }
                lastTop = target.scrollTop;
            });
        }
        
        dispose() {
            super.dispose();
        }
    }
    return ScrollList;
})($);
export default ScrollList;