var path = window.location.href;// 获取界面路径
/*******************************************************************************
 * z-tree控件基本参数设置
 ******************************************************************************/
var settingRight = {
    check: {
        enable: true,
        chkDisabledInherit: true
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {
        beforeExpand: beforeExpand,
        beforeCheck: beforeCheck,
        onExpand: onExpand,
        onClick: onClick,
        onCheck: checkTarget
    }
};
var loading;// 用于页面的loading
var className = "dark";

function beforeCheck(treeId, treeNode) {
    className = (className === "dark" ? "" : "dark");
    return (treeNode.doCheck !== false);
}

// tree展开前处理事件
var curExpandNode = null;

function beforeExpand(treeId, treeNode) {
    var pNode = curExpandNode ? curExpandNode.getParentNode() : null;
    var treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
    var zTree1 = $.fn.zTree.getZTreeObj("target");
    for (var i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
        if (treeNode !== treeNodeP.children[i]) {
            zTree1.expandNode(treeNodeP.children[i], false);
        }
    }
    while (pNode) {
        if (pNode === treeNode) {
            break;
        }
        pNode = pNode.getParentNode();
    }
    if (!pNode) {
        singlePath(treeNode);
    }
}

// 重新绘制tree内容 只展开一个tree根节点添加该事件
function singlePath(newNode) {
    if (newNode === curExpandNode)
        return;
    var zTree1 = $.fn.zTree.getZTreeObj("target"), rootNodes, tmpRoot, tmpTId, i, j, n;
    if (!curExpandNode) {
        tmpRoot = newNode;
        while (tmpRoot) {
            tmpTId = tmpRoot.tId;
            tmpRoot = tmpRoot.getParentNode();
        }
        rootNodes = zTree1.getNodes();
        for (i = 0, j = rootNodes.length; i < j; i++) {
            n = rootNodes[i];
            if (n.tId != tmpTId) {
                zTree1.expandNode(n, false);
            }
        }
    } else if (curExpandNode && curExpandNode.open) {
        if (newNode.parentTId === curExpandNode.parentTId) {
            zTree1.expandNode(curExpandNode, false);
        } else {
            var newParents = [];
            while (newNode) {
                newNode = newNode.getParentNode();
                if (newNode === curExpandNode) {
                    newParents = null;
                    break;
                } else if (newNode) {
                    newParents.push(newNode);
                }
            }
            if (newParents != null) {
                var oldNode = curExpandNode;
                var oldParents = [];
                while (oldNode) {
                    oldNode = oldNode.getParentNode();
                    if (oldNode) {
                        oldParents.push(oldNode);
                    }
                }
                if (newParents.length > 0) {
                    zTree1.expandNode(oldParents[Math.abs(oldParents.length
                        - newParents.length) - 1], false);
                } else {
                    zTree1.expandNode(oldParents[oldParents.length - 1], false);
                }
            }
        }
    }
    curExpandNode = newNode;
}

// 回调函数，展开tree节点
function onExpand(event, treeId, treeNode) {
    curExpandNode = treeNode;
}

// 回调函数，点击tree展开节点
function onClick(e, treeId, treeNode) {
    var zTree1 = $.fn.zTree.getZTreeObj("target");
    zTree1.expandNode(treeNode, null, null, null, true);
}

/*******************************************************************************
 * 获取查询指标 计算tree选中的节点，for循环去除计算父节点在内
 ******************************************************************************/
var checkCount = 1, totalcount = 6, nodes = '', node = null;

function checkTarget() {
    var zTree1 = $.fn.zTree.getZTreeObj("target");
    checkCount = zTree1.getCheckedNodes(true).length;
    node = zTree1.getCheckedNodes(true);
    totalcount = checkCount;
    nodes = '';
    var k = 0;

    for (var i = 0; i < totalcount; i++) {
        if (node[i].pId == null) {
            checkCount--;
        } else {
            if (k < 5) {
                nodes += node[i].id + ',';
            } else {
                zTree1.checkNode(node[i], false, true);
            }
            k++;
        }
    }

    if (nodes != '') {
        nodes = nodes.substring(0, nodes.lastIndexOf(','));

        if (nodes.indexOf("41") != -1 || nodes.indexOf("42") != -1) {
            $("#harmonic").css("display", "inline");//显示
        } else {
            $("#harmonic").css("display", "none");//不显示
        }
        if (nodes.indexOf("43") != -1) {
            $("#harmonicInHarm").css("display", "inline");//显示
        } else {
            $("#harmonicInHarm").css("display", "none");//不显示
        }
    }

    if (k > 5) {
        layer.msg('最多选择5个指标');
    }

    if (checkCount >= 5) {
        disabledNode(true);
    } else {
        disabledNode(false);
    }
}

$(document).ready(function () {
    parent.triggerCheckBox(1);
    parent.setTreeSelected(1, -1);
    $.fn.zTree.init($("#target"), settingRight, zNodes);
    checkTarget();

    $('#times').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
        if (clickedIndex != null) {
            var value = document.getElementById("times").options[clickedIndex].value;
            var odd = [];
            var evn = [];
            var total = [];

            for (var i = 0; i < previousValue.length; i++) {
                if (previousValue[i] > 0 && previousValue[i] % 2 == 0) { //偶次
                    odd.push(previousValue[i]);
                } else if (previousValue[i] > 0 && previousValue[i] % 2 != 0) { //奇次
                    evn.push(previousValue[i]);
                } else {
                    total.push(previousValue[i]); //全部 ...
                }
            }

            if ((value === '-1' && previousValue.length > 0 && previousValue[0] != '-1') || (value != '-1' && previousValue[0] === '-1')) { //清空并重新选中
                $('#times').selectpicker('deselectAll');
                $('#times').selectpicker('val', value);
            } else if (value === '-2') {
                var array = [];

                if (odd.length > 0) {
                    array.push(value);

                    for (var i = 0; i < evn.length; i++) {
                        array.push(evn[i]);
                    }

                    for (var j = 0; j < total.length; j++) {
                        if (total[j] == -3) {
                            array.push(total[i]);
                        }
                    }

                    $('#times').selectpicker('deselectAll');
                    $('#times').selectpicker('val', array);
                }
            } else if (value === '-3') {
                var array = [];

                if (evn.length > 0) {
                    array.push(value);

                    for (var i = 0; i < odd.length; i++) {
                        array.push(odd[i]);
                    }

                    for (var j = 0; j < total.length; j++) {
                        if (total[j] == -2) {
                            array.push(total[j]);
                        }
                    }

                    $('#times').selectpicker('deselectAll');
                    $('#times').selectpicker('val', array);
                }
            } else if (value != '-1') {
                var array = [];

                for (var i = 0; i < odd.length; i++) {
                    if (value === odd[i]) {
                        return;
                    }
                }

                for (var i = 0; i < evn.length; i++) {
                    if (value === evn[i]) {
                        return;
                    }
                }

                array.push(value);

                for (var i = 0; i < odd.length; i++) {
                    array.push(odd[i]);
                }

                for (var k = 0; k < evn.length; k++) {
                    array.push(evn[k]);
                }

                if (value % 2 == 0) {
                    for (var j = 0; j < total.length; j++) {
                        if (total[j] == -3) {
                            array.push(total[j]);
                        }
                    }
                } else {
                    for (var j = 0; j < total.length; j++) {
                        if (total[j] == -2) {
                            array.push(total[j]);
                        }
                    }
                }

                /*for (var i = 0; i < array.length; i++) {
                    if (value === array[i]) {
                        array.splice(i, 1);
                    }
                }*/

                $('#times').selectpicker('deselectAll');
                $('#times').selectpicker('val', array);
            }
        }

        $('#times').selectpicker('refresh');
    });
});

var objSearch = new Object();// 跳转页面
function getData() {
    var start = $("#startTime").val();
    var end = $("#endTime").val();
    var points = parent.getTreeSelected(1);
    var lineId = "";

    if (points.length == 0) {
        layer.msg('请至少选择一个监测点');
        return;
    }

    if (nodes == '') {
        layer.msg('请至少选择一个指标');
        return;
    }

    for (var i = 0; i < points.length; i++) {
        lineId += points[i].nodeIndex + ',';
    }

    var times = '';
    var harmonicInHarms = '';

    if (nodes.indexOf("41") > -1 || nodes.indexOf("42") > -1) {
        var data = $('#times').selectpicker('val');

        if (data == null) {
            layer.msg('请选择需要查看的谐波次数', {icon: 2, time: 2000});
            return;
        }

        if (data.length == 1 && data[0] < 0) {
            if (data[0] == -1) {
                for (var i = 0; i < 24; i++) {
                    times += (i + 2) + ',';
                }
            } else if (data[0] == -2) {
                for (var i = 0; i < 12; i++) {
                    times += ((i + 1) * 2) + ',';
                }
            } else {
                for (var i = 0; i < 12; i++) {
                    times += ((i + 1) * 2 + 1) + ',';
                }
            }
        } else {
            var b1 = 0;
            var b2 = 0;

            for (var i = 0; i < data.length; i++) {
                if (data[i] == -2) {
                    b1 = 1;
                } else if (data[i] == -3) {
                    b2 = 1;
                }
            }


            if (b1 == 1 && b2 == 0) {
                for (var i = 0; i < 12; i++) {
                    times + ((i + 1) * 2) + ',';
                }

                for (var i = 0; i < data.length; i++) {
                    if (data[i] % 2 != 0) {
                        times += data[i] + ',';
                    }
                }
            } else if (b2 == 1 && b1 == 0) {
                for (var i = 0; i < 12; i++) {
                    times += ((i + 1) * 2 + 1) + ',';
                }

                for (var i = 0; i < data.length; i++) {
                    if (data[i] % 2 == 0) {
                        times += data[i] + ',';
                    }
                }
            } else if (b1 == 0 && b2 == 0) {
                for (var i = 0; i < data.length; i++) {
                    times += data[i] + ',';
                }
            } else {
                for (var i = 0; i < 24; i++) {
                    times += (i + 2) + ',';
                }
            }
        }
    }

    if (nodes.indexOf("43") > -1) {
        var data = $('#harmonicInHarms').selectpicker('val');

        if (data == null) {
            layer.msg('请选择需要查看的谐波次数', {icon: 2, time: 2000});
            return;
        }

        if (data.length == 1 && data[0] < 0) {
            if (data[0] == -1) {
                for (var i = 0; i < 16; i++) {
                    harmonicInHarms += (i + 1) + ',';
                }
            }
        } else {
            for (var i = 0; i < data.length; i++) {
                harmonicInHarms += data[i] + ',';
            }
        }
    }

    $.ajax({
        type: 'POST',
        dataType: "json",
        data: {
            startTime: start,
            endTime: end,
            lineId: lineId,
            type: nodes,
            index: times,
            harmonicInHarms:harmonicInHarms
        },
        url: '/pqs9000/device/getHistoryTableData',
        success: function (data) {
            layer.close(loading);

            if (data.code == 500) {
                initTable([]);
                layer.msg(data.message, {icon: 2, time: 2000})
            } else {
                var tableData = '';
                var selectData = $('#type').val();

                for (var i = 0; i < data.body.length; i++) {
                    for (var j = 0; j < data.body[i].list.length; j++) {
                        for (var k = 0; k < data.body[i].list[j].list.length; k++) {
                            for (var m = 0; m < data.body[i].list[j].list[k].list.length; m++) {
                                var b = 0;

                                if (selectData == '合格' && data.body[i].list[j].list[k].pass == 0) {
                                    b = 1;
                                } else if (selectData == '不合格' && data.body[i].list[j].list[k].pass == -1) {
                                    b = 1;
                                } else if (selectData == '全部') {
                                    b = 1;
                                }

                                if (b == 1) {
                                    if ((data.body[i].pttype == 1 || data.body[i].pttype == 2) && data.body[i].list[j].targetName.indexOf('电压不平衡') != -1) {
                                        break;
                                    }

                                    if ((data.body[i].pttype == 1 || data.body[i].pttype == 2) && data.body[i].list[j].targetName.indexOf('电流') == -1) {
                                        if (data.body[i].list[j].list[k].list[m].phaseType == 'A')
                                            data.body[i].list[j].list[k].list[m].phaseType = 'AB';
                                        else if (data.body[i].list[j].list[k].list[m].phaseType == 'B')
                                            data.body[i].list[j].list[k].list[m].phaseType = 'BC';
                                        else if (data.body[i].list[j].list[k].list[m].phaseType == 'C') {
                                            if (data.body[i].pttype == 2) {
                                                break;
                                            } else {
                                                data.body[i].list[j].list[k].list[m].phaseType = 'CA';
                                            }
                                        }
                                    }

                                    tableData += '["' + data.body[i].bdName + '","'
                                        + data.body[i].name + '","'
                                        + data.body[i].list[j].targetName + '","'
                                        + judge(data.body[i].list[j].list[k].list[m].phaseType) + '","' //单独处理，否则影响最大、最小展示
                                        + data.body[i].voltage + '","'
                                        + judge(data.body[i].list[j].list[k].list[m].strTime) + '","'
                                        + data.body[i].list[j].unit + '","'
                                        + judge(data.body[i].list[j].list[k].list[m].fmaxValue) + '","'
                                        + judge(data.body[i].list[j].list[k].list[m].minValue) + '","'
                                        + judge(data.body[i].list[j].list[k].list[m].meanValue) + '","'
                                        + judge(data.body[i].list[j].list[k].list[m].cp95Value) + '","';

                                    if (data.body[i].list[j].list[k].pass == null) {
                                        tableData += '/","';
                                    } else if (data.body[i].list[j].list[k].pass == 0) {
                                        tableData += '合格","';
                                    } else if (data.body[i].list[j].list[k].pass == -1) {
                                        tableData += '不合格","';
                                    }

                                    tableData += data.body[i].lineId + '","'
                                        + data.body[i].list[j].typeId + '","' + data.body[i].list[j].timeId + '"],';
                                }
                            }
                        }
                    }
                }

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

function judge(str) {
    return str === null ? '/' : str;
}

var lineName = "";
var oTable;

function initTable(tableData) {
    var $height = $("body").height() * 0.85;

    oTable = $("#tableId")
        .dataTable({
            scrollX: true,
            data: tableData,
            autoWidth: false,
            /*columnDefs: [
                {"width": "15%", "targets": 0},
                {"width": "20%", "targets": 1},
                {"width": "10%", "targets": 2},
                {"width": "7%", "targets": 3},
                {"width": "8%", "targets": 4},
                {"width": "8%", "targets": 5},
                {"width": "8%", "targets": 6},
                {"width": "8%", "targets": 7},
                {"width": "8%", "targets": 8},
                {"width": "8%", "targets": 9}],*/
            lengthChange: false,
            paging: false,
            bDestroy: true,
            info: false,
            ordering: true,
            sDom: '"top"i',
            scrollY: $height,
            scrollCollapse: true,
            language: {
                url : '/pqs9000/json/chine.json',
                "sEmptyTable" : "没有内容"
            },
            aoColumnDefs: [{
                "aTargets": [1], "mRender": function (data, type, full) {
                    return "<a href='#'  onclick=\"preInfo('" + full[12] + "')\">" + data + "</a> "
                }
            }, {
                "aTargets": [7], "mRender": function (data, type, full) {
                    return "<a href='#'  onclick=\"preUpdate('" + full[12] + "','" + full[1] + "','" + 1 + "','" + full[3] + "','" + full[13] + "','" + full[14] + "','" + full[2] + "','" + data + "','" + full[5] + "')\">" + data + "</a> "
                }
            },
                {
                    "aTargets": [8], "mRender": function (data, type, full) {

                        return "<a href='#'  onclick=\"preUpdate('" + full[12] + "','" + full[1] + "','" + 2 + "','" + full[3] + "','" + full[13] + "','" + full[14] + "','" + full[2] + "','" + data + "','" + full[5] + "')\">" + data + "</a> "
                    }
                },
                {
                    "aTargets": [9], "mRender": function (data, type, full) {

                        return "<a href='#'  onclick=\"preUpdate('" + full[12] + "','" + full[1] + "','" + 0 + "','" + full[3] + "','" + full[13] + "','" + full[14] + "','" + full[2] + "','" + data + "','" + full[5] + "')\">" + data + "</a> "
                    }
                },
                {
                    "aTargets": [10], "mRender": function (data, type, full) {

                        return "<a href='#'  onclick=\"preUpdate('" + full[12] + "','" + full[1] + "','" + 3 + "','" + full[3] + "','" + full[13] + "','" + full[14] + "','" + full[2] + "','" + data + "','" + full[5] + "')\">" + data + "</a> "
                    }
                }]
        });

    new $.fn.dataTable.Buttons(oTable.api(), {
        buttons: [
            {
                extend: 'csv',//导出格式
                title: '稳态指标统计',//导出csv名称
            }
        ]
    });

    modifyCss(oTable.api());

    return oTable;
}

function modifyCss(dataTable) {
    //dataTable.buttons().container().css("display", "inline-block");
    dataTable.buttons().container().css("float", "right");
    dataTable.buttons().container().css("top", "2px");
    dataTable.buttons().container().find("a").prepend("<i class='glyphicon glyphicon-share'></i>");
    dataTable.buttons().container().appendTo('.header');
}

function preUpdate(point, lineName, data, phase, condition, harmonic, phaseName, isData, time) {
    objSearch.point = point;
    objSearch.condition = condition;
    if (objSearch.condition.indexOf('41') > -1
        || objSearch.condition.indexOf('42') > -1) {
        objSearch.harmonic = harmonic;
    }
    if(objSearch.condition.indexOf('43') > -1){
        objSearch.inHarmonic = harmonic;
    }
    objSearch.lineName = lineName;
    objSearch.phaseName = phaseName;
    objSearch.startTime = time;
    objSearch.endTime = time;
    objSearch.type = data;
    objSearch.start = '00:00:00';
    objSearch.end = '23:59:59';
    objSearch.phase = phase;
    if (isData == '/') {
        layer.msg("未获取到稳态指标数据", {
            icon: 5,
            time: 3000
        });
    } else {
        layer.open({
            type: 2,
            title: '稳态指标波形',
            maxmin: false,
            shadeClose: true, // 点击遮罩关闭层
            area: ['100%', '100%'],
            content: 'normlimitdraw',
            scrollbar: false
        });
    }
}

// 根据检测点id获取监测点名称
function getName(index) {
    for (var i = 0; i < totalcount; i++) {
        if (node[i].id == index) {
            return ' ' + node[i].name;
        }
    }
    return ' ';
}

// 根据条件设置tree节点状态 可用/不可用
function disabledNode(e) {
    var zTree1 = $.fn.zTree.getZTreeObj("target"), l = zTree1
        .getCheckedNodes(false).length, nodes = zTree1
        .getCheckedNodes(false);
    nodeAll = zTree1.getNodes();
    m = zTree1.getNodes().length;
    if (e) {
        for (var i = 0; i < l; i++) {
            zTree1.setChkDisabled(nodes[i], e, false, false);
        }
    } else {
        for (var i = 0; i < m; i++) {
            zTree1.setChkDisabled(nodeAll[i], e, true, true);
        }
    }
}

var height = $(window).height();

$("#query").click(function () {
    loading = ityzl_SHOW_LOAD_LAYER();
    getData();
});

function preInfo(indexdd) {
    layer.open({
        type: 2,
        title: '监测点详情',
        maxmin: false,
        shadeClose: true, // 点击遮罩关闭层
        area: ['65%', '60%'],
        content: 'pointInfo',
        scrollbar: false,
        success: function (layero, index) {
            $(layero).find("iframe")[0].contentWindow.getPointData(indexdd);
        }
    });
}

function changeTree(ptType) {

}
