/**
 * 点击确定之后关闭所有的子页面，弹出波形展示页面
 */
var checkedData = [];
var nCount = 0;
var objTable = null;
var checkaddboxId = [];
var tData = [];

var selectData = [];


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

$('#submit').click(function () {
    if (nCount < 1) {
        layer.msg("请至少选择一个事件!");
        return;
    }

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

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

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

                tableLen--;
            }

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

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

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

                    var obj = new Object();
                    obj.indexEventAss = (tData[i].indexEventAss == null ? 'null' : tData[i].indexEventAss);
                    obj.indexEventDetail = tData[i].indexEventDetail;
                    obj.strTime = tData[i].strTime;
                    obj.namePoint = tData[i].plantInfo.namePoint;
                    obj.sagType = tData[i].sagType;
                    checkedData.push(obj);
                }

                nCount = checkCount;
            }
        });

$('#tableId').on('click', '.checkList', function () {
    var count = checkedData.length;

    if (objTable != null) {
        var item = objTable.row($(this).closest('tr')).data();

        if (document.getElementById('check_'
            + item[1]).checked) {
            nCount++;
            var obj = new Object();
            obj.indexEventAss = (item[0] == null ? 'null' : item[0]);
            obj.indexEventDetail = item[1];
            obj.strTime = item[4];
            obj.namePoint = item[7];
            obj.sagType = item[10];

            checkedData.push(obj);

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

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

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

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

$('body').on('change','#interval',function () {
    addWave(arrGuid,strTime,tabId,picId,addtabId)
})


/**
 * 根据时间查询相隔60s之内的所有暂降事件60000
 *
 * @param arrayGuid
 * @param time
 * @returns
 */
var arrGuid = [];
var strTime ='';
var tabId = -1;
var picId = -1;
var addtabId = -1;
var layerId = -1;

function addWave(arrayGuid, time, id1, id2, id3) {
    layerId = SHOW_LOAD_LAYER(layer);

    arrGuid = arrayGuid
    strTime = time
    tabId = id1;
    picId = id2;
    addtabId = id3
    let intervalTime = $('#interval').val()

    /**
     * 处理查询参数
     */
    checkedData = arrayGuid.slice(0);
    selectData = arrayGuid.slice(0);
    var date = string2Date(time);
    var endTime = new Date(date.getTime() + intervalTime*1000)
    endTime = endTime.Format('yyyy-MM-dd hh:mm:ss');
    var date1 = string2Date(time);
    var startTime = new Date(date1.getTime() - intervalTime*1000)
    startTime = startTime.Format('yyyy-MM-dd hh:mm:ss');
    var obj = new Object();
    var arr = [];
    obj.startTime = startTime;
    obj.endTime = endTime;
    obj.strGuid = arrayGuid[0].indexEventAss;
    arr.push(obj);

    $.ajax({
        type: 'POST',
        dataType: "json",
        data: {
            queryCondition: JSON.stringify(arr)
        },
        url: '/pqs9200/advanced/queryEventsByGUID',
        success: function (data) {
            checkaddboxId = [];
            tData = data.object;
            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].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,
            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);
                checkaddboxId.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;
}

function string2Date(str) {
    var date = new Date(Date.parse(str));
    return date;
}

/**
 * Format日期格式
 */
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

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