// 在WSHandler的onUserList之类的方法里使用。
// -----------------------------------------------
var loadAuditLog = function() {
	$('[data-toggle="tooltip"]').tooltip();
	console.log("loadAuditLog!");
	
	changePie1Time($("#pie1")[0].value);
	changePie2Time($("#pie2")[0].value);

	changeLine1Time($("#line1")[0].value);
	changeLine2Time($("#line2")[0].value);
	
	document.getElementById('manageLogInput').value="2";
	changeManageLogTime(2);   //默认查看近2天的日志
	document.getElementById('CMLogInput').value="2";
	changeCMLogTime(2);
};

var changePie1Time = function(data){
	var time = data.split("天")[0];
	setTimeout(function() {
		var arg = {};
		arg.action = "listManageLogPie";
		arg.date = new Date().getTime() - 24 * 3600 * 1000 * time;
		global.wssocket.send(JSON.stringify(arg));
	}, 300);
};

var changePie2Time = function(data){
	var time = data.split("天")[0];
	setTimeout(function() {
		var arg = {};
		arg.action = "listCMLogPie";
		arg.date = new Date().getTime() - 24 * 3600 * 1000 * time;
		global.wssocket.send(JSON.stringify(arg));
	}, 300);
};

var changeLine1Time = function(data){
	var time = data.split("天")[0];
	global.ManageLineTime = time;
	setTimeout(function() {
		var arg = {};
		arg.action = "listManageLogLine";
		arg.date = new Date().getTime() - 24 * 3600 * 1000 * global.ManageLineTime;
		arg.start = getDateDaysBefore(global.ManageLineTime);
		global.wssocket.send(JSON.stringify(arg));
	}, 300);
};

var changeLine2Time = function(data){
	var time = data.split("天")[0];
	global.CMLineTime = time;
	setTimeout(function() {
		var arg = {};
		arg.action = "listCMLogLine";
		arg.date = new Date().getTime() - 24 * 3600 * 1000 * global.CMLineTime;
		arg.start = getDateDaysBefore(global.CMLineTime);
		global.wssocket.send(JSON.stringify(arg));
	}, 300);
};

var onListManageLogPie = function(data){
	//console.log(data.data);
	drawLogPie("auditLogPieDiv", data.data, logActionToCategory);
};

var onListCMLogPie = function(data){
	//console.log(data.data);
	drawLogPie("auditCMLogPieDiv", data.data, cmActionToCategory);
};

var onListManageLogLine = function(data){
	//console.log(data.data);
	drawLogBar("auditLogBarDiv", data);
};

var onListCMLogLine = function(data){
	//console.log(data.data);
	drawLogBar("auditCMLogBarDiv", data);
};

var customAlert = function(message, title) {
	if (!title)
		title = '提示';

	if (!message)
		message = 'No Message to Display.';

	$('<div></div>').html(message).dialog({
		title : title,
		resizable : false,
		modal : true,
		buttons : {
			'Ok' : function() {
				$(this).dialog('close');
			}
		}
	});
};

var changeManageLogTime = function(){
	var data = document.getElementById('manageLogInput').value;
	data = parseInt(data);
	// console.log(data);
	if(data > 30 || data < 1){
		customAlert("超出时间范围!");
		return;
	}
	
	global.manageLogTime = parseInt(data);
	setTimeout(function() {
		var arg = {};
		arg.action = "queryActionLog";
		arg.date = new Date().getTime() - 24 * 3600 * 1000 * global.manageLogTime;
		global.wssocket.send(JSON.stringify(arg));
	}, 300);
};

var changeCMLogTime = function(){
	var data = document.getElementById('CMLogInput').value;
	data = parseInt(data);
	// console.log(data);
	if(data > 30 || data < 1){
		customAlert("超出时间范围!");
		return;
	}
	
	global.CMLogTime = parseInt(data);
	setTimeout(function() {
		var arg = {};
		arg.date = new Date().getTime() - 24 * 3600 * 1000 * global.CMLogTime;
		arg.action = "queryCMLog";
		arg.reverse = true;
		arg.filter = "syncPing";
		global.wssocket.send(JSON.stringify(arg));
	}, 300);
};

var auditConf = {
	firstRowHeight : '200px'
};
// -----------------------------------------------
var logActionToCategory = function(action) {
	switch (action) {
	case 'getSessionID':
	case 'login':
	case 'getRole':
		return "登录类";
	case 'listAllUsers':
	case 'listApplyList':
	case 'applyRole':
	case 'accept':
	case 'delete':
	case 'authNodeManager':
		return "用户类";
	case 'queryCMLog':
	case 'queryActionLog':
	case 'queryUserStat':
	case 'listManageLogPie':
	case 'listCMLogPie':
	case 'listManageLogLine':
	case 'listCMLogLine':
		return "日志类";
	case 'listLicence':
	case 'updateLicence':
	case 'listNodes':
	case 'listTrustUnits':
	case 'getNodeTrustUnits':
	case 'distributeContract':
	case 'startContractTrustfully':
	case 'createTrustUnit':
		return "维护类";
	default:{
		// console.log(action);
		return "其他类";
	}
	}
};
var cmActionToCategory = function(action) {
	switch (action) {
	case "syncPing":
		return undefined;
	case "setNodeID":
	case "onGetUDPID":
		return "连接类";
	case "listCMInfo":
	case "updateContract":
		return "状态更新类";
	case "pubEvent":
	case "subEvent":
	case "executeContractOnOtherNodes":
	case "eonReceiveContractExecution":
	case "receiveProject":
	case "onReceiveProject":
	case 'onStartEachNode':
		return "合约执行类";
	default:{
		// console.log(action);
		return "其他类";
	}
	}
};

var drawLogPie = function(id, data, cateFun) {
	if(id == "auditLogPieDiv"){
		$("#Pie1").html("管理操作分类统计（" + global.manageLogTime + "日）");
	}else if(id == "auditCMLogPieDiv"){
		$("#Pie2").html("合约操作分类统计（" + global.CMLogTime + "日）");
	}
	
	if ($("#" + id).css("height") == "0px") {
		console.log("drawLogPie: ignore");
		return;
	}
	$("#" + id).html(
			"<div class='col-12' id='" + id
					+ "Canv' style='width:100%; min-height: "
					+ auditConf.firstRowHeight + "; padding: 0px'></div>");
	var result = {};
	for (var i = 0; i < data.length; i++) {
		var obj = JSON.parse(data[i]);
		var act = cateFun(obj.action)
		if (act == undefined)
			continue;
		if (result[act] == undefined) {
			result[act] = obj.times;
		} else
			result[act] += obj.times;
	}
	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 = {
		toolbox : {
			show : true,
			feature : {
				restore : {},
				saveAsImage : {}
			}
		},
		tooltip : {
			trigger : 'item',
			formatter : '{a} <br/>{b}: {c} ({d}%)'
		},
		legend : {
			y : 'bottom',
			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 drawLogBar = function(id, data) {
	time = 30;
	var startTime;
	if(id == "auditLogBarDiv"){
		time = global.manageLogTime;
		$("#Bar1").html("管理操作每日统计（" + global.manageLogTime + "日）");
		startTime = getDateDaysBefore(global.ManageLineTime);
	}else if(id == "auditCMLogBarDiv"){
		time = global.CMLogTime;
		$("#Bar2").html("合约操作每日统计（" + global.CMLogTime + "日）");
		startTime = getDateDaysBefore(global.CMLineTime);
	}
	
	
	if ($("#" + id).css("height") == "0px") {
		console.log("drawLogBar: ignore");
		return;
	}
	$("#" + id).html(
			"<div class='col-12' id='" + id
					+ "Canv' style='width:100%; min-height: "
					+ auditConf.firstRowHeight + "; padding: 0px'></div>");
	var myChart = echarts.init($("#" + id + "Canv")[0], 'walden');
	var xAxisData = data.xAxis;
	var data1 = data.yAxis;
	
	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 : data1,
			markPoint : {
				data : [ {
					type : 'max',
					name : '最大值'
				}, {
					type : 'min',
					name : '最小值'
				} ]
			},

		} ]
	};

	myChart.setOption(option);

};
var drawLogTable = function(id, data) {
	
	if ($("#" + id).css("height") == "0px") {
		console.log("drawLogTable: 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='"
			+ id
			+ "Tab' class='table display row-border'><thead><tr><th>序号</th><th>时间</th><th>操作</th><th>公钥</th></tr></thead><tbody>";
	var tableTail = "</tbody></table>";

	console.log("drawLogTable");
	var html = tableHead;
	var lines = data.data;
	
	for (var i = 0; i < lines.length; i++) {
		var obj = JSON.parse(lines[i]);
		html += "<tr><td>";
		html += (i + 1);
		html += ("</td><td>");
		html += (obj.date);
		html += ("</td><td>");
		html += (obj.action);
		html += ("</td><td>");
		html += (obj.pubKey);
		html += "</td> </tr>";
	}
	html += applyTableTail;
	$("#" + id).html(html);
	$("#" + id + "Tab").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) {
								return new Date(data / 1).toLocaleString();
							}
						},
						{
							"targets" : 3,
							"render" : function(data, type, row, meta) {
								if (data.length > 15)
									return "<span title='" + data + "'>"
											+ data.substring(0, 25)
											+ "  ...</span>";
								else
									return data;
							}

						} ]
			});
};
