var dtLang = {
	"sProcessing" : "处理中...",
	"lengthMenu" : '显示 <select>' + '<option value="5">5</option>'
			+ '<option value="20">20</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 fillAuthRoleData = function(data) {
	var tableHead = "<table id='authorizedRoleTab' class='table display row-border'><thead><tr><th>序号</th><th>公钥</th><th>注册时间</th><th>角色种类</th><th>管理</th></tr></thead><tbody>";
	var tableTail = "</tbody></table>";
	console.log("fillAuthRoleData111");
	var html = tableHead;
	global.authorizedUsers = data;
	console.log(data);
	var lines = (data);
	for (var i = 0; i < lines.kv.length; i++) {
		if (lines.kv[i].key == "__NodeManager__") {
			continue;
		} else {
			html += "<tr><td>";
			html += (i + 1);
			html += ("</td><td>");
			html += (lines.kv[i].key);
			html += ("</td><td>");
			html += (lines.time[i].value);
			html += ("</td><td style='padding:4px 12px 4px 12px'>");
			var roles = lines.kv[i].value.split(",");
			global.rolesList = lines.kv[i].value.split(",").length;
			var len = global.rolesList;
			html += "<select id='chosenRole' style='-webkit-appearance: none;'  class='custom-select'>";
			for (var j = 0; j < global.rolesList; j++) {
				html += "<option selected>" + roles[j]
				"</option>";
			}

			html += ("</td><td style='padding:4px 12px 4px 12px'>");
			html += ("<input type='button' class='btn btn-secondary' value='删除'></input>");
			// html += ("<input type='button' id='allDelete' class='btn-outline-danger' value='全部删除'></input>");
			html += "</td></tr>";
		}
	}
	html += tableTail;
	$("#authorizedRole").html(html);
	$("#authorizedRole").off("click", ":button")
			.on(
					"click",
					":button",
					function(event) {
						var deleteInfo = {};
						var pos = ($(this).closest("tr").find("td").eq(0)
								.text() - 1) / 1;
						var chosenDelete = ($(this).closest("tr").find(
								"select option:selected").val());
						// console.log("chosenDelete" + chosenDelete);
						deleteInfo.role = chosenDelete;
						deleteInfo.pubKey = global.authorizedUsers.kv[pos].key;
						deleteInfo.action = "deleteRole";
						global.wssocket.send(JSON.stringify(deleteInfo));
						// console.log(data);
					});
	$("#authorizedRoleTab").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 : 5,
				order : [ [ 2, 'desc' ] ],
				"columnDefs" : [
						{
							"targets" : 2,
							"render" : function(data, type, row, meta) {
								return new Date(data / 1).toLocaleString();
							}
						},
						{
							"targets" : 1,
							"render" : function(data, type, row, meta) {
								if (data.length > 15)
									return "<span title='" + data + "'>"
											+ data.substring(0, 15)
											+ "  ...</span>";
								else
									return data;
							}
						},

				]
			});
};

var fillUnAuthRoleData = function(data) {
	console.log("fillUnAuthRoleData222");
	var applyTableHead = "<table id='unAuthorizedRoleTab'  class='table display row-border'><thead><tr><th>序号</th><th>公钥</th><th>申请时间</th><th>申请角色</th><th>是否授权</th></tr></thead><tbody>";
	var applyTableTail = "</tbody></table>";
	var html = applyTableHead;
	var lines = data;
	global.authList = lines;
	for (var i = 0; i < lines.kv.length; i++) {
		html += "<tr><td>";
		html += (i + 1);
		html += ("</td><td>");
		html += (lines.kv[i].key);
		html += ("</td><td>");
		html += (lines.time[i].value);
		html += ("</td><td style='padding:4px 12px 4px 12px'>");
		var roles = lines.kv[i].value.split(",");
		global.applyRolesList = lines.kv[i].value.split(",").length;
		var len = global.applyRolesList;
		html += "<select id='appRole' style='-webkit-appearance: none;'  class='custom-select'>";
		for (var j = 0; j < global.applyRolesList; j++) {
			html += "<option selected>" + roles[j]
			"</option>";
		}
		// html += (lines.kv[i].value);
		html += ("</td><td style='padding:4px 12px 4px 12px'>");
		html += ("<input type='button' class='btn btn-primary' value='授权'></input>&nbsp;");
		html += ("<input type='button' class='btn btn-secondary' value='忽略'></input>");
		html += "</td></tr>";
	}
	html += applyTableTail;
	$("#unAuthorizedRole").html(html);
	$("#unAuthorizedRole").off("click", ":button")
			.on(
					"click",
					":button",
					function(event) {
						var authInfo = {};
						authInfo.action = "authNodeRole";
						var pos = ($(this).closest("tr").find("td").eq(0)
								.text() - 1) / 1;
						authInfo.pubKey = global.authList.kv[pos].key;
						authInfo.isAccept = "" + event.target.value == '授权';
						global.wssocket.send(JSON.stringify(authInfo));
						// console.log(data);
					});
	$("#unAuthorizedRoleTab").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 : 5,
				order : [ [ 2, 'desc' ] ],
				"columnDefs" : [
						{
							"targets" : 2,
							"render" : function(data, type, row, meta) {
								return new Date(data / 1).toLocaleString();
							}
						},
						{
							"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" : 3,
						// 	"render" : function(data, type, row, meta) {
						// 		if (data.length > 15)
						// 			return "<span title='" + data + "'>"
						// 					+ data.substring(0, 15)
						// 					+ "  ...</span>";
						// 		else
						// 			return data;
						// 	}
						// }
				]
			});
};

// TODO
// 在WSHandler的onUserList之类的方法里使用。
// -----------------------------------------------
var loadUserMan = function() {
	setTimeout(function() {
		console.log("loadUserManTrigged!");
		var loginAllUser = {};
		loginAllUser.action = "listAllAuthRole";
		global.wssocket.send(JSON.stringify(loginAllUser));
		var loginApplyList = {};
		loginApplyList.action = "listUnAuthRole";
		global.wssocket.send(JSON.stringify(loginApplyList));

		var getUserActivities = {};
		getUserActivities.action = "countNodeLogGroupByCategory";
		getUserActivities.start = getDateDaysBefore(30);
		getUserActivities.category = "login,applyNodeRole,authNodeRole";
		getUserActivities.interval = 24*3600*1000;
		global.wssocket.send(JSON.stringify(getUserActivities));

		var countList = {};
		countList.action = "countRole";
		global.wssocket.send(JSON.stringify(countList));
	}, 200);

};

// -----------------------------------------------
var setUserTypeDistribution = function(data) {

	$("#RolePie")
			.html(
					"<div class='col-12' id='RolePieCanv' style='min-height: 250px; padding: 0px'></div>");
	var myChart = echarts.init($("#RolePieCanv")[0], 'walden');
	var count = data.data;
	var option222 = {
		tooltip : {
			trigger : 'item',
			formatter : '{a} <br/>{b}: {c} ({d}%)'
		},
		legend : {
			orient : 'vertical',
			left : 10,
			data : [ '节点管理员', '合约管理员', '合约提供者', '合约使用者' ]
		},
		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 : [ {
				value : data.NodeManager,
				name : '节点管理员'
			}, {
				value : data.ContractInstanceManager,
				name : '合约管理员'
			}, {
				value : data.ContractProvider,
				name : '合约提供者'
			}, {
				value : data.ContractUser,
				name : '合约使用者'
			} ]
		} ]
	};
	myChart.setOption(option222);
};

var drawUserActivityGraph = function(data) {
	global.lastData = data;
	console.log(data);
	console.log("drawUserActivityGraph");
	$("#nodeUserActivityDiv")
			.html(
					"<div class='col-12' id='nodeUserActivityCanv' style='min-height: 250px; padding: 0px'></div>");
	var xAxisData = [];
	var loginData = data.data.login;
	var applyData = data.data.applyNodeRole;
	var authData = data.data.authNodeRole;

	var startTime = data.start;
	var interval = data.interval;
	for (var i=0;i<loginData.length;i++){
		xAxisData.push(new Date(startTime).toISOString().substring(0, 10));
	    startTime+=interval;
	}
	var myChart = echarts.init($("#nodeUserActivityCanv")[0], 'walden');
	var option = {
		title : {
			subtext : '次数'
		},
		tooltip : {
			trigger : 'axis'
		},
		legend : {
			data : [ '登录', '申请', '授权' ],
			y : 'bottom',
		},
		toolbox : {
			show : true,
			feature : {
				dataZoom : {
					yAxisIndex : 'none'
				},
				dataView : {
					readOnly : false
				},
				magicType : {
					type : [ 'line', 'bar' ]
				},
				restore : {},
				saveAsImage : {}
			}
		},
		xAxis : {
			type : 'category',
			boundaryGap : false,
			data : xAxisData
		},
		yAxis : {
			type : 'value',
			axisLabel : {
				formatter : '{value}次'
			}
		},
		series : [ {
			name : '登录',
			type : 'line',
			data : loginData,
			markPoint : {
				data : [ {
					type : 'max',
					name : '最大值'
				}, {
					type : 'min',
					name : '最小值'
				} ]
			},

		}, {
			name : '申请',
			type : 'line',
			data : applyData,
			markPoint : {
				data : [ {
					type : 'max',
					name : '最大值'
				}, {
					type : 'min',
					name : '最小值'
				} ]
			}
		}, {
			name : '授权',
			type : 'line',
			data : authData,
			markPoint : {
				data : [ {
					type : 'max',
					name : '最大值'
				}, {
					type : 'min',
					name : '最小值'
				} ]
			}
		} ]
	};
	myChart.setOption(option);
};
