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 tableHead = "<table id='authorizedUsersTab' class='table display row-border'><thead><tr><th>序号</th><th>公钥</th><th>注册时间</th><th>备注</th><th>管理</th></tr></thead><tbody>";
var tableTail = "</tbody></table>";
var fillUserData = function(data) {
	console.log("fillUserData");
	var html = tableHead;
	var lines = data;
	global.authorizedUsers = lines;
	for (var i = 0; i < lines.kv.length; i++) {
		if (data == undefined) {
			data = "[]";
		}
		if (lines.kv[i].key == "__CenterManager__") {
			continue;
		} else {
			// var o = data[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>");
			html += (lines.kv[i].value);
			html += ("</td><td style='padding:6px 12px'>");
			html += ("<input type='button' class='btn btn-sm btn-outline-danger' value='删除'></input>");
			html += "</td></tr>";
		}
	}
	html += tableTail;
	$("#authorizedUsers").html(html);
	$("#authorizedUsers").off("click", ":button").on(
			"click",
			":button",
			function(event) {
				var deleteInfo = {};
				var pos = ($(this).closest("tr").find("td").eq(0)
						.text() - 1) / 1;
				
				deleteInfo.pubKey = global.authorizedUsers.kv[pos].key;
				deleteInfo.action = "delete";
				global.wssocket.send(JSON.stringify(deleteInfo));
			});
	$("#authorizedUsersTab").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 applyTableHead = "<table id='unAuthorizedUsersTab' 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 fillApplyUserData = function(data) {
	if (data == undefined) {
		data = "[]";
	}
	var html = applyTableHead;
	var lines = (data);
	global.applyList = 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>");
		html += (lines.kv[i].value);
		html += ("</td><td style='padding:6px 12px'>");
		html += ("<input type='button' class='btn btn-sm btn-outline-primary' value='授权'></input>&nbsp;");
		html += ("<input type='button' class='btn btn-sm btn-outline-danger' value='忽略'></input>");
		html += "</td></tr>";
	}
	html += applyTableTail;
	$("#unAuthorizedUsers").html(html);
	$("#unAuthorizedUsers").off("click", ":button")
			.on(
					"click",
					":button",
					function(event) {
						var acceptInfo = {};
						acceptInfo.action = "authNodeManager";
						var pos = ($(this).closest("tr").find("td").eq(0)
								.text() - 1) / 1;
						acceptInfo.pubKey = global.applyList.kv[pos].key;
						acceptInfo.isAccept = "" + event.target.value == '授权';
						global.wssocket.send(JSON.stringify(acceptInfo));
					});
	$("#unAuthorizedUsersTab").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;
							}

						} ]
			});
};

// TODO
// 在WSHandler的onUserList之类的方法里使用。
// -----------------------------------------------
var loadUserMan = function() {
	console.log("loadUserManTrigged!");

	var loginAllUser = {};
	loginAllUser.action = "listAllUsers";
	global.wssocket.send(JSON.stringify(loginAllUser));
	var loginApplyList = {};
	loginApplyList.action = "listApplyList";
	global.wssocket.send(JSON.stringify(loginApplyList));
	var queryUserStat = {};
	setTimeout(function() {
		queryUserStat.action = "queryUserStat";
		global.wssocket.send(JSON.stringify(queryUserStat));
		changeLineApply($("#lineApply")[0].value);	
	}, 500);
};

var changeLineApply = function(data){
	var time = data.split("天")[0];
	global.lineApplyTime = time;
	setTimeout(function() {
	    var queryApplyStat = {};
    	queryApplyStat.action = "countActionLogByCategory";
    	queryApplyStat.category = "applyRole,accept";
    	queryApplyStat.start = getDateDaysBefore(global.lineApplyTime);
    	queryApplyStat.interval=24*3600*1000;
    	queryApplyStat.requestID = "changeLineApply_"+new Date().getTime()+"_"+Math.floor(Math.random()*1000000);
        global.wscallbacks[queryApplyStat.requestID]=onChangeLineApply;
    	global.wssocket.send(JSON.stringify(queryApplyStat));
	}, 300);
};
var onChangeLineApply = function(obj){
    console.log(obj);
    var data = {};
   var  start = getDateDaysBefore(global.lineApplyTime);

    data.xAxis =[];
    for (var i=0;i<obj.data.applyRole.length;i++){
        var date = new Date(start);
        data.xAxis.push(date.getMonth()+1+"/"+date.getDate());
        start+=24*3600*1000;
    }
    data.yAxis1 = obj.data.applyRole;
    data.yAxis2 = obj.data.accept;
    setUSERMANBar(data);
};
// -----------------------------------------------
var setUserTypeDistribution = function(jqueryDiv, data) {
	var divName = "userTypeDistributionCanv"
			+ Math.floor(Math.random() * 10000000);
	jqueryDiv.html("<div class='col-12' id=\"" + divName
			+ "\" style='width:100%; min-height: 200px; padding: 0px'></div>");
	var myChart = echarts.init($("#" + divName)[0], 'walden');

	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 : 1,
				name : '中心管理员'
			}, {
				value : data.userListCount,
				name : '节点管理员'
			}, {
				value : data.applyListCount,
				name : '申请中'
			} ]
		} ]
	};
	myChart.setOption(option222);

};
var setUSERMANBar = function(data) {
	if ($("#userManBarDiv").css("height") == "0px") {
		console.log("setUSERMANBar: ignore");
		return;
	}
	$("#userManBarDiv")
			.html(
					"<div class='col-12' id='userManBarDivCanv' style='width:100%; min-height: 200px; padding: 0px'></div>");
	var myChart = echarts.init($("#userManBarDivCanv")[0], 'walden');
	
	var xAxisData = data.xAxis;
	var data1 = data.yAxis1;
	var data2 = data.yAxis2;
	
	var option2 = {
		legend : {
			data : [ "当日注册", '当日授权' ]
		},
		toolbox : {
			// y: 'bottom',
			feature : {
				magicType : {
					type : [ 'stack', 'tiled' ]
				},
				dataView : {},
				saveAsImage : {
					pixelRatio : 2
				}
			}
		},
		tooltip : {},
		xAxis : {
			data : xAxisData,
			splitLine : {
				show : false
			}
		},
		yAxis : {},
		series : [ {
			name : '当日注册',
			type : 'bar',
			data : data1,
			animationDelay : function(idx) {
				return idx * 10;
			}
		}, {
			name : '当日授权',
			type : 'bar',
			data : data2,
			animationDelay : function(idx) {
				return idx * 10 + 100;
			}
		} ],
		animationEasing : 'elasticOut',
		animationDelayUpdate : function(idx) {
			return idx * 5;
		}
	};

	myChart.setOption(option2);
};