/**
 * jquery 滚动分页
 * Copyright (c) 2020 xiaofanku
 * build on jQuery 3.2.1 & BootStrap v3
 * @author xiaofanku <xiaofanku@live.cn>
 * @version 0.0.1 - 20200311
 *
*/
(function($) {
    'use strict';
    //防止重复请求的
    var timer=0;
    var scrollPagination = {
        /**
         * 合成配置参数
         * @param {Object} option - 配置参数
         * @returns {Object}
         */
        init:function(option){
            var config=$.extend({pageSize:20, totalRecords:0, page:1, range:5, url: '', dataType: 'json'}, option);
            return config;
        },
        /**
         * 计算有多少页
         * @param {number} totalRecords - 总记录数
         * @param {number} pageSize - 每页显示的记录数
         * @returns {Object}
         */
        getTotalPage: function(totalRecords, pageSize){
            var tp = 1;
            if(totalRecords > pageSize){
                var tp = Math.floor(totalRecords / pageSize);
                if(totalRecords % pageSize !== 0){
                    tp+=1;
                }
            }
            return {
                pageSize : pageSize,
                pages : tp,
                records : totalRecords
            };
        },
        /**
         * 获取数据
         * @param {string} requestURI - 异步请求的地址
         * @param {string} dataType - 请求的数据类型, json|jsonp
         * @param {number} pageSize - 每页显示的记录数
         * @param {number} page - 当前页码值
         * @param {Object} jqEle - 当前的jQuery元素
         */
        getData: function(requestURI, dataType, pageSize, page, jqEle){
            var self = this; //self.disable();
            var formatAjaxParams = {
                type: 'get',
                cache: false,
                data: {},
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                dataType: dataType,
                async: true,
                timeout: 3000
            };
            formatAjaxParams.url = requestURI;
            var postData = {};
                postData.pageSize = pageSize;
                postData.pageNumber = page;
            $.extend(formatAjaxParams.data || {}, postData);
            formatAjaxParams.success = function(response){
                var currentPageNumber = parseInt(page);
                //若大于1,移除上一个哨兵位
                if(currentPageNumber > 1){
                var t='#'+self.sentinel+'-'+currentPageNumber;
                    $(t).remove();
                }
                if($.isFunction(self.jsonCallbackHandler)){
                    self.jsonCallbackHandler(response.result);
                }
                //若存在下一页时插入哨兵,作为下一次的参考位
                var a = self.getTotalPage(response.total, pageSize);
                if(a.pages > currentPageNumber){
                    jqEle.append($('<a>查看更多</a>').addClass(self.sentinel).attr('id', self.sentinel+'-'+(currentPageNumber+1)));
                }
            };
            formatAjaxParams.error = function(jqXHR, textStatus, errorThrown){
            };
            formatAjaxParams.beforeSend = function(xhr) {
                console.log('[ps][pagination] ajax before send exec');
                //若大于1,更新哨兵的内容
                if(page > 1){
                    $('#'+self.sentinel+'-'+page).html('正在玩命的搬运数据');
                }
            };
            formatAjaxParams.complete = function(xhr, textStatus) {
                //记入历史
                recordHistory(page, pageSize);
                console.log('[ps][pagination] ajax is complete');
            };
            $.ajax(formatAjaxParams);
        },
        /**
         * 绑定翻页事件
         * @param {Object} page - 所有的配置参数
         * @param {Object} jqEle - 当前的jQuery元素
         */
        bindEvent: function(finalConfig, jqEle){
            var self = this;
            //一屏的高度(A)
            var maxWindowHeight = parseInt($(window).height());
            //滚动事件绑定
            $(document).on('scroll',function(e) {
                if($('.'+self.sentinel).length == 0){
                    return false;
                }
                //哨兵到顶的高度(B)
                var _pa = Math.floor($('.'+self.sentinel).offset().top);
                //移动的高度(C)
                var scrollTop = Math.floor($(this).scrollTop());
                //出现加载数据的提示条{B-A+浮动值 < C}的值
                if(_pa - maxWindowHeight + 50 < scrollTop){
                    var nextPage = parseInt(getCurrentPageNumber())+1;
                    if(!timer){
                        timer=setTimeout(function(){
                            self.getData(finalConfig.url, finalConfig.dataType, finalConfig.pageSize, nextPage, jqEle);
                            timer=0;
                        },1000);
                    }
                }
            });
            //滚动加载失败
            $('body').on('click', '.'+self.sentinel, function(e){
                e.preventDefault();
                var nextPage = parseInt(getCurrentPageNumber())+1;
                self.getData(finalConfig.url, finalConfig.dataType, finalConfig.pageSize, nextPage, jqEle);
            });           
        }
    };
    $.fn.scrollPagination = function(option) {
        option.page = getCurrentPageNumber();
        var gtx = scrollPagination.init(option);
                  //拿到数据后的回调
                  scrollPagination.jsonCallbackHandler = option.jsonCallback || null;
                  scrollPagination.sentinel = 'pagescroll-pagination'; //哨兵元素
        var _self=this;
        // 没有总记录数
        scrollPagination.getData(gtx.url, gtx.dataType, gtx.pageSize, gtx.page, _self);
        //绑定事件
        scrollPagination.bindEvent(gtx, _self);
        return this;
    };
    //无分页查询字符串返回1,有的返回其值
    function getCurrentPageNumber(){
        //固定的参数:写诗在此(Pagination)
        var pnParam = 'p';
        //当前浏览器地址栏中的查询参数
        var cuQueryString = window.location.search;
        if(cuQueryString){
            var pn = getQueryString(pnParam, cuQueryString);
            return (isBlank(pn))?1:pn;
        }
        return 1;
    };
    //设置历史
    //https://developer.mozilla.org/en-US/docs/Web/API/History/pushState
    function recordHistory(pageNumber, pageSize){
        //固定的参数:写诗在此(Pagination)
        var pnParam = 'p';
        //没有分页参数的地址
        var location = clearPageQueryNameURL();
        //加入
        if(location.indexOf('?')== -1){
            location+='?';
        }else{
            location+='&';
        }
        location+=pnParam+'='+pageNumber;
        //是否考虑页标题中加入第n页
        var pageTitle = document.title;
        var state = {'page_number': pageNumber, 'page_size': pageSize};
        window.history.pushState(state, pageTitle, location);
    };
    //清掉分页参数的地址
    function clearPageQueryNameURL(){
        //固定的参数:写诗在此(Pagination)
        //var pnParam = 'p=';
        //当前浏览器地址栏中的地址
        var cuLocation = window.location.href;
        var cuQueryString = window.location.search;
        if(cuQueryString){
            cuLocation=cuLocation.substring(0, cuLocation.indexOf('?'));
            cuQueryString = cuQueryString.replace(/[?&]p=\d+/g, '').substring(1);
            if(!isBlank(cuQueryString)){
                cuLocation+='?'+cuQueryString;
            }
        }
        return cuLocation;
    };
    /**
     * Get the value of a querystring
     * @param  {String} field The field to get the value of
     * @param  {String} url   The URL to get the value from (optional)
     * @return {String}       The field value
     */
    function getQueryString(field, url) {
        var href = url ? url : window.location.href;
        var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
        var string = reg.exec(href);
        return string ? string[1] : null;
    };
})(jQuery);