String.prototype.replaceAll = function(s1, s2) {
    return this.replace(eval("/" + s1 + "/g"), s2);
};
(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 = {
            checkable: false,
            sortable: false,
            isShoWPager: true,
            pager: {
                page_size: 10
            }
        };
        this.options = $.extend(true, {}, 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=""><div class="my_table" data-checkable="true" data-sortable="true"></div></div>' +
            '<div id="kkpager" class="" 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;
            if (typeof(options.pager.p_cur) != "undefined" && options.pager.p_cur != null) {
                p_cur = options.pager.p_cur;
            }

            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;
            //加载层
            var index = layer.load(2, { shade: false }); //0代表加载的风格，支持0-2
            post_common_service(url + "/" + p_cur + "/" + page_size, param, function(data) {
                // console.log(data);
                layer.close(index);
                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.isShoWPager) {
                    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, options, element);
            var rowData = formatTableData(tableData, cols, p_cur);

            // 使用data参数更新数据：
            $(element).find('.my_table').datatable('load', {
                cols: cols,
                rows: rowData
            });
            // $('#my_table').datatable({checkable: true});

            // $('a.lightbox-toggle').lightbox(); //图片轮播
            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 == "href_link") {

                        var html_1 = cols[i].field;
                        var c_temps = cols[i].field.split("$");
                        for (var w = 0; w < c_temps.length; w++) {
                            var p = c_temps[w];
                            if (p.indexOf("field=") != -1) {
                                var q = p.split("=");
                                html_1 = html_1.replace(p, obj[q[1]]);
                            }
                        }
                        html_1 = html_1.replaceAll("\\$", "");
                        dArr.push(html_1);

                    } else if (cols[i].type == "imagedd") {
                        var pics = obj[cols[i].field];
                        var picStr = '';
                        var num = uuid();
                        if (pics) {
                            var picArr = pics.split(',');
                            for (var j in picArr) {


                                var ispic = true;

                                var src = picArr[j];
                                if (!src.startWith("http"))
                                    src = base_image_server_url + src;

                                var videosrc = src;
                                if (src.indexOf('.avi') != -1) {
                                    src = src.split('.avi')[0] + "_screen_0.png"
                                    ispic = false;
                                }
                                if (src.indexOf('.mov') != -1) {
                                    src = src.split('.mov')[0] + "_screen_0.png"
                                    ispic = false;
                                }
                                if (src.indexOf('.mp4') != -1) {
                                    src = src.split('.mp4')[0] + "_screen_0.png"
                                    ispic = false;
                                }
                                var pic = (ispic ? '<a class="card lightbox-toggle" onclick="img_play(\'' + src + '\')" href="javascript:void(0)" style="width:60px;height:50px;float:left;">' : '<a class="card" onclick="video_paly(\'' + videosrc + '\')" href="javascript:void(0)" style="width:60px;height:50px;">') +
                                    '<img class="pic-class  img-thumbnail" style="width:60px;height:50px;" src="' + src + '" alt="">' + (ispic ? '' : '<i class="icon icon-play-circle" style=" font-size: 30px;position: absolute;top: 10px;left: 15px;color: white;"></i>') +
                                    '</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 += '<a href="javascript:void(0)" class="btn-table" 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] || obj[cols[i].field]==0) {
                            if (cols[i].custom) {
                                dArr.push(obj[cols[i].field] + cols[i].custom);
                            } else {
                                dArr.push(obj[cols[i].field]);
                            }
                        } else {
                            if (cols[i].nullvalue != undefined) {
                                dArr.push(cols[i].nullvalue);
                            } else {
                                dArr.push('-');
                            }
                        }
                    }

                }
                row.data = dArr;
                return row;
            }

            function uuid() {
                var s = [];
                var hexDigits = "0123456789abcdef";
                for (var i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
                s[8] = s[13] = s[18] = s[23] = "-";

                var uuid = s.join("");
                return uuid;
            }

            function clearTable(cols, options, element) {
                var checkable = options.checkable;
                var sortable = options.sortable
                $(element).find('.my_table').datatable({
                    checkable: checkable,
                    sortable: sortable,
                    data: {
                        cols: cols,
                        rows: []
                    },
                    checksChanged: function(event) {
                        var checkArr = event.checks.checks;
                        var checkedIds = [];
                        for (var i = 0; i < checkArr.length; i++) {
                            element.tt_data[i].checked = true;
                            checkedIds.push(element.tt_data[i].id);
                        }
                        element.tt_checkedIds = checkedIds;
                        $(element).data("select_cache", checkedIds);
                        // console.log(element.tt_checkedIds);
                    }
                });
                $(element).find('.table .table-datatable .table-hover').html("");
                // console.log("执行清空");
            }
        },
        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,
                isShowTotalRecords: true,
                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 'getTableCheckedIds':
                    // return this[0].tt_checkedIds;
                    return $(this).data("select_cache");
                case 'empty':
                    return new mytable(this, options, true);
            }
        } else {
            var table = null;
            this.each(function() {
                table = new mytable(this, options);
            });
            return table;
        }
    };


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