var treeObj = null;
var limitMax = 1; //最多选取一个节点
var arrVerify;
var setting = {
	check : {
		enable : true,
		nocheckInherit: true
	},
	data: {
		simpleData: {
			enable: true
		}
	},
	view: {
		fontCss: setHighlight // 高亮一定要设置，setHighlight是自定义方法
	},
	callback : {
		beforeCheck: doVerify,
		onCheck: onVerify,
		onClick: zTreeOnClick
	}
};

var flowSet = false;

$(function(){
	getTree();
	triggerCheckBox(1)
});

function getTree() {
	$.ajax({
		type : 'POST',
		dataType : "json",
		url : '/pqs9900/device/terminalDeviceTree',
		data : {},
		async:false,
		error : function() {
			console.log("获取终端树请求发送失败！");
		},
		success : function(data) {
			var datalist = [];
				for ( var i = 0; i < data.length; i++) {
					var str = '';
					str += '{' + "id:" + data[i].id;
					str += ',' + "name:'" + data[i].name + "'";
					str += ',' + "nodeIndex:" + data[i].nodeIndex;
					str += ',' + "nodeType:" + data[i].nodeType;
					str += ',' + "ppId:" + data[i].ppId;
					if(data[i].nodeType == "0" || data[i].nodeType == "1" || data[i].nodeType == "2"){
						str += ',' + "open:" + true;
					}else{
						str += ',' + "open:" + false;
					}
					str += ',' + "state:" + data[i].state;
					str += ',' + "pId:" + data[i].pId + '}';
					datalist.push(str);
				}
			datalist = eval('[' + datalist + ']');// string->json数组
			var zNodes = datalist;
			treeObj = $.fn.zTree.init($("#tree"), setting, zNodes);
		}
	});
}

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

	if (zTree != null) {
		var nodes = zTree.getSelectedNodes();   //获取树控件选中对象集合
		// 关闭所有节点的高亮
        var allNodes = treeObj.transformToArray(treeObj.getNodes());
        for (var i = 0; i < allNodes.length; i ++) {
            allNodes[i].highlight = false;
            treeObj.updateNode(allNodes[i]);
        }

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

		if (nodes[0].level == 0) {   //根节点
			$("#buttonarea button").attr("hidden","true");
			$("#addProj2").removeAttr("hidden");
		}else if(nodes[0].level == 1){    //项目
			$("#buttonarea button").attr("hidden","true");
			$("#addProj").removeAttr("hidden");
			$("#modProj").removeAttr("hidden");
			$("#delProj").removeAttr("hidden");
			$("#addPro2").removeAttr("hidden");

			var projIndex=nodes[0].nodeIndex;
			$("#projIndex").val(projIndex);
		}else if(nodes[0].level == 2){    //省份
			$("#buttonarea button").attr("hidden","true");
			$("#addPro").removeAttr("hidden");
			$("#modPro").removeAttr("hidden");
			$("#delPro").removeAttr("hidden");
			$("#addGd2").removeAttr("hidden");

			var projIndex=nodes[0].getParentNode().nodeIndex;
			$("#projIndex").val(projIndex);
			var proIndex=nodes[0].nodeIndex;
			$("#proIndex").val(proIndex);
		}else if(nodes[0].level == 3){    //供电公司
			$("#buttonarea button").attr("hidden","true");
			$("#addGd").removeAttr("hidden");
			$("#modGd").removeAttr("hidden");
			$("#delGd").removeAttr("hidden");
			$("#addSub2").removeAttr("hidden");

			var projIndex=nodes[0].getParentNode().getParentNode().nodeIndex;
			$("#projIndex").val(projIndex);
			var proIndex=nodes[0].getParentNode().nodeIndex;
			$("#proIndex").val(proIndex);
			var gdIndex=nodes[0].nodeIndex;
			$("#gdIndex").val(gdIndex);
		}else if(nodes[0].level == 4){   //变电站
			$("#buttonarea button").attr("hidden","true");
			$("#addSub").removeAttr("hidden");
			$("#modSub").removeAttr("hidden");
			$("#delSub").removeAttr("hidden");
			$("#addDev2").removeAttr("hidden");

			var projIndex=nodes[0].getParentNode().getParentNode().getParentNode().nodeIndex;
			$("#projIndex").val(projIndex);
			var proIndex=nodes[0].getParentNode().getParentNode().nodeIndex;
			$("#proIndex").val(proIndex);
			var gdIndex=nodes[0].getParentNode().nodeIndex;
			$("#gdIndex").val(gdIndex);
			var subIndex=nodes[0].nodeIndex;
			$("#subIndex").val(subIndex);
		}else if(nodes[0].level == 5){    //终端
			$("#buttonarea button").attr("hidden","true");
			$("#addDev").removeAttr("hidden");
			$("#modDev").removeAttr("hidden");
			$("#delDev").removeAttr("hidden");
			$("#addSubv2").removeAttr("hidden");
			$("#devcommit").removeAttr("disabled");

			var projIndex=nodes[0].getParentNode().getParentNode().getParentNode().getParentNode().nodeIndex;
			$("#projIndex").val(projIndex);
			var proIndex=nodes[0].getParentNode().getParentNode().getParentNode().nodeIndex;
			$("#proIndex").val(proIndex);
			var gdIndex=nodes[0].getParentNode().getParentNode().nodeIndex;
			var gdname=nodes[0].getParentNode().getParentNode().name;
			$("#gdIndex").val(gdIndex);
			var subIndex=nodes[0].getParentNode().nodeIndex;
			var subname=nodes[0].getParentNode().name;
			$("#subIndex").val(subIndex);
			var devIndex=nodes[0].nodeIndex;
			$("#devIndex").val(devIndex);

			loadDevice(devIndex,gdname,subname);
			loadLineIndex(devIndex);
		}else if(nodes[0].level == 6){     //母线
			$("#buttonarea button").attr("hidden","true");
			$("#addSubv").removeAttr("hidden");
			$("#modSubv").removeAttr("hidden");
			$("#delSubv").removeAttr("hidden");
			$("#addLine2").removeAttr("hidden");

			var projIndex=nodes[0].getParentNode().getParentNode().getParentNode().getParentNode().getParentNode().nodeIndex;
			$("#projIndex").val(projIndex);
			var proIndex=nodes[0].getParentNode().getParentNode().getParentNode().getParentNode().nodeIndex;
			$("#proIndex").val(proIndex);
			var gdIndex=nodes[0].getParentNode().getParentNode().getParentNode().nodeIndex;
			$("#gdIndex").val(gdIndex);
			var subIndex=nodes[0].getParentNode().getParentNode().nodeIndex;
			$("#subIndex").val(subIndex);
			var devIndex=nodes[0].getParentNode().nodeIndex;
			$("#devIndex").val(devIndex);
			var subvIndex=nodes[0].nodeIndex;
			$("#subvIndex").val(subvIndex);
		}else if(nodes[0].level == 7){    //线路
			$("#buttonarea button").attr("hidden","true");
			$("#addLine").removeAttr("hidden");
			$("#modLine").removeAttr("hidden");
			$("#delLine").removeAttr("hidden");

			var projIndex=nodes[0].getParentNode().getParentNode().getParentNode().getParentNode().getParentNode().getParentNode().nodeIndex;
			$("#projIndex").val(projIndex);
			var proIndex=nodes[0].getParentNode().getParentNode().getParentNode().getParentNode().getParentNode().nodeIndex;
			$("#proIndex").val(proIndex);
			var gdIndex=nodes[0].getParentNode().getParentNode().getParentNode().getParentNode().nodeIndex;
			var gdname=nodes[0].getParentNode().getParentNode().getParentNode().getParentNode().name;
			$("#gdIndex").val(gdIndex);
			var subIndex=nodes[0].getParentNode().getParentNode().getParentNode().nodeIndex;
			var subname=nodes[0].getParentNode().getParentNode().getParentNode().name;
			$("#subIndex").val(subIndex);
			var devIndex=nodes[0].getParentNode().getParentNode().nodeIndex;
			$("#devIndex").val(devIndex);
			var subvIndex=nodes[0].getParentNode().nodeIndex;
			$("#subvIndex").val(subvIndex);
			var lineIndex=nodes[0].nodeIndex;
			$("#lineIndex").val(lineIndex);

			$("#linecommit").removeAttr("disabled");
			loadLine(lineIndex);

			loadDevice(devIndex,gdname,subname);
		}
	}
}

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

//复选框操作事件
function onVerify() {
	var arrPoint = getTreeSelected(1);
console.log(arrPoint)
	if (0 === arrPoint.length) {
		return;
	}

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

	closeHigh();

	if (arrPoint.length > limitMax) {
		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 {
		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 getAllSelected() {
	var zTree = $.fn.zTree.getZTreeObj("tree");
	return zTree.getCheckedNodes(true);
}

//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 == 5) {
				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 == 5) {
			pointNodes.push(nodes[0]);
		}
	}

	return pointNodes;
}

/*********************************
 * 是否显示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]);
	}
}


function loadDevice(devIndex,gdname,subname){
	jQuery.ajax({
		type : 'POST',
		dataType : "json",
		url : '/pqs9900/device/loadDevice',
		data : {
			devIndex : devIndex
		},
		success : function(data) {
			var iptype = data.iptype;
			if(iptype == "cld"){
				$("#ipmac").html("<font color='red'>*</font>MAC:");
				$("#mac").val(data.ip);

				$("#onlycld").removeAttr("hidden");
				$("#dataplan").removeAttr("disabled");
				$("#newtraffic").removeAttr("disabled");

				$("#dataplan").val(data.dataplan);
				$("#newtraffic").val(data.newtraffic);
			}else if(iptype == "pqdif"){
				$("#ipmac").html("<font color='red'>*</font>IP/MAC:");
				$("#mac").val(data.ip);

		        $("#onlycld").attr("hidden","true");
		        $("#dataplan").attr("disabled",true);
		        $("#newtraffic").attr("disabled",true);

				$("#dataplan").val("");
				$("#newtraffic").val("");
			}else{
				$("#ipmac").html("<font color='red'>*</font>IP:");
				$("#mac").val(data.ip);

		        $("#onlycld").attr("hidden","true");
		        $("#dataplan").attr("disabled",true);
		        $("#newtraffic").attr("disabled",true);

				$("#dataplan").val("");
				$("#newtraffic").val("");
			}
			$("#devname").val(data.name);
			$("#devtype").val(data.devType);
			$("#port").val(data.portId);

			if(data.status == 1){
				$("#status").val("正常");
			}else{
				$("#status").val("中断");
			}

			$("#gdname").val(gdname);
			$("#subname").val(subname);

			$("#LogonTime").val(data.logTime);
			$("#UpdateTime").val(data.updTime);
			$("#nodeinfo").val(data.nodeIndex);
			$("#datatype").val(data.datatype);
			$("#devmodel").val(data.devmodel);

			$("#ThisTimeCheck").val(data.thisTime);
			$("#NextTimeCheck").val(data.nextTime);
			$("#manufacturer").val(data.manufacturer);
			$("#callflag").val(data.callFlag);
			$("#devfunction").find("option").remove();
//			$("#devfunction").val(data.devfunction);
			var devfunction = [];
			for(v of data.devfunction){
				devfunction.push(v.fucname);
			}
			changeDevfunc(devfunction);
//			if(data.devfunction!=null){
//				for(var i=0;i<data.devfunction.length;i++){
//					$("#devfunction").val(data.devfunction[i]);
//					var mm = $("#devfunction").find("option:contains("+data.devfunction[i].fucname+")");
//					.attr("selected",true);
//				}
//			}

			if(data.series.length>0){
				$("#series").val(data.series);
			}else{
				$("#series").val("");
			}
			if(data.key.length>0){
				$("#key").val(data.key);
			}else{
				$("#key").val("");
			}
		}
	})
}

function loadLineIndex(devIndex){
	jQuery.ajax({
		type : 'POST',
		dataType : "json",
		url : '/pqs9900/device/loadLineIndex',
		data : {
			devIndex : devIndex
		},
		success : function(data) {
			if(data != 0){
				loadLine(data);
			}
			}
		})
}
function loadLine(lineIndex){
	jQuery.ajax({
		type : 'POST',
		dataType : "json",
		url : '/pqs9900/device/loadLine',
		data : {
			lineIndex : lineIndex
		},
		success : function(data) {
			$("#linename").val(data.name);
			$("#scale").val(data.scale);
			$("#dlcMp").val(data.dlcMp);
			$("#xycMp").val(data.xycMp);
			$("#jzcMp").val(data.jzcMp);
			$("#devcMp").val(data.devcMp);
			$("#CT1").val(data.ct1);
			$("#CT2").val(data.ct2);
			$("#PT1").val(data.pt1);
			$("#PT2").val(data.pt2);
			$("#ptType").val(data.ptType);
			$("#tInterval").val(data.tinterval);
			$("#loadType").val(data.loadType);
			$("#businessType").val(data.businessType);
			$("#powerId").val(data.powerId);
			$("#remark").val(data.remark);
			$("#monitorId").val(data.monitorId);
		}
	})
}

function changeDevfunc(devfunction){
	var dictypeName = "装置功能";
	$.ajax({
		method : "post",
		url : "/pqs9900/device/getselect",
		data : {
			dictypeName:dictypeName
		},
		async:true,
		success : function(data) {
			$.each(data, function(i, item) {
				if(devfunction.indexOf(item.dicIndex)>-1){
					var option = $("<option selected value='"
							+ item.dicIndex + "'>"
							+ item.dicName + "</option>");
					$('#devfunction').append(option);
				}else{
					var option = $("<option value='"
							+ item.dicIndex + "'>"
							+ item.dicName + "</option>");
					$('#devfunction').append(option);
				}
			})
			$('#devfunction').fSelect("device");
		}
	})
}

//模糊搜索name满足条件的节点
function searchNode(value) {
	if (value == "")
		return;

	// 获取搜索的节点
	var nodes = treeObj.getNodesByParamFuzzy("name", value);
	// 关闭所有节点的高亮
	var allNodes = treeObj.transformToArray(treeObj.getNodes());
	for (var i = 0; i < allNodes.length; i++) {
		allNodes[i].highlight = false;
		treeObj.updateNode(allNodes[i]);
	}
	// 展开第一层节点
	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);
	}
}
//设置字体高亮
function setHighlight(treeId, treeNode) {
	return (treeNode.highlight) ? {color:"#000000", "font-weight":"bold","border-bottom":"dotted 1px #fff"} : {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]);
	}
}
