grid.js 10.7 KB
/*
 *
 *使用方法
 *
 *<div id="id"></div>
 **/

/*var g=new grid({
    el:"#id",
    columns:[
        {display:"性别",name:"sex"},
        {display:"全名",name:"name",render:function(item){
            return item.xingshi+item.name;
        }}
    ]

});
g.init('url');*/


var $ = require('jquery');
require('../util/jquery.simplePagination');

var grid = function(options) {
    var defaults = {
        hash: true,
        //size: 10,
        innerHtml: "<div class='grid'><table class='table table-striped table-bordered responsive dataTable no-footer' role='grid' aria-describedby='basicTable_info'>" + "<thead></thead><tbody></tbody></table></div>" + "<nav><ul class='pagination'></ul></nav>",
        nav: true,
        tabUrl: false
    }
    this.options = $.extend({}, defaults, options);

}

grid.prototype = {
    constructor: grid,

    init: function(url, second) {
        var g = this,
            p = this.options;


        p.url = url;
        p.second = second;
        g.grid = $(p.el);
        g.grid.html(p.innerHtml);
        g.table = $("table", g.grid);
        g.thead = $("thead", g.grid);
        g.tbody = $("tbody", g.grid);
        g.pagination = $(".pagination", g.grid);
        g.records = [];
        g.rows = [];
        g.selected = [];

        g.clear();
        g.renderHead();
        g.renderBody();
        g.bindEvent();
    },
    renderBody: function() {
        var g = this,
            p = this.options;
        g.__bodyload();
    },
    __bodyload: function() {
        var g = this,
            p = this.options;
        var _p = g.__getparams();
        if (_p == null) {
            var json = {
                page: 0,
                total: 0
            };
            g.__pagination(json);
            return;
        } else {
            g.clear();
            if (typeof p.url == "string") {
                g.ajax(_p);
            } else {
                g.__bodyClomun(p.url, p.second);
            }

        }
    },
    __getparams: function() {
        var g = this,
            p = this.options;

        var param = {},
            urlParam = {},
            urlArr = location.hash.substring(1).split('&&');

        if (p.parms) {
            if (typeof(p.parms) == "function") {
                param = p.parms();
            }
        }

        $.each(urlArr, function(i, value) {
            var result = value.split('='),
                key = result[0],
                value = result[1];
            if (key) {
                urlParam[key] = value;
            }
        });

        $.each(urlParam, function(key, value) {
            if (!param[key] && param[key] !== +param[key]) {
                param[key] = value;
            }
        });
        if (param.page !== p.page) {
            param.page = p.page;
        } else {
            param.page = urlParam.page;
        }

        if (param.productStatusStr == 'all') {
            param.productStatusStr = '';
        }

        if (param.isInfoMiss == 'N') {
            param.isInfoMiss = '';
        }
        var urlHash = '';
        $.each(param, function(key, value) {
            if (value || value == '0') {
                urlHash += key + '=' + value + '&&';
            }
        });
        if (p.hash) {
            location.hash = urlHash;
        }

        return param;
    },
    __pagination: function(pagination) {
        var g = this,
            p = this.options;
        g.pagination.pagination({
            items: pagination.total,
            itemsOnPage: 5,
            pages: pagination.total,
            currentPage: pagination.page,
            edges: 1,
            hrefTextPrefix: '#page=',
            ellipsePageSet: false,
            onPageClick: function(pageNumber, event) {
                p.page = pageNumber;
                g.renderBody();
                return false;
            }
        });
    },
    renderHead: function() {
        var g = this,
            p = this.options;
        g.__headerClomun();
    },
    clear: function() {
        var g = this,
            p = this.options;
        g.tbody.html("");
        g.records = [];
        g.rows = [];
        g.selected = [];
    },
    __headerClomun: function() {
        var g = this,
            p = this.options;
        var tr = $("<tr></tr>");
        $(p.columns).each(function(i, column) {
            var td = g.__headerCell(column);
            tr.append(td);
        })
        g.thead.append(tr);
    },
    __headerCell: function(column) {
        var g = this,
            p = this.options;
        var c = $("<th></th>");
        if (column.width) {
            c.attr("width", column.width);
        }
        if (column.name) c.attr({
            columnname: column.name
        });
        var h_t = column.display || "";
        c.html(h_t);
        if (column.type) c.html("<input type='" + column.type + "' class='wqt_all' />");
        return column.hidden ? "" : c;
    },
    ajax: function(param) {
        var g = this,
            p = this.options;
        var timeid;
        var ajaxOptions = {
            type: 'POST',
            url: p.url,
            data: param,
            dataType: 'json',
            beforeSend: function() {
                //发送请求
            },
            success: function(res) {
                var data = res.data.data;
                p.callback && (data = p.callback(res.data)); //data.data,data.data1

                g.__pagination({
                    total: data.totalPage,
                    page: data.page
                });
                g.__bodyClomun(data.list, p.second);
            },
            complete: function(res) {
                console.log("complete~~");
                // p.complete && p.complete();
            },
            error: function(res) {
                console.log("error~~", res);
                clearTimeout(timeid);
                if (res.status == 429) {
                    timeid = setTimeout(function() {
                        g.reload();
                    }, 800);
                }
                g.__pagination({
                    total: 0,
                    page: 0
                });
            }
        };
        $.ajax(ajaxOptions);
    },
    __bodyClomun: function(rows, second) {
        var g = this,
            p = this.options;
        g.tbody.html("");
        if (!rows) {
            return "";
        };
        var _r = [],
            _count = 0;

        function _r_num() {
            return (p.page - 1) * parseInt(p.rp);
        }



        if (rows.length > 0) {
            for (var row in rows) {
                var item = rows[row],
                    _h = "";
                var num = _r_num() + _count;

                item._num = _count;
                item.rowid = "wqt_" + num + "_" + _count;
                if (!item) continue;
                g.records.push(_count);
                item.__index = _count;
                g.rows.push(item);

                if (item[second] && item[second].length > 0) {
                    _h += g.__bodySecondClomun(item, item[second])
                } else {
                    _h += ('<tr >');
                    $(p.columns).each(function(i, column) {
                        if (!column.hidden) {
                            _h += ('<td>');
                            _h += (g.__bodyCell(item, column));
                            _h += ('</td>');
                        }
                    })
                    _h += ('</tr>');
                    _count++;
                }

                _r.push(_h);
                g.tbody.html(_r.join(''));
            }
        } else {
            var _h = "";
            _h += ('<tr >');
            _h += ('<td colspan=' + p.columns.length + '>');
            _h += ('<p class="nodata-tip">' + (p.msg ? p.msg : "没有查询到数据") + '</p>');
            _h += ('</td>');
            _h += ('</tr>');
            _r.push(_h);
            g.tbody.html(_r.join(''));
        }
        p.complete && p.complete();
    },
    __bodySecondClomun: function(row, second) {
        var g = this,
            p = this.options,
            index = this.options.secondIndex;
        var _r = '',
            count = 0;

        $.each(second, function(i, value) {
            _r += '<tr>';
            $(p.columns).each(function(i, column) {
                if (!column.hidden && count < index) {
                    _r += ('<td rowspan="' + second.length + '">');
                    _r += (g.__bodyCell(row, column));
                    _r += ('</td>');
                    count++;
                } else {
                    if (i >= index) {
                        _r += ('<td>');
                        _r += (g.__bodyCell(value, column));
                        _r += ('</td>');
                    }
                }
            });
            _r += '</tr>';
        });

        return _r;
    },
    __bodyCell: function(row, col) {
        var g = this,
            p = this.options;
        if (!row || !col) return "";
        var value = col.name ? row[col.name] : null;

        var content = "";
        if (col.type) {
            content = "<input type='" + col.type + "' name='" + col.name + "' class='wqt_checkbox' data-index='" + row.__index + "'>";
        } else if (col.render) {
            content = col.render.call(g, row, value, col);
        } else {
            content = value;
        }
        if (content || typeof(content) == 'number') {
            return content;
        } else {
            return '';
        }
    },
    reload: function(param) {
        var g = this,
            p = this.options;

        if (param == 1) {
            p.page = 1;
        }
        g.__bodyload();
    },
    bindEvent: function() {
        var g = this,
            p = this.options;
        //$(".wqt_all",g.grid).change(function(){
        $(g.grid).on("change", ".wqt_all", function() {
            var selected = $(".wqt_all").prop("checked");
            $(".wqt_checkbox").prop("checked", selected);
            g.selected.length = 0;
            $(".wqt_checkbox").each(function() {
                var checked = $(this).prop("checked");
                var index = $(this).data("index");
                if (checked) {
                    g.selected.push(g.rows[index]);
                }
            });

        }); //g.selected
        //$(".wqt_checkbox").prop("checked",true);
        $(g.grid).on("change", ".wqt_checkbox", function() {
            $(".wqt_all").prop("checked", false);
            g.selected.length = 0;
            $(".wqt_checkbox").each(function() {
                var checked = $(this).prop("checked");
                var index = $(this).data("index");
                if (checked) {
                    g.selected.push(g.rows[index]);
                }
            });
        });
    }
}

module.exports = grid;