var path = window.location.href;//获取界面路径
var treeAllData;
var wfassArr = [] //用于存策略绑定监测点的id

/*********************************************************************************************************************
 * zTree操作deviceTree代码段
 *********************************************************************************************************************/
//zTree属性配置
var setting = {
    check: {
        enable: true,
        nocheckInherit: true
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    view: {
        fontCss: setHighlight // 高亮一定要设置，setHighlight是自定义方法
    },
    callback: {
        onCheck: onVerify,
        beforeCheck: doVerify,
        onClick: pointSelected
    }
};
var type=0;
var typeName='';
var isOutIn='';
var devtype='';
var devindex;
var deviceName='';
var wfIndex = null; //预警策略id
var alarmIndex = null; //预警策略id
var bindLineArr= []


$(function () {
    wfIndex = getQueryString('wfIndex')
    alarmIndex = getQueryString('alarmIndex')
    getData();

});


//刷新树的checkbox
function refreshTreeCheckBox(type) {
    bindLineArr=[]
    if(type == 1){
        //预警
        $.ajax({
            type: 'POST',
            dataType: "json",
            url:'/pqs9300/strategy/getStrategyLine',
            data:{wfIndex:wfIndex,type:2},
            success: function (data) {
                if (data.code == 200) {
                    bindLineArr = data.body
                    if (bindLineArr.length != 0) {
                        bindLineArr = data.body
                        setTreeSelected(1)
                    }

                }


            },
            error:function () {

            }
        });
    }else {
        //告警
        $.ajax({
            type: 'POST',
            dataType: "json",
            url:'/pqs9300/alarmstrategy/getStrategyLine',
            data:{alarmIndex:alarmIndex,type:2},
            success: function (data) {
                if (data.code == 200) {
                    bindLineArr = data.body
                    if (bindLineArr.length != 0) {
                        bindLineArr = data.body
                        setTreeSelected(2)
                    }

                }


            },
            error:function () {

            }
        });
    }


}




//设备书复选框点击监听
function pointSelected() {
    var zTree = $.fn.zTree.getZTreeObj("tree");
    var nodes = zTree.getSelectedNodes();
    type=nodes[0].level;
    if (0 === nodes.length) {
        return;
    }

    closeHigh();

    if (type == 5 && nodes[0].nocheck && path.indexOf("terminal") == -1) {
        nodes[0].highlight = !nodes[0].highlight;
        zTree.updateNode(nodes[0]);
    } else if (path.indexOf("terminal") != -1 && type == 5) {
        nodes[0].highlight = !nodes[0].highlight;
        zTree.updateNode(nodes[0]);

        //修改选中监测点的信息展示
        var subvname = nodes[0].getParentNode();
        var devname = nodes[0].getParentNode().getParentNode();
        var bdname = nodes[0].getParentNode().getParentNode().getParentNode();
        var gdname = nodes[0].getParentNode().getParentNode().getParentNode().getParentNode();

        $('#pointInfo').text('所选:' + gdname.name + '->' + bdname.name + '->' + devname.name + '->' + subvname.name + '->' + nodes[0].name).css('color', 'red');
        typeName=nodes[0].name;
        deviceName=devname.name;
        isOutIn = 'out';
        var line_index = nodes[0].nodeIndex;
        devindex=nodes[0].nodeIndex;
        $("#lineIndex").val(line_index);
        $("#lineName").val(nodes[0].name);

        var status = nodes[0].status;
        var state = nodes[0].state;
        if (state == 2) {
            $("#image").val("gray");
        } else if (state == 1) {
            $("#image").val("yellow");
        } else {
            if (status == 1) {
                $("#image").val("green");
            } else {
                $("#image").val("red");
            }
        }
        var middlesrc = $("#middlesrc").val();
        if (middlesrc == "dzgl") {
            document.getElementById("main_right").src = "dzgl";
        } else if (middlesrc == "devfz") {
            document.getElementById("main_right").src = "devfz";
        }
        devTypeName(devname.name);
    }else if(path.indexOf("terminal") != -1 && type == 3){
        nodes[0].highlight = !nodes[0].highlight;
        zTree.updateNode(nodes[0]);

        //修改选中监测点的信息展示
        var gdname = nodes[0].getParentNode().getParentNode();
        var bdname = nodes[0].getParentNode();

        $('#pointInfo').text('所选:' + gdname.name + '->' + bdname.name + '->' + nodes[0].name).css('color', 'red');
        typeName=nodes[0].name;
        deviceName=nodes[0].name;
        isOutIn = 'in';
        var line_index = nodes[0].nodeIndex;
        devindex=nodes[0].nodeIndex;
        $("#lineIndex").val(line_index);
        $("#lineName").val(nodes[0].name);

        var status = nodes[0].status;
        var state = nodes[0].state;
        if (state == 2) {
            $("#image").val("gray");
        } else if (state == 1) {
            $("#image").val("yellow");
        } else {
            if (status == 1) {
                $("#image").val("green");
            } else {
                $("#image").val("red");
            }
        }
        var middlesrc = $("#middlesrc").val();
        if (middlesrc == "dzgl") {
            document.getElementById("main_right").src = "dzgl";
        } else if (middlesrc == "devfz") {
            document.getElementById("main_right").src = "devfz";
        }
        devTypeName(nodes[0].name);
    }else if(path.indexOf("xbcsv") != -1){
        /*if(nodes[0].level == 4){
            document.getElementById("main_right").contentWindow.initDetail(nodes[0].nodeIndex)
        }*/

    }
}

function zTreeOnAsyncSuccess() {
    var zTree = $.fn.zTree.getZTreeObj("tree");

    var nodes = zTree.getNodes();
    zTree.expandNode(nodes[0], true);

    var childNodes = zTree.transformToArray(nodes[0]);

    var i = 0;
    for (i = 0; i < childNodes.length; i++) {
        type = childNodes[i].level;
        if (type == 5) {
            var subvname = childNodes[i].getParentNode();
            var devname = childNodes[i].getParentNode().getParentNode();
            var bdname = childNodes[i].getParentNode().getParentNode().getParentNode();
            var gdname = childNodes[i].getParentNode().getParentNode().getParentNode().getParentNode();

            zTree.expandNode(gdname, true);
            zTree.expandNode(bdname, true);
            zTree.expandNode(devname, true);
            zTree.expandNode(subvname, true);
            zTree.expandNode(childNodes[i], true);

            $('#pointInfo').text('所选:' + gdname.name + '->' + bdname.name + '->' + devname.name + '->' + subvname.name + '->' + childNodes[i].name).css('color', 'red');

            typeName=childNodes[i].name;
            deviceName=devname.name;
            isOutIn = 'out';
            var line_index = childNodes[i].nodeIndex;
            $("#lineIndex").val(line_index);
            $("#lineName").val(childNodes[i].name);
            var status = childNodes[i].status;
            var state = childNodes[i].state;
            if (state == 2) {
                $("#image").val("gray");
            } else if (state == 1) {
                $("#image").val("yellow");
            } else {
                if (status == 1) {
                    $("#image").val("green");
                } else {
                    $("#image").val("red");
                }
            }
            devTypeName(devname.name);
            // 关闭所有节点的高亮
            var treeObj = $.fn.zTree.getZTreeObj("tree");
            var allNodes = treeObj.transformToArray(treeObj.getNodes());
            for (var n = 0; n < allNodes.length; n++) {
                allNodes[n].highlight = false;
                treeObj.updateNode(allNodes[n]);
            }
            var middlesrc = $("#middlesrc").val();
            if(middlesrc == "dzgl"){
                document.getElementById("main_right").src = "dzgl";
            }else if(middlesrc == "devfz"){
                document.getElementById("main_right").src = "devfz";
            }
            // 高亮并展开搜索到的节点
            childNodes[i].highlight = true;
            treeObj.updateNode(childNodes[i]); // 更新节点，让高亮生效

            break;
        }
    }

}

//获取当前的终端类型
function devTypeName(devName) {
    jQuery.ajax({
        type: 'POST',
        dataType: "json",
        url: '/pqs9900/deviceTree/devNameType',
        data: {
            devName: devName
        },
        success: function (data) {
            devtype=data.devType;
        }
    })
}

/*****************************
 * 选中之前验证是否超过约定上限
 * 超过弹框提示并不选中节点
 *****************************/
var limitMax = 10;
var arrVerify;

function doVerify() {
    arrVerify = getAllSelected();
}

function getAllSelected() {
    var zTree = $.fn.zTree.getZTreeObj("tree");
    return zTree.getCheckedNodes(true);
}

function onVerify() {
    var arrPoint = getTreeSelected(1);


    var arr = getAllSelected();
    var zTree = $.fn.zTree.getZTreeObj("tree");


    closeHigh();


    /*if (arrVerify.length == 0) {
        zTree.checkAllNodes(false);
    } else {
        for (var i = 0; i < arr.length; i++) {
            var index = $.inArray(arr[i], arrVerify);

            if (index === -1) {
                zTree.checkNode(arr[i], false, false);
            }
        }
    }

    layer.msg("最多选择" + limitMax + "个监测点.");
} else {*/
    wfassArr = []
    arrPoint.forEach(function (item) {
        wfassArr.push(item.nodeIndex.toString())
    })


    for (var j = 0; j < arrVerify.length; j++) {
        arrVerify[j].highlight = false;
        zTree.updateNode(arrVerify[j]);
    }

    for (var i = 0; i < arrPoint.length; i++) {
        arrPoint[i].highlight = true;
        zTree.updateNode(arrPoint[i]);
    }

}

// 设置高亮字体
function setHighlight(treeId, treeNode) {
    return (!!treeNode.highlight) ? {color: "#000000", "font-weight": "bold"} : {
        color: "#666",
        "font-weight": "normal"
    };
}

//关闭所有高亮节点
function closeHigh() {
    var treeObj = $.fn.zTree.getZTreeObj("tree");
    var allNodes = treeObj.transformToArray(treeObj.getNodes());// 关闭所有节点的高亮

    for (var i = 0; i < allNodes.length; i++) {
        allNodes[i].highlight = false;
        treeObj.updateNode(allNodes[i]);
    }
}

// 模糊搜索name满足条件的节点
function searchNode(value) {

    if (value == "") return;

    var treeObj = $.fn.zTree.getZTreeObj("tree");
    var nodes = treeObj.getNodesByParamFuzzy("name", value);// 获取搜索的节点

    closeHigh();

    treeObj.expandAll(false);// 展开第一层节点
    treeObj.expandNode(treeObj.getNodes()[0], true);

    // 高亮并展开搜索到的节点
    for (var i = 0; i < nodes.length; i++) {
        nodes[i].highlight = true;
        treeObj.updateNode(nodes[i]); // 更新节点，让高亮生效
        treeObj.expandNode(nodes[i].getParentNode(), true);
    }
}





/*********************************************************************************************************************
 * zTree操作deviceTree代码段结束
 *********************************************************************************************************************/
//type-1:getCheckedNodes方法,type-2:getSelectedNodes方法
function getTreeSelected(type) {
    var pointNodes = [];

    if (type == 1) {
        var nodes = getAllSelected();

        if (0 === nodes.length) {
            return pointNodes;
        }

        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].level == 4) {
                pointNodes.push(nodes[i]);
            }
        }

    } else if (type == 2) {
        var zTree = $.fn.zTree.getZTreeObj("tree");
        var nodes = zTree.getSelectedNodes();

        if (0 === nodes.length) {
            return pointNodes;
        }

        if (nodes[0].level == 4) {
            pointNodes.push(nodes[0]);
        }
    }

    return pointNodes;
}




function valueChange(value) {
    if (value == '') {
        closeHigh();
    }
}




//数据库获取终端树数据
function getData() {
    $.ajax({
        url: "/pqs9300/device/getTree",
        type: "post",
        dataType: "json",
        beforeSend: function () {
            layui.use('layer',function () {
                var layer = layui.layer
                layer.msg('数据加载中...', {
                    icon : 16,
                    shade : [ 0.5, '#f5f5f5' ],
                    scrollbar : false,
                    area:'200px',
                    time : 100000
                });
            })

        },
        success: function (data) {

            treeAllData = data.body
            initTree(data.body);
            triggerCheckBox(1);
            if(wfIndex){
                refreshTreeCheckBox(1)
            }else {
                refreshTreeCheckBox(2)
            }

            layui.use('layer',function () {
                var layer = layui.layer
                layer.closeAll()
            })
        },
        error: function () {
            layui.use('layer',function () {
                var layer = layui.layer
                layer.msg("获取终端树内容失败.");
            })
        }
    });
}

/*********************************
 * 是否显示checkBox
 * type-1:显示
 * type-2:不显示
 *********************************/
function triggerCheckBox(type) {
    var zTree = $.fn.zTree.getZTreeObj("tree");
    var nodes = zTree.transformToArray(zTree.getNodes());
    var isShow = false;

    if (type == 2) {
        isShow = true;
    }

    for (var i = 0; i < nodes.length; i++) {
        nodes[i].nocheck = isShow;
        zTree.updateNode(nodes[i]);
    }
}

/****************************************************
 * 初始化终端树时，设置其选中状态
 * 如果传入的参数<=0，则默认置为1
 * type-1:复选框 type-2:无复选框
 ***************************************************/
function setTreeSelected(type) {

    var zTree = $.fn.zTree.getZTreeObj("tree");
    var nodes = zTree.transformToArray(zTree.getNodes());

    for (var i = 0; i < nodes.length; i++) {
        if(nodes[i].nodeIndex ==22){

        }
        if(bindLineArr.length==0){
            if(nodes[i].level == 4){
                zTree.selectNode(nodes[i]);
                break
            }
        }else {
            if(type== 1){
if(nodes[i].nodeType == 4 ){
                for(var j=0;j<bindLineArr.length;j++){
                    if(nodes[i].nodeIndex==bindLineArr[j].wfassIndex){
                        zTree.selectNode(nodes[i]);
                        zTree.checkNode(nodes[i], true, true);
                        break
                    }
                }
}
            }else {
                if(nodes[i].nodeType == 4) {
                    for (var j = 0; j < bindLineArr.length; j++) {
                        if (nodes[i].nodeIndex == bindLineArr[j].alarmassIndex) {
                            zTree.selectNode(nodes[i]);
                            zTree.checkNode(nodes[i], true, true);
                            break
                        }
                    }
                }
            }



        }

    }

}

/**
 * 获取url参数
 * @param name 参数名
 * @returns 值
 */
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var result = window.location.search.substr(1).match(reg);
    return result?decodeURIComponent(result[2]):'';
}



//初始化终端树
function initTree(treeData) {

    if (treeData.length == 0) {
        layer.msg("数据库数据为空,终端树加载失败.");
        return;
    }

    var datalist = [];
    for (var i = 0; i < treeData.length; i++) {
        var str = '';

        str += '{' + "id:" + treeData[i].id;
        str += ',' + "name:'" + treeData[i].name + "'";
        str += ',' + "nodeIndex:" + treeData[i].nodeIndex;
        str += ',' + "nodeType:" + treeData[i].nodeType;
        str += ',' + "ppId:" + treeData[i].ppId;
        if (treeData[i].nodeType == "0") {
            str += ',' + "open:" + true;
        } else {
            str += ',' + "open:" + false;
        }
        str += ',' + "state:" + treeData[i].state;
        str += ',' + "status:" + treeData[i].status;
        str += ',' + "pId:" + treeData[i].pId + '}';
        datalist.push(str);
    }

    datalist = eval('[' + datalist + ']');// string->json数组
    var zNodes = datalist;

    for (var index = 0; index < zNodes.length; index++) {
        if (zNodes[index].nodeType == 0) {
            zNodes[index].icon = "../images/img/base.png";
        }else if (zNodes[index].nodeType == 1) {
            zNodes[index].icon = "../images/img/province.png";
        } else if (zNodes[index].nodeType == 2) {
            zNodes[index].icon = "../images/img/power.png";
        } else if (zNodes[index].nodeType == 3) {
            zNodes[index].icon = "../images/img/substation.png";
        }  else if (zNodes[index].nodeType == 5) {
            zNodes[index].icon = "../images/img/subvstation.png";
        } else if (zNodes[index].nodeType == 4) {
            if (zNodes[index].state == 2) {
                zNodes[index].icon = "../images/img/gray.png";
            } else if (zNodes[index].state == 1) {
                zNodes[index].icon = "../images/img/yellow.png";
            } else {
                if (zNodes[index].status == 0) {
                    zNodes[index].icon = "../images/img/red.png";
                } else {
                    zNodes[index].icon = "../images/img/green.png";
                }
            }
        }
    }

    $.fn.zTree.init($("#tree"), setting, zNodes);


}



