(function($) {
    'use strict';

    var con;
    var options;
    var curDatas;
    var element;
    var obj;
    /**
     * Datatable class
     * 
     * @param object element           DOM element or jquery element
     * @param object options           Datatable options
     */
    var mytable = function(element, options, flag) {
        // default options
        var DEFAULTS = {
            isShoWPager:true,
            pager:{
                page_size:10
            }
        };
        this.options = $.extend({}, DEFAULTS, options);
        this.element = element;
        // this.options = options;
        this.pager = options.pager;
        this.con = $(element);
        this.obj = this;
        $(element).html('');
        if(flag) return;
        $(element).append('<div class="row"><div id="my_table" data-checkable="true" data-sortable="true"></div></div>'
                           + '<div id="kkpager" class="row" style="text-align:center"></div>');
        this.getRemoteData(element,this.options,this);
        return this;       
    };

    // Get options
    mytable.prototype = {
        getRemoteData:function(element,options,obj){
            if(!element) element = this.element;
            if(!options) options = this.options;
            var url = options.url;
            var p_cur = 1;
            var pager = options.pager;
            this.getServerData(p_cur, options, element, obj);
        },
        getRemoteData1:function(p_cur){
            this.getServerData(p_cur, this.options, this.element, this.obj);
        },
        getServerData:function(p_cur, options, element, obj){
            var url = options.url;
            var pager = options.pager;
            var page_size = pager.page_size;
            var param = options.param;
            // var obj = this.obj;
            post_common_service(url+"/"+p_cur+"/"+page_size, param, function(data) {
                console.log(data);
                if(!data){
                    data = {list:[]};
                    // return;
                }
                 // 这边把请求过来的数据缓存到table选择器中
                $(element).data("data_cache",data.list);
                element.tt_data=data.list;
                options.tableData=data.list;
                obj.setTable(data.list,element, options,p_cur); 
                if(obj.options.pager){
                    options.pager = {
                        page_size:10,
                        p_cur : data.pageNum, //页号
                        p_pages:data.pages, //总页码
                        p_totalRecords:data.total
                        // 'cb':'getRemoteData
                    }   
                    obj.setPager();
                }
                if(data.list.length<=0){
                    $("#kkpager").css("display","none");
                }else{
                    $("#kkpager").css("display","block");
                }
            }, function(error) {
                alert(error);
            });
        },
        setTable:function(datas, element, options,p_cur) {
            var cols = options.cols;
            var newCols = []
            for(var i in cols) {
                if(!cols[i].hide){
                    newCols.push(cols[i]);
                }
            }
            cols = newCols;
            var tableData = datas;
            // var pager = options.pager;
           
            clearTable(cols);
            var rowData = formatTableData(tableData, cols, p_cur);

            // 使用data参数更新数据：
            $('#my_table').datatable('load',{
                    cols: cols,
                    rows:rowData
                }
            );
            function formatTableData(data,cols,p_cur){
                var rows = [];
                for(var i=0;i<data.length;i++){
                    data[i].num=(p_cur-1)*10+i+1;
                    rows.push(genRow(data[i],cols));
                }
                return rows;
            }

            function genRow(obj,cols){
                var row = {checked: false, data:null};
                var dArr=[];
                for(var i=0;i<cols.length;i++){
                    if(cols[i].func!=null){
                        dArr.push(cols[i].func(obj[cols[i].field]));
                    }else if(cols[i].type=="imagedd"){
                        var pics = obj[cols[i].field];
                        var picStr='';
                        if(pics){
                            var picArr = pics.split(',');
                            for(var j in picArr){
                                var pic =  '<a class="lightbox-toggle" href="'+picArr[j]+'" style="width:60px;height:50px;">'
                                    +      '<img class="pic-class  img-thumbnail" style="width:60px;height:50px;" src="'+picArr[j]+'" alt="">'
                                    +  '</a>';
                                picStr+=pic;
                            }
                        }
                        dArr.push(picStr);
                    }else if(cols[i].oper!=null) {
                        var oper = cols[i].oper;
                        var operStr="";
                        for(var j=0;j<oper.length;j++){
                            operStr+='&nbsp;<a href="#" onclick="'+oper[j].func+'('+obj[cols[i].field]+','+obj[cols[i].field_other]+')"><i class="icon '+oper[j].icon_class+'"></i>'+oper[j].text+' </a>&nbsp;';
                        }
                        dArr.push(operStr);
                    }else{
                        if(cols[i].type == "date"){
                            if(cols[i].custom){
                                dArr.push(timeStamp2String(obj[cols[i].field],cols[i].date_type) + cols[i].custom);
                            }else{
                                dArr.push(timeStamp2String(obj[cols[i].field],cols[i].date_type));
                            }
                        
                        }else if(obj[cols[i].field]){
                            if(cols[i].custom){
                                dArr.push(obj[cols[i].field] + cols[i].custom);
                            }else{
                                dArr.push(obj[cols[i].field]);
                            }
                        }else{ 
                            dArr.push('0');
                        }
                    }
                    
                }
                row.data=dArr;
                return row;
            }
            function clearTable(cols){
                $('#my_table').datatable( {
                    checkable:false,
                    sortable:false,
                    data: {
                        cols: cols,
                        rows:[]
                    }
                });
            }
        },
        setPager:function(data) {
            var pager = this.options.pager;
            var p_cur = pager.p_cur;
            var p_pages = pager.p_pages;
            var p_totalRecords = pager.p_totalRecords;
            var obj=this;
            kkpager.generPageHtml({
                pno : p_cur,
                total : p_pages,
                totalRecords : p_totalRecords,
                mode : 'click',
                click : function(n){
                    obj.options.pager.p_cur = n;
                    this.selectPage(n);
                    obj.getRemoteData1(n);//调用获取数据方法
                    return false;
                }
            },true);
        }
    };

    $.fn.mytable = function(options) {
        if (typeof options == 'string') {
            switch (options) {
                case 'getTableData': 
                    return this[0].tt_data;
                case 'empty': 
                    return new mytable(this,options,true);
            }
         }   else{
        return this.each(function() {
            // var $this = $(this);
                new mytable(this,options);
            //  $(this).attr('tableData',mytable.tableData);
            });
        }
    };


    $.fn.mytable.Constructor = mytable;
}(jQuery));

