/*
 * objTable：表格对象
 * count：计数，选中几个子事件
 * arrayGuid:子事件数据
 */

var strTime;
var objTable = null;
var count = 0;
var tabId = -1;
var strName = '';
var layerId = -1;
var layer = null;
var checkboxId = [];
var tableData = [];

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

/*
 * layui加载页面完成时调用方法处理数据 根据归一化处理的GUID查询暂降事件
 */
function queryEventsByGUID(strGUID, name, time, id) {
    layerId = SHOW_LOAD_LAYER(layer);

    strTime = time;
    var obj = new Object();
    var arr = [];
    obj.strGuid = strGUID;
    arr.push(obj);
    tabId = id;
    strName = name;

    document.getElementById("eventName").innerText += name;

    $.ajax({
        type: 'POST',
        dataType: "json",
        data: {
            queryCondition: JSON.stringify(arr)
        },
        url: '/pqs9200/advanced/queryEventsByGUID',
        success: function (data) {
            checkboxId = [];
            tableData = data.object.slice(0);
            processData(data);
        },
        error: function () {
            CLOSE_LOAD_LAYER(layer, layerId);
            layer.msg("事件查询失败！");
        }
    });
}

/*
 * 处理查询的数据
 */
function processData(data) {
    if (data.code != 0) {
    }

    var tableData = '';
    var offset = 0;

    while (offset < data.object.length) {
        // 后台返回到前台的表格数据
        tableData += '["' + data.object[offset].indexEventAss + '","'
            + data.object[offset].indexEventDetail + '","' + '","'
            + data.object[offset].strTime + '","'
            + data.object[offset].plantInfo.nameGD + '","'
            + data.object[offset].plantInfo.nameBD + '","'
            + data.object[offset].plantInfo.namePoint + '","'
            + data.object[offset].voltage + '","'
            + data.object[offset].strEventValue + '","'
            + data.object[offset].strPersist + '","'
            + data.object[offset].sagType + '","'
            + data.object[offset].sagReason + '","' + '' + '"],';

        offset++;
    }

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

    objTable = initTableCheck($('#tableId'), tableData, 0);
    CLOSE_LOAD_LAYER(layer, layerId);
}

/*
 * 行内按钮 obj:表格对象 tableData:表格数据 nIndex:checkbox添加的列
 */
function initTableCheck(obj, tableData, nIndex) {
    var $height = $("body").height() * 0.75;
    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>>',
            scrollY: $height,
            scrollCollapse: true,
            columnDefs: [{
                targets: [0, 1],
                visible: false
            }, {
                targets: [2, 3],
                orderable: false
            }],
            pageLength: length,
            language: {
                url: '/pqs9200/json/chine.json'
            },
            createdRow: function (row, data, index) {
                if (index == 0) {
                    $(row).css("color", "red");
                }
            },
            '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);
                        });
            }
        });

    var tableName = strName + '_' + time2String();

    new $.fn.dataTable.Buttons(oTable, {
        buttons: [{
            extend: 'csv',// 导出格式
            title: tableName,
            exportOptions: {
                columns: [3, 4, 5, 6, 7, 8, 9, 10, 11],// 导出需要的列
                format: {
                    body: function (data, rID, cID) {// 对导出内容的筛选 data 表格内容
                        // rid 行索引 cid 列索引
                        if (cID == 0) {
                            return data.replace("0", "O");
                        } else {
                            return data;
                        }
                    }
                }
            }
        }]
    });

    oTable.buttons().container().css("display", "inline-block");
    oTable.buttons().container().css("float", "right");
    oTable.buttons().container().find("a").prepend(
        "<i class='glyphicon glyphicon-share'></i>");
    oTable.buttons().container().appendTo('.header');
    oTable.buttons().container().after($("#fliteData")[0]);

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

    return oTable;
}

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