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

var strTime;
var objTable = null;
var count = 0;
var arrayGuid = [];
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) {
                var $btnView = $('<input type="checkbox" class="checkList" id="check_'
                    + data[1] + '">');
                $('td', row).eq(nIndex).append($btnView);
                checkboxId.push(data[1]);

                /*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, 12],// 导出需要的列
                format: {
                    body: function (data, rID, cID) {// 对导出内容的筛选 data 表格内容
                        // rid 行索引 cid 列索引
                        if (cID == 1) {
                            return data.replace("0", "O");
                        } else if (cID == 0) {
                            return rID + 1;
                        } 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(3, {
            draw: 'applied',
        }).nodes().each(function (cell, i) {
            cell.innerHTML = i + 1;
        });
    }).draw();

    return oTable;
}

/**
 * 增加表格数据全选按钮： 如果所选数据超过十条，提示最多只能选择十条数据并选中前面十条数据
 */
$('#check_all')
    .click(
        function () {
            var tableLen = checkboxId.length;
            arrayGuid = [];
            count = 0;

            while (tableLen - 1 >= 0) {
                if (document.getElementById('check_'
                    + checkboxId[tableLen - 1]) != null) {
                    document.getElementById('check_'
                        + checkboxId[tableLen - 1]).checked = false;
                }

                tableLen--;
            }

            if (document.getElementById('check_all').checked) {
                var checkCount = checkboxId.length;

                if (checkCount > 10) {
                    layer.msg("最多选择10条记录！");
                    checkCount = 10;
                }

                for (var i = 0; i < checkCount; i++) {
                    document.getElementById('check_' + checkboxId[i]).checked = true;

                    var obj = new Object();
                    obj.indexEventAss = tableData[i].indexEventAss;
                    obj.indexEventDetail = tableData[i].indexEventDetail;
                    obj.strTime = tableData[i].strTime;
                    obj.namePoint = tableData[i].plantInfo.namePoint;
                    obj.sagType = tableData[i].sagType;
                    arrayGuid.push(obj);
                }

                count = checkCount;
            }
        });

/*
 * 对checkbox的操作 最多选择10条记录对比 将选中事件的GUID放到数组中缓存使用
 */
$('#tableId')
    .on(
        'click',
        '.checkList',
        function () {
            if (objTable != null) {
                var item = objTable.row($(this).closest('tr')).data();

                if (document.getElementById('check_' + item[1]).checked) {
                    count++;

                    var obj = new Object();
                    obj.indexEventAss = item[0];
                    obj.indexEventDetail = item[1];
                    obj.strTime = item[4];
                    obj.namePoint = item[7];
                    obj.sagType = item[10];
                    arrayGuid.push(obj);

                    if (count > 10) {
                        layer.msg("最多选择10条记录！");
                        document.getElementById('check_' + item[1]).checked = false;
                        count--;
                        arrayGuid.pop();
                    }

                    if ((count == 10 && tableData.length > 9)
                        || count == tableData.length) {
                        document.getElementById('check_all').checked = true;
                    }
                } else {
                    count--;

                    for (var i = 0; i < arrayGuid.length; i++) {
                        if (arrayGuid[i].indexEventDetail === item[1]) {
                            arrayGuid.splice(i, 1);
                            break;
                        }
                    }

                    if ((count < 10 && tableData.length > 9)
                        || count < tableData.length) {
                        document.getElementById('check_all').checked = false;
                    }
                }
            }
        });

/*
 * 波形对比按钮点击事件
 */
$('#waveCompare').click(
    function () {
        if (count < 1) {
            layer.msg("请至少选择一个事件!");
            return;
        }

        var id = parent.layer.open({
            type: 2,
            title: '波形对比',
            maxmin: false,
            shadeClose: true, // 点击遮罩关闭层
            area: ['100%', '100%'],
            content: 'wavecompare',
            scrollbar: false,
            success: function (layero, index) {
                $(layero).find("iframe")[0].contentWindow.getData(
                    arrayGuid, strTime, tabId, id, strName);
            },
        });
    });

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