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

var objTable = null;
var count = 0;
var arrayGuid = [];
var tabId = -1;
var picId = -1;
var deleteId = -1;
var layerId = -1;
var checkboxId = [];
var tableData = [];

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

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

    var obj = new Object();
    var arr = [];
    obj.arrGuid = strGUID.slice(0);
    arr.push(obj);
    tabId = id1;
    picId = id2;
    deleteId = id3;

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

    $.ajax({
        type: 'POST',
        dataType: "json",
        data: {
            queryCondition: JSON.stringify(arr)
        },
        url: '/pqs9200/advanced/queryEventsByGUID',
        success: function (data) {
            processData(data);
            tableData = data.object;
        },
        error: function () {
            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].strEventValue + '","'
            + data.object[offset].strPersist + '","'
            + data.object[offset].sagReason + '","'
            + data.object[offset].sagType + '","' + '' + '"],';

        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;
    checkboxId = [];
    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,
            order: [[4, 'desc']],
            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]);
            }
        });

    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;

                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;
                    arrayGuid.push(obj);
                }

                count = checkCount;
            }
        });

$('#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];
            arrayGuid.push(obj);

            if (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 < tableData.length) {
                document.getElementById('check_all').checked = false;
            }
        }
    }
});

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

    var obj = new Object();
    var arr = [];
    obj.arrGuid = arrayGuid;
    arr.push(obj);

    $.ajax({
        type: 'POST',
        data: {
            condition: JSON.stringify(arr)
        },
        url: '/pqs9200/advanced/deleteWaveform',
        success: function (data) {
            parent.layer.close(tabId);
            parent.layer.close(picId);
            parent.layer.close(deleteId);
        },
        error: function () {
            CLOSE_LOAD_LAYER(layer, layerId);
            layer.msg("从归一化中删除事件失败！");
        }
    });
});

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