var layer = null;
var objTable = null;

layui.use(['layer'], function () {
    layer = layui.layer;
    queryEvents();
});

function queryEvents() {
    layer.ready(function () {
        layerId = layer.msg('数据加载中...', {
            icon: 16,
            shade: [0.5, '#f5f5f5'],
            scrollbar: false,
            time: 10000
        });

        $.ajax({
            type: 'POST',
            dataType: "json",
            url: '/pqs9200/advanced/queryEvents',
            success: function (data) {
                processData(data);
            },
            error: function () {
                layer.msg("事件列表查询失败！");
                CLOSE_LOAD_LAYER(layer, layerId);
            }
        });
    });
}

function processData(data) {
    if (data.code != 0) {
        objTable = initTableBtn($('#tableId'), data, 4);
        CLOSE_LOAD_LAYER(layer, layerId);

        return;
    }

    var tableData = '';
    var offset = 0;

    while (offset < data.object.length) {
        // 后台返回到前台的表格数据
        tableData += '["' + '","' + data.object[offset].strTime + '","'
            + data.object[offset].strTime + '","'
            + data.object[offset].userName + '","' + '","'
            + '"],';

        offset++;
    }

    /*
     * 去除最右边',' string转json
     */
    tableData = tableData.substring(0, tableData.lastIndexOf(','));
    tableData = eval('[' + tableData + ']');

    objTable = initTableBtn($('#tableId'), tableData, 4);
    CLOSE_LOAD_LAYER(layer, layerId);
}

function initTableBtn(obj, tableData, nIndex) {
    var $height = $("body").height() * 0.70;
    var height = $(window).height() - 155;
    var length = Math.floor(height / 28);
    if (length < 1) {
        length = 1;
    }
    var oTable = obj
        .DataTable({
            scrollX: true,
            data: tableData,
            lengthChange: false,
            bDestroy: true,
            ordering: true,
            'searching': true,
            dom: 'lrt<<"myStyle"i><"myStyle"p>>',
            language: {
                url: '/pqs9200/json/chine.json'
            },
            order: [[2, 'desc']],
            scrollY: $height,
            scrollCollapse: true,
            columnDefs: [{
                targets: [0, 4],
                orderable: false
            }],
            pageLength: length,
            createdRow: function (row, data, index) {
                var $btnView = $('<button type="button" class="btn themeBGColor btn-view">删除</button>');
                $('td', row).eq(nIndex).append($btnView);
            },
            fnDrawCallback: function (oTable) {
                $("#tableId_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 = $("#tableId").dataTable();
                $('#dataTable-btn')
                    .click(
                        function (e) {
                            if ($("#changePage").val()
                                && $("#changePage").val() > 0) {
                                var redirectpage = $("#changePage")
                                    .val() - 1;
                            } else {
                                var redirectpage = 0;
                            }
                            table.fnPageChange(redirectpage);
                        });
            }
        });

    oTable.on('draw.dt', function () {
        oTable.column(0, {
            draw: 'applied',
        }).nodes().each(function (cell, i) {
            cell.innerHTML = i + 1;
        });
    }).draw();

    return oTable;
}

$('#tableId').on("click", ".btn-view", function () {
    if (objTable != null) {
        var item = objTable.row($(this).closest('tr')).data();
    }

    var layid = layer.confirm('是否确认删除？', {
        btn: ['删除', '取消']
    }, function () {
        layer.close(layid);
        deleteData(item[2]);
    }, function () {
        layer.close(layid);
    });
});

function deleteData(time) {
    $.ajax({
        type: 'POST',
        dataType: "json",
        data: {
            date: time
        },
        url: '/pqs9200/advanced/deleteEvent',
        success: function (data) {
            if(data.code == 200){
                layer.msg("回退成功",{icon:1,time:1000}, function () {
                    queryEvents()
                })
            }else {
                layer.msg("事件结果回退失败！");
            }

        },
        error: function () {
            layer.msg("事件结果回退失败！");
        }
    });
}

//搜索框内容改变结果记录
function valueChange(value) {
    objTable.search(value).draw();
}
