var mCurrentPage = 0;//当前页
var mIsLoading = false;
var lineHeight = 70;
var mListView = null;

function init() {
    //绑定虚拟列表
    bindVirtualList();
    //绑定搜索栏
    bindSearchBar();
    //加载列表
    loadList();
}

function bindSearchBar(){
    mySearchbar = myApp.searchbar(
        '.searchbar',
        {
            customSearch: true,
            onSearch:function(){
                //输入后， 重新加载列表
                loadList();
            }
        }
    );
}

function bindVirtualList() {
    mListView = myApp.virtualList('#notice-list', {
        items: [],
        height: function (item) {
            return lineHeight;
        },
        renderItem: function (index, item) {
            return renderItem(index, item);
        },
    });

    var refreshContent = $('.pull-to-refresh-content');
    refreshContent.off('refresh');
    refreshContent.on('refresh', function (e) {
        mCurrentPage = 0;
        console.log("执行了下拉刷新");
        myApp.pullToRefreshDone();
        loadList();
        setTimeout(function () {
            myApp.pullToRefreshDone();
        }, 20000);
    });
}

function renderItem(index, item) {
    var itemHtml = Template7.templates.noticeItem(item);
    itemHtml = itemHtml.replace(/[\r\n]/g, "");
    itemHtml = itemHtml.trim();
    return itemHtml;
}

function loadList(){
    var txt = $('#search-input').val();
    var params = {
        'page': mCurrentPage,
        'txt' : txt
    };

    odoo.rpcCall('ws.fd.notice', 'mobile_read_list', [params], {}, function (result) {
        mIsLoading = false;
        myApp.pullToRefreshDone();

        if (mCurrentPage == 0) {
            mListView.deleteAllItems();
        }

        mListView.appendItems(result);

        $(".infinite-scroll-preloader").hide();
    });
}

$('.infinite-scroll').on('infinite', function () {
    if (mIsLoading) {
        return;
    }
    if (mCurrentPage > 10) {
        $('.infinite-scroll-preloader').hide();
        return;
    }
    mIsLoading = true;
    setTimeout(function () {
        mIsLoading = false;
        $('.infinite-scroll-preloader').hide();
    }, 20000);
    mCurrentPage++;
    loadList();
});

function onView(notice_id) {
    mainView.router.load({
            'url': '/m_ws/fd/notice/view?notice_id=' + notice_id + "&t=" + new Date().getTime(),
            'reload': false,
            'animatePages': true,
            'pushState': true
        });
}

function onBack() {
    mainView.router.back({'reload': true, 'animatePages': true});
}


init();