$("#interval").val("月份");
$(function () {
    //默认为月份统计
    refresh();
});
var height = $(window).height() - 75;

//点击查询按钮
$("#query").on("click", function () {
    refresh();
});

//实现全选功能
$("#all_checked").click(function () {
    $('[name=test]:checkbox').prop('checked', this.checked);//checked为true时为默认显示的状态
});

$("#delete").click(function () {
    var indexs = [];
    var $checkboxs = $("[name=test]:checked");
    var length = $checkboxs.length;
    if (length === 0) {
        layer.msg('至少选则一条短信', {icon: 2, time: 2000});
    } else {
        for (var i = 0; i < length; i++) {
            indexs.push($checkboxs.eq(i).val())
        }
        startDel(indexs);
    }
})

/**
 * 初始化获取后台数据
 */
function refresh() {
    /*获取各项条件 */
    var startTime = $("#startTime").val();
    var endTime = $("#endTime").val();
    var msgtype = $("#msgtype").val()

    var indexi;
    $.ajax({
        type: "get",
        url: "/pqs9900/message/getAllMsgList",
        dataType: "json",
        data: {
            startTime: startTime,
            endTime: endTime,
            type: msgtype
        },
        beforeSend: function () {
            indexi = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            if (data.code === 200) {
                //初始化表格
                initTransactionTable(data.body);
            } else {
                layer.msg(data.message, {icon: 2, time: 2000})
                initTransactionTable(null);
            }
            ityzl_CLOSE_LOAD_LAYER(indexi);
        }
    })
}


var dataTable;

//初始化表格数据
function initTransactionTable(tableData) {
    var tableHeight = height - 75;
    var length = Math.floor(tableHeight / 32);
    if (length < 1) {
        length = 1;
    }
    var tableCellHeight = 32 * length+30;
    dataTable = $("#message").DataTable();
    dataTable.clear().draw();
    dataTable = $('#message').DataTable({
        order: [],
        columnDefs: [
            {
                orderable: false,
                targets: [0]
            }
        ],
        columns: [
            {
                width: "1%", data: "msgIndex",
                render: function (data, type, full, meta) {
                    return "<input type ='checkbox' name='test' class='icheckbox_minimal' value='" + data + "'>";
                }
            },
            {width: "18%", data: "sendTime",render:function (data,type) {
                    if (data == null) {
                        return '';
                    } else {
                        var date = new Date(data);
                        var y = date.getFullYear();// 年
                        var MM = date.getMonth() + 1;// 月
                        MM = MM < 10 ? ('0' + MM) : MM;
                        var c = date.getDate();// 日
                        c = c < 10 ? ('0' + c) : c;
                        var h = date.getHours();// 时
                        h = h < 10 ? ('0' + h) : h;
                        var m = date.getMinutes();// 分
                        m = m < 10 ? ('0' + m) : m;
                        var s = date.getSeconds();// 秒
                        s = s < 10 ? ('0' + s) : s;
                        return y + '-' + MM + '-' + c + ' ' + h + ':' + m + ':' + s;
                    }
                }},
            {width: "10%", data: "name"},
            {width: "10%", data: "phone"},
            {width: "69%", data: "msgContent"},
        ],
        destroy: true,
        data: tableData,
        lengthChange: false,
        searching: true,
        dom: 'rtip',
        scrollY: tableCellHeight,
        scrollX: true,
        autoWidth:true,
        lengthMenu: [length],
        language: {
            url: '/pqs9900/json/chine.json'
        },
        fnDrawCallback: function (oTable) {
            $("#message_info").attr('style','margin:0 0 0 0;float:left')
            $("#message_paginate").attr('style','20px 0 0 0 !important;float:right')

            $("#message_paginate").append("<div style='float:right;padding-top:4px;padding-left:10px'>到第 <input type='text' id='changePage' class='input-text' style='width:50px;height:28px;'> 页  <button class='btn btn-primary' id='dataTable-btn'>确定</button></div>");
            var table = $("#message").dataTable();
            $('#dataTable-btn').click(function (e) {
                if ($("#changePage").val() && $("#changePage").val() > 0) {
                    var redirectpage = $("#changePage").val() - 1;
                } else {
                    var redirectpage = 0;
                }
                table.fnPageChange(redirectpage);
            });

        },
        createdRow: function( row, data, dataIndex ) {
            $(row).children('td').attr('style', 'vertical-align: middle;')
            $(row).children('td').eq(4).attr('style', 'vertical-align: middle;text-align:left')
        },
    });
    new $.fn.dataTable.Buttons(dataTable, {
        buttons: [
            {
                extend: 'csv',//导出格式
                title: '短信列表',//导出csv名称
                exportOptions: {
                    columns: [0,1, 2, 3, 4],//导出需要的列
                    format: {
                        body:function(data,rID,cID){
                            if(cID===0){
                                return rID+1;
                            }else if(cID ===1){
                                return '\t'+data+'\t'
                            }
                            else{
                                return data;
                            }
                        }
                    }
                }
            }
        ]
    });
    modifyCss(dataTable)
}

function modifyCss(dataTable){
    dataTable.buttons().container().css("padding","0px 5px");
    dataTable.buttons().container().css("float","right");
    dataTable.buttons().container().find("a").prepend("<i class='glyphicon glyphicon-share'></i>");
    dataTable.buttons().container().appendTo('.bbbb');
}

//搜索表中的数据
function searchResult(value) {
    dataTable.search(value).draw();
}

function startDel(indexs) {
    layer.confirm('确认要删除吗？', function () {
        $.ajax({
            type: 'POST',
            dataType: "json",
            contentType: 'application/json;charset=UTF-8',
            url: '/pqs9900/message/deleteMsgList',
            data: JSON.stringify(indexs),
            success: function (data) {
                if (data.code == 200) {
                    refresh()
                    layer.msg('删除成功', {icon: 1})
                } else {
                    layer.msg('删除失败', {icon: 2})
                }

            },
            error: function () {
                layer.msg('未知错误', {icon: 2})
                return false
            }

        })
    })
}



