var loadNodesListMan = function(event) {
	console.log("loadNodesListMan");
	listNodes();
	listTrustUnits();
};

var listNodes = function(event) {
	console.log("listNodes");
	setTimeout(function() {
		var param = {};
		param.action = "listNodes";
		param.pubKey = global.sm2Key.publicKey;
		global.wssocket.send(JSON.stringify(param));
	}, 300);
};

var listTrustUnits = function(event) {
	console.log("listTrustUnits");
	setTimeout(function() {
		var param = {};
		param.action = "listTrustUnits";
		param.pubKey = global.sm2Key.publicKey;
		global.wssocket.send(JSON.stringify(param));
	}, 300);
};

var submitTrustUnitNodes = function(event) {
	const options = document.querySelector('#selectTrustUnitNodes').options;
	var list = [];
	for (let i = 0; i < options.length; i++) {
		// 如果该option被选中，则将它的value存入数组
		if (options[i].selected) {
			var item = {};
			item.nodeName = options[i].text;
			item.peerID = options[i].value;
			list.push(item);
		}
	}
	var param = {};
	param.action = "createTrustUnit";
	param.data = list;
	var name = $("#newUnitName")[0].value;
	if (name == undefined || name =="" ){
		myToast("失败","请输入集群名称");
	}
	param.msg = name;
	// console.log(JSON.stringify(param));
	global.wssocket.send(JSON.stringify(param));

};

var onCreateTrustUnit = function(event) {
	myToast("Success", "创建可信集群成功")
	listTrustUnits();
};

// if ($("#nodesStatusPieDiv").css("height") == "0px") {
var drawNodesStatusPie = function(id, obj) {
	// if ($("#nodesStatusPieDiv").css("height") == "0px") {
	if ($("#" + id).css("height") == "0px") {
		console.log("drawNodesStatusPie: ignore");
		return;
	}
	$("#" + id)
			.html(
					"<div class='col-12' id='"
							+ id
							+ "Canv' style='width:100%; min-height: 150px; padding: 0px'></div>");
	var result = {};
	if (obj.offline.length > obj.online.length) {
		result["Offline"] = obj.offline.length - obj.online.length;
		result["Online"] = obj.online.length;
	} else {
		result["Offline"] = 0;
		result["Online"] = obj.online.length;
	}
	global.result = result;
	var dataList = [];
	var valDataList = [];
	for ( var key in result) {
		dataList.push(key);
		var l = {};
		l.name = key
		l.value = result[key];
		valDataList.push(l);
	}

	var myChart = echarts.init($("#" + id + "Canv")[0], 'walden');
	var option222 = {
		tooltip : {
			trigger : 'item',
			formatter : '{a} <br/>{b}: {c} ({d}%)'
		},
		legend : {
			orient : 'vertical',
			left : 10,
			data : dataList
		},
		series : [ {
			name : '节点数目',
			type : 'pie',
			radius : [ '50%', '70%' ],
			avoidLabelOverlap : false,
			label : {
				normal : {
					show : false,
					position : 'center'
				},
				emphasis : {
					show : true,
					textStyle : {
						fontSize : '15',
						fontWeight : 'bold'
					}
				}
			},
			labelLine : {
				normal : {
					show : false
				}
			},
			data : valDataList
		} ]
	};
	myChart.setOption(option222);
};

var onListNodes = function(obj) {
	// mainVue
	var len = 0;
	if (obj.offline != undefined) {
		mainVue.nodeCount = obj.offline.length;
	}
	if (obj.offline == undefined && obj.online != undefined
			&& obj.online.length != undefined) {
		mainVue.nodeCount = obj.online.length;
	}
	
	var count = 0;
	if (obj.online != undefined) {
		for (var i = 0; i < obj.online.length; i++) {
			count += obj.online[i].contracts.length;
		}
	}
	mainVue.contractCount = count;
	// nodesStatusPieDiv
	// dashNodesStatusPieDiv
	drawNodesStatusPie("nodesStatusPieDiv", obj);
	drawNodesStatusPie("dashNodesStatusPieDiv", obj);

	// console.log(obj);
	if ($("#nodesTabDiv").css("height") == "0px") {
		console.log("nodesTabDiv: ignore");
		return;
	}
	var dtLang = {
		"sProcessing" : "处理中...",
		"lengthMenu" : '显示 <select>' + '<option value="10">10</option>'
				+ '<option value="50">50</option>'
				+ '<option value="100">100</option>'
				+ '<option value="-1">全部</option>' + '</select> 项结果',
		"sZeroRecords" : "没有匹配结果",
		"sInfo" : "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
		"sInfoEmpty" : "显示第 0 至 0 项结果，共 0 项",
		"sInfoFiltered" : "(由 _MAX_ 项结果过滤)",
		"sInfoPostFix" : "",
		"sSearch" : "搜索:",
		"sUrl" : "",
		"sEmptyTable" : "表中数据为空",
		"sLoadingRecords" : "载入中...",
		"sInfoThousands" : ",",
		"oPaginate" : {
			"sFirst" : "首页",
			"sPrevious" : "上页",
			"sNext" : "下页",
			"sLast" : "末页"
		},
		"oAria" : {
			"sSortAscending" : ": 以升序排列此列",
			"sSortDescending" : ": 以降序排列此列"
		}
	};
	var tableHead = "<table id='nodesTabDivTab' class='table display row-border'><thead><tr><th>序号</th><th>Name</th><th>状态</th><th>合约数目</th><th>事件数目</th><th>PeerID</th><th>UDPID</th><th>公钥</th></tr></thead><tbody>";
	var tableTail = "</tbody></table>";
	var html = tableHead;
	var contractCount = 0;
	var eventCount = 0;
	$("#selectTrustUnitNodes").html("");
	var x = document.getElementById("selectTrustUnitNodes");
	x.options.length = 0;
	var i;
	for (i = 0; i < obj.online.length; i++) {
		html += "<tr><td>";
		html += (i + 1);
		html += "</td> <td>";
		html += obj.online[i].nodeName;
		html += "</td> <td>";
		html += "Online";
		html += "</td> <td>";
		html += obj.online[i].contracts.length;
		html += "</td> <td>";
		html += obj.online[i].events.length;
		html += "</td> <td>";
		html += obj.online[i].peerID;
		html += "</td> <td>";
		html += obj.online[i].udpID;
		html += "</td> <td>";
		html += obj.online[i].pubKey;
		html += "</td> </tr>";
		if (obj.online[i].contracts!=undefined)
		contractCount += obj.online[i].contracts.length;
		eventCount += 0;

		var option = document.createElement("option");
		option.text = obj.online[i].nodeName;
		option.value = obj.online[i].peerID;
		x.add(option);// new
		// Option(obj.online[i].pubKey,obj.online[i].pubKey),0);
		// option += '<option value="' + obj.online[i].pubKey + '">' +
		// obj.online[i].pubKey.substring(0,15) + '</option>';

	}
	// console.log("offline: ",obj.offline);
    for (i; i < obj.offline.length; i++) {
        html += "<tr><td>";
        html += (i + 1);
        html += "</td> <td>";
        html += obj.offline[i];
        html += "</td> <td>";
        html += "Offline";
        html += "</td> <td>";
        html += "-";
        html += "</td> <td>";
        html += "-";
        html += "</td> <td>";
        html += "-";
        html += "</td> <td>";
        html += "-";
        html += "</td> <td>";
        html += "-";
        html += "</td> </tr>";

    }

	$("#selectTrustUnitNodes").selectpicker('refresh');

	mainVue.contractCount = contractCount;
	mainVue.eventCount = eventCount;
	html += tableTail;
	$("#nodesTabDiv").html(html);
	$("#nodesTabDivTab").DataTable(
			{
				"language" : dtLang,
				"rowCallback" : function(row, data, displayNum, displayIndex,
						dataIndex) {

				},
				"headerCallback" : function(thead, data, start, end, display) {
					$(thead).css("background", primaryColor);
					$(thead).css("color", "white");
					$(thead).children().css("background", primaryColor);
					$(thead).children().css("color", "white");
				},
				scrollCollapse : false,
				paging : true,
				pageLength : 10,
				order : [ [ 0, 'desc' ] ],
				"columnDefs" : [
						{
							"targets" : 1,
							"render" : function(data, type, row, meta) {
								if (data.length > 15)
									return "<span title='" + data + "'>"
											+ data.substring(0, 15)
											+ "  ...</span>";
								else
									return data;
							}

						},
						{
							"targets" : 5,
							"render" : function(data, type, row, meta) {
								if (data.length > 10)
									return "<span title='" + data + "'>"
											+ data.substring(0, 10)
											+ "  ...</span>";
								else
									return data;
							}

						},
						{
							"targets" : 7,
							"render" : function(data, type, row, meta) {
								if (data.length > 15)
									return "<span title='" + data + "'>"
											+ data.substring(0, 15)
											+ "  ...</span>";
								else
									return data;
							}

						} ]

			});
};

var onListTrustUnits = function(obj) {
	// mainVue
	mainVue.unitCount = obj.data.length;
	// console.log(obj);
	if ($("#trustNodesUnitTabDiv").css("height") == "0px") {
		console.log("trustNodesUnitTabDiv: ignore");
		return;
	}
	var dtLang = {
		"sProcessing" : "处理中...",
		"lengthMenu" : '显示 <select>' + '<option value="10">10</option>'
				+ '<option value="50">50</option>'
				+ '<option value="100">100</option>'
				+ '<option value="-1">全部</option>' + '</select> 项结果',
		"sZeroRecords" : "没有匹配结果",
		"sInfo" : "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
		"sInfoEmpty" : "显示第 0 至 0 项结果，共 0 项",
		"sInfoFiltered" : "(由 _MAX_ 项结果过滤)",
		"sInfoPostFix" : "",
		"sSearch" : "搜索:",
		"sUrl" : "",
		"sEmptyTable" : "表中数据为空",
		"sLoadingRecords" : "载入中...",
		"sInfoThousands" : ",",
		"oPaginate" : {
			"sFirst" : "首页",
			"sPrevious" : "上页",
			"sNext" : "下页",
			"sLast" : "末页"
		},
		"oAria" : {
			"sSortAscending" : ": 以升序排列此列",
			"sSortDescending" : ": 以降序排列此列"
		}
	};
	var tableHead = "<table id='trustNodesUnitTabDivTab' class='table display row-border'><thead><tr><th>序号</th><th>ID</th><th>创建者</th><th>节点数目</th><th>节点公钥</th><th></th></tr></thead><tbody>";
	var tableTail = "</tbody></table>";
	var html = tableHead;
	for (var i = 0; i < obj.data.length; i++) {
		var at_ = obj.data[i].key.indexOf("_");
		var nodes = JSON.parse(obj.data[i].value);
		html += "<tr><td>";
		html += (i + 1);
		html += "</td> <td>";
		html += obj.data[i].key.substring(at_ + 1);
		html += "</td> <td>";
		html += obj.data[i].key.substring(0, at_ - 1);
		html += "</td> <td>";
		html += nodes.length;
		html += "</td> <td>";
		html += JSON.stringify(nodes);
		html += "</td> <td>";
		html += "<button class='btn-outline-danger' onclick='deleteTrustUnit(\"" + obj.data[i].key
				+ "\")'>删除</button>";
		html += "</td> </tr>";
	}
	html += tableTail;
	$("#trustNodesUnitTabDiv").html(html);
	$("#trustNodesUnitTabDivTab").DataTable(
			{
				"language" : dtLang,
				"rowCallback" : function(row, data, displayNum, displayIndex,
						dataIndex) {

				},
				"headerCallback" : function(thead, data, start, end, display) {
					$(thead).css("background", primaryColor);
					$(thead).css("color", "white");
					$(thead).children().css("background", primaryColor);
					$(thead).children().css("color", "white");
				},
				scrollCollapse : false,
				paging : true,
				pageLength : 10,
				order : [ [ 0, 'desc' ] ],
				"columnDefs" : [
						{
							"targets" : 2,
							"render" : function(data, type, row, meta) {
								if (data.length > 15)
									return "<span title='" + data + "'>"
											+ data.substring(0, 15)
											+ "  ...</span>";
								else
									return data;
							}

						},
						{
							"targets" : 4,
							"render" : function(data, type, row, meta) {
								if (data.length > 40)
									return "<span title='" + data + "'>"
											+ data.substring(0, 40)
											+ "  ...</span>";
								else
									return data;
							}

						} ]
			});
};

var deleteTrustUnit = function(data) {
	var param = {};
	param.action = "deleteTrustUnit";
	param.data = data;
	// console.log(JSON.stringify(param));
	global.wssocket.send(JSON.stringify(param));
};

var onDeleteTrustUnit = function(event) {
	myToast("Success", "删除可信集群成功")
	listTrustUnits();
};
