/*
 *
 *使用方法
 *
 *<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 pagesizes=[10,20,30,50,100];
    var select=[];
    pagesizes.forEach(function(page){
        select.push("<option value="+page+">"+page+"条</option>");
    });
    var defaults = {
        hash: true,
        //size: 10,
        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>" +
        "<div class='t_foot'><ul class='pagination' style='float: left; margin: 10px 0'></ul><select class='form-control t_size' style='display:none; width: 80px; height: 32px; padding: 0 10px; float: left; margin: 10px 0 10px 10px'>" +select.join('') + 
        "</select><span class='label label-info t_total' style='display:none; width: 80px; height: 32px; float: left; padding: 10px; margin: 10px 0 10px 10px'></span></div>",
        nav: true,
        tabUrl: false,
        pagesizes:pagesizes,
        usepagesize:false,
        showtotalsize:false,
        page: 1
    };
    this.options = $.extend({}, defaults, options);
    this.response={};
}

grid.prototype = {
    constructor: grid,

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

        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.foot=$(".t_foot", g.grid);
        if(p.usepagesize){
            $(".t_size", g.foot).show();
        }
        if(p.showtotalsize){
            $(".t_total", g.foot).show();
        }
        g.pagination = $(".pagination", g.grid);
        g.records = [];
        g.rows = [];
        g.selected = [];

        g.clear();
        g.renderHead();
        g.renderBody();
        g.bindEvent();
    },

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

        if (g.grid) {
            g.grid.html("");
            g.grid = null;
            g.table = null;
            g.thead = null;
            g.pagination = null;
            g.clear();
        }
    },

    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);
                g.foot.hide();
            }

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

        var param = {},
            urlParam = {};

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

        if (param.page !== p.page) {
            param.page = p.page;
        } else {

            if (location.hash.search(/page=(\d+)/g) > -1) {
                param.page = /page=(\d+)/g.exec(location.hash)[1];
            }

        }
        if (param.page && p.hash) {
            if (location.hash.search(/page=(\d+)/g) > -1) {
                location.hash = location.hash.replace(/page=(\d+)/g, function(source, $1) {
                    return "page=" + param.page;
                })
            } else {
                location.hash += "page=" + param.page;
            }
        }


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

        if (param.isInfoMiss == 'N') {
            param.isInfoMiss = '';
        }

        if (p.size) {
            param.size = p.size;
        }

        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;
            }
        });
        if(!pagination.total){
            g.foot.hide();
        }else{
            g.foot.show();
            if(p.size){
                $(".t_size",g.foot).val(p.size);
            }
            
            if(p.nopage){
                $(".t_size",g.foot).hide();
            }
        }

    },
    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.style) {
            c.attr("style", column.style);
        }

        if (column.name) c.attr({
            columnname: column.name
        });
        var h_t = column.display || "";
        c.html(h_t);
        var input_class=column._class||"wqt_all";
        if (column.type) c.html("<input type='" + column.type + "' class='"+input_class+"' />");
        return column.hidden ? "" : c;
    },
    ajax: function(param) {
        var g = this,
            p = this.options;
        var timeid;
        if(p.url.indexOf('?')==-1){
            p.url+="?";
        }
        p.url+="_datetime_="+Date.now();

        var ajaxOptions = {
            type: 'POST',
            url: p.url,
            async: (typeof p.async == "boolean") ? p.async:true,
            data: param,
            dataType: 'json',
            beforeSend: function() {
                //发送请求
                g.tbody.html("<tr><td colspan=100><center>正在加载中...</center></td></tr>");
            },
            success: function(res) {
                var data = res.data;
                //add by chenchao
                g.response=data;
                p.callback && (data = p.callback(res)); //data.data,data.data1

                g.__pagination({
                    total: data.totalPage,
                    page: data.page
                });
                if(data.list){
                    g.__bodyClomun(data.list, p.second);
                }else{
                    g.__bodyClomun([], p.second);
                }
                g.total = data.total?data.total:0;
                $(".t_total", g.foot).text("共" + g.total + "条");
                p.complete2 && p.complete2(res);
            },
            complete: function(res) {
                console.log("gridComplete~~");
                 //p.complete && p.complete();
            },
            error: function(res) {
                console.log("gridError~~", 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(''));
        }
        $(".wqt_all").prop("checked",false);
        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 && !col.render ) {
            if(col.typeAttr){
                content = "<input type='" + col.type + "'  checked='"+col.typeAttr+"'   name='" + col.name + "' class='wqt_checkbox' data-index='" + row.__index + "'>";
            }else{
                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;
            var selectedCb = p.selectedCallback,
            unselectedCb = p.unselectedCallback;

        //$(".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) {
                    /**************业务控制 特殊情况**************/        
                    if(selectedCb && typeof selectedCb === 'function') {
                        selectedCb(g.rows[index]);
                    }   
                    /*********************************************/
                    g.selected.push(g.rows[index]);
                }else{
                    /**************业务控制 特殊情况**************/
                    if(unselectedCb && typeof unselectedCb === 'function') {
                        unselectedCb(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;
            var selected = true;  

            /************业务控制 特殊情况****************/
            if($(this).prop("checked")){
                if(selectedCb && typeof selectedCb === 'function') {
                    selectedCb(g.rows[$(this).attr("data-index")]);
                }
            }else{
                if(unselectedCb && typeof unselectedCb === 'function') {
                    unselectedCb(g.rows[$(this).attr("data-index")]);
                }
             
            }            
            /********************************************/

            $(".wqt_checkbox").each(function() {
                var checked = $(this).prop("checked");
                var index = $(this).data("index");
                if (checked) {                    
                    g.selected.push(g.rows[index]);                                                
                } else {                                      
                    selected = false;
                }
            });
            $(".wqt_all").prop("checked", selected);
        });

        $(g.grid).on("change",".t_size",function(){
            p.size=$(this).val();

            // 将当前页面size保存起来
            if (location.hash.search(/size=(\d+)/g) > -1) {
                location.hash = location.hash.replace(/size=(\d+)/g, function(source, $1) {
                    return "size=" + p.size;
                })
            } else {
                location.hash += "&size=" + p.size;
            }

            g.reload(1);
        })
    }
}

module.exports = grid;