/*
* Version 1.0
* 2015-12-20 by sullivan
* AJAX Pager
*/
;
(function (window, $) {

    var ms = {
        init: function (obj, args) {
            return (function () {
                $.ajax({
                    type: args.type,
                    //async: true,
                    data: $.extend(args.searchParam || {}, {
                        pageIndex: args.pageIndex,
                        pageSize: args.pageSize || 10
                    }),
                    dataType: args.dataType,
                    url: args.url,
                    beforeSend: function () {
                        if (args.beforeSend != null) {
                            args.beforeSend();
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        args.error(XMLHttpRequest, textStatus, errorThrown);
                    },
                    success: function (data) {
                        args.success(data);

                        //后台返回数据格式：{"total":0,"items":[]}
                        args.pageCount = Math.ceil(data.total / args.pageSize);
                        if (args.pageCount == 0) {
                            args.pageCount = 1;
                        }
                        ms.fillHtml(obj, args);
                        ms.bindEvent(obj, args);
                    },
                    complete: function () {

                        args.complete();
                    }
                });
            })();
        },
        doPage: function (obj, args, index, pageSize, searchParam) {
            args.pageIndex = index;
            args.pageSize = pageSize;
            args.searchParam = searchParam;
            $.ajax({
                type: args.type,
              //  async: true,
                data: $.extend(args.searchParam || {}, {
                    pageIndex: args.pageIndex,
                    pageSize: args.pageSize || 10
                }),
                dataType: args.dataType,
                url: args.url,
                beforeSend: function () {
                    if (args.beforeSend != null) {
                        args.beforeSend();
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    args.error(XMLHttpRequest, textStatus, errorThrown);
                },
                success: function (data) {
                    args.pageCount = Math.ceil(data.total / args.pageSize);
                    if (args.pageCount == 0) {
                        args.pageCount = 1;
                    }
                    args.success(data);
                    ms.fillHtml(obj, { "pageIndex": index, "pageCount": args.pageCount });
                },
                complete: function () {

                    args.complete();
                }
            });
        },
        //填充html
        fillHtml: function (obj, args) {
            return (function () {
                obj.empty();
                var sHtml = "";
                //obj.append('<li>');
                sHtml += '<ul class="pagination pagination-sm m-0 float-right">'
                if (args.pageCount > 1) {
                  
                    if (args.pageIndex != 1) {
                        sHtml += '<li class="page-item"><a href="javascript:;" class="page-link tcdNumber" data_pageIndex="' + (args.pageIndex - 1) + '" >«</a></li>'
                    } else {
                        sHtml += '<li class="page-item"><a href="javascript:;" class="page-link tcdNumber" data_pageIndex="" >«</a></li>'
                    }


                    //中间页码
                    if (args.pageIndex != 1 && args.pageIndex >= 4 && args.pageCount != 4) {
                        sHtml += '<li class="page-item"><a href="javascript:;" class="page-link tcdNumber">' + 1 + '</a></li>';
                    }
                    if (args.pageIndex - 2 > 2 && args.pageIndex <= args.pageCount && args.pageCount > 5) {
                        sHtml += '<li class="page-item"><span class="page-link">...</span>';
                    }
                    var start = args.pageIndex - 2, end = args.pageIndex + 2;
                    if ((start > 1 && args.pageIndex < 4) || args.pageIndex == 1) {
                        end++;
                    }
                    if (args.pageIndex > args.pageCount - 4 && args.pageIndex >= args.pageCount) {
                        start--;
                    }
                    for (; start <= end; start++) {
                        if (start <= args.pageCount && start >= 1) {
                            if (start != args.pageIndex) {
                                sHtml += '<li class="page-item"><a href="javascript:;" class="page-link tcdNumber">' + start + '</a></li>';
                            } else {
                                sHtml += '<li class="page-item active"><a class="page-link">' + start + '</a></li>';
                            }
                        }
                    }
                    if (args.pageIndex + 2 < args.pageCount - 1 && args.pageIndex >= 1 && args.pageCount > 5) {
                        sHtml += '<li class="page-item"><span class="page-link">...</span></li>';
                    }
                    if (args.pageIndex != args.pageCount && args.pageIndex < args.pageCount - 2 && args.pageCount != 4) {
                        sHtml += '<li class="page-item"><a href="javascript:;" class="page-link tcdNumber">' + args.pageCount + '</a></li>'
                    }
                    if (args.pageCount >= (args.pageIndex + 1)) {
                        sHtml += '<li class="page-item"><a href="javascript:;" class="page-link tcdNumber" data_pageIndex="' + (args.pageIndex + 1) + '">»</a></li>'
                    } else {
                        sHtml += '<li class="page-item"><a href="javascript:;" class="page-link tcdNumber" data_pageIndex="">»</a></li>'
                    }
                } else {
                    sHtml += '<li class="page-item"><span class="page-link">«</span></li>';
                    sHtml += '<li class="page-item active"><span class="page-link">1</span></li>';
                    sHtml += '<li class="page-item"><span class="page-link">»</span></li>';
                }
                sHtml += '</ul>'

                //sHtml += '<span>共' + args.pageCount + '页</span>';
                obj.append(sHtml);

            })();
        },
        //绑定事件
        bindEvent: function (obj, args) {
            return (function () {
                obj.unbind("click");
                obj.on("click", "a.tcdNumber", function () {
                    var pageIndex = parseInt($(this).text());
                    if (isNaN(pageIndex)) {
                        pageIndex = parseInt($(this).attr("data_pageIndex"));
                    }
                    if (!isNaN(pageIndex)) {
                        //ms.fillHtml(obj, { "pageIndex": pageIndex, "pageCount": args.pageCount });
                        if (typeof (args.backFn) == "function") {
                            args.backFn(pageIndex);
                        } else {
                            ms.doPage(obj, args, pageIndex, args.pageSize, args.searchParam);
                            //alert(pageIndex);
                        }
                    }
                });
            })();
        }
    }
    //保存数据
    var mydata = {}

    $.fn.sjAjaxPager = function (type, options) {

        var gettype = Object.prototype.toString

        if (gettype.call(type) == "[object Object]") {
            var args = {
                url: "", //url
                type: "POST",  //提交分数
                dataType: "JSON",  //格式
                searchParam: {},  //参数
                beforeSend: null,
                success: null,
                complete: null,
                error: function () {
                    alert("抱歉,请求出错,请重新请求！");
                },
                pageSize: 10,    //每页显示    
                pageIndex: 1,   //当前页码
                pageCount: 0,   //总共多少页             
                backFn: null,  //自定义点击时间
            };
            var data = $.extend({}, args, type);
            mydata[$(this).attr('id')] = data;
            ms.init(this, data);

        } else if (type.toLowerCase() == 'load') {   //通过传递一些参数执行一次查询，通过调用这个方法从服务器加载新数据。
            var data = mydata[$(this).attr('id')];
            data.searchParam = options;
            ms.doPage(this, data, 1, data.pageSize, data.searchParam);
        } else if (type.toLowerCase() == 'reload') {   //刷新当前页
            var data = mydata[$(this).attr('id')];
            ms.doPage(this, data, data.pageIndex, data.pageSize, data.searchParam);
        }
    }

})(window, jQuery);