//初始化日志菜单
var initLocalLog = function() {
	$('[data-toggle="tooltip"]').tooltip();
	console.log("initLog!");
	changePie1Time($("#pie1")[0].value);
	changePie2Time($("#pie2")[0].value);
	changeLine1Time($("#line1")[0].value);
	changeLine2Time($("#line2")[0].value);
	document.getElementById('nodeLogInput').value="2";
	changeNodeLogTime(2);   //默认查看近2天的日志
	document.getElementById('contractLogInput').value="2";
	changeContractLogTime(2);
	document.getElementById('ledgerLogInput').value="10";
    changeLedgerLogCount(10);

	// changeLedgerLogCount(10);
};

var changePie1Time = function(data){
    var cate = ['getNodeSessionID',
               'login',
               'getNodeRole',
               'listAllAuthRole',
               'listUnAuthRole',
               'countRole',
               'applyNodeRole',
               'authNodeRole',
               'deleteRole',
               'listLocalNodeLog',
               'listLocalContractLog',
               'listLocalNodeLogPie',
               'listLocalNodeLogLine',
               'listLocalContractLogPie',
               'listLocalContractLogLine',
               'onGetHashCount',
               'onQueryDataByHash',
               'loadNodeConfig',
               'updateLicence',
               'listNodes',
               'changeNodeName',
               'changeYJSPath',
               'changeNodeCenter',
               'getPeerID',
               'getNodeID',
               'uploadLicence',
               'connectTo',
               'startContract',
               'initcodeManage',
               'listContractProcess',
               'startContractBatched',
               'startContractConfig',
               'killContractProcess',
               'killAllContract',
               'switchProject',
               'stopContract',
               'staticVerify',
               'staticVerifyContractByPath',
               'executeContract',
               'dumpContract',
               'loadMemory',
               'changeDumpPeriod',
               'getDumpPeriod',
               'startSync',
               'stopSync',
               'changeSyncType',
               'getSyncType',
               'recoverBySync',
               'deleteFile',
               'uploadFile',
               'downloadContract',
               'listProjects',
               'listProject',
               'listFile',
               'createFile',
               'uploadRequest',
               'changePublic',
               'listMemoryFiles',
               'saveFile'
               ];
;
	var time = data.split("天")[0];
	setTimeout(function() {
		var arg = {};
		arg.action = "countNodeLogGroupByCategory";
		arg.start = new Date().getTime() - 24 * 3600 * 1000 * time;
        arg.interval = 24*3600*1000*time+24*3600*500;
        arg.category = cate.join(",");
		global.wssocket.send(JSON.stringify(arg));
	}, 300);
};

var changePie2Time = function(data){
	var time = data.split("天")[0];
	setTimeout(function() {
		var arg = {};
		arg.action = "listLocalContractLogPie";
		arg.action = "countContractLogGroupByAction";
		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.line1Time = time;
	setTimeout(function() {
		var arg = {};
		arg.action = "countNodeLogGroupByCategory";
		arg.start = getDateDaysBefore(global.line1Time);
		arg.interval = 24*3600*1000;
		global.wssocket.send(JSON.stringify(arg));
	}, 300);
};

var changeLine2Time = function(data){
	var time = data.split("天")[0];
	global.line2Time = time;
	setTimeout(function() {
		var arg = {};
		arg.action = "countContractLogGroupByCategory";
	    arg.start = getDateDaysBefore(global.line2Time);
		arg.interval = 24*3600*1000;
		global.wssocket.send(JSON.stringify(arg));
	}, 300);
};

var changeNodeLogTime = function(){
	var data = document.getElementById('nodeLogInput').value;
	data = parseInt(data);
	if (data > 30 || data < 1) {
		customAlert("超出时间范围!");
		return;
	}

	global.nodeLogTime = parseInt(data);
	setTimeout(
			function() {
				var arg = {};
				arg.action = "queryNodeLogByDate";
				arg.start = getDateDaysBefore(data);
				global.wssocket.send(JSON.stringify(arg));
			}, 300);
};

var changeContractLogTime = function() {
	var data = document.getElementById('contractLogInput').value;
	data = parseInt(data);
	if (data > 30 || data < 1) {
		customAlert("超出时间范围!");
		return;
	}

	global.contractLogTime = data;
	setTimeout(function() {
		var arg = {};
		arg.action = "listLocalContractLog";
		arg.action = "queryContractLogByDate";
		arg.start = new Date().getTime() - 24 * 3600 * 1000
				* global.contractLogTime;
		global.wssocket.send(JSON.stringify(arg));
	}, 300);
};

var changeLedgerLogCount = function() {
	var data = document.getElementById('ledgerLogInput').value;
	data = parseInt(data);
	if (data > 200 || data < 1) {
		customAlert("超出条数范围!");
		return;
	}
	global.ledgerCount = data;
	
	var url = window.location.href.replace("/NodePortal.html", "");
	if (url.indexOf("SCIDE") != -1)
		url += "/CMManager?";
	else
		url += "/SCIDE/CMManager?";
	var arg = "action=queryHashByOffset&count=" + data;
	$.ajax({
		url : url + arg,
		dataType : "json"
	}).done(function(result) {
		fillLedgerLogData(result.data);
	});
};

var onListLocalNodeLogPie = function(data){
	drawLocalNodeLogPie(data.data);
};

var onListLocalContractLogPie = function(data){
	drawLocalContractLogPie(data.data);
};

var onListLocalNodeLogLine = function(data){
       	drawLocalNodeLogLine("auditLocalNodeLogLine",data);


};

var onListLocalContractLogLine = function(data){
    var xyAxis = {};
    var startTime = data.start;
    var interval = data.interval;
	xyAxis.xAxis=[];
	xyAxis.yAxis=data.data;
	for (var i=0;i<xyAxis.yAxis.length;i++){
        xyAxis.xAxis.push(new Date(startTime).toISOString().substring(0, 10));
        startTime+=interval;
    }
	drawLocalContractLogLine("auditLocalContractLogLine",xyAxis);
};

var drawLocalLogLine = function(data) {
    if (data.interval<=24*3600*1000){
	    console.log("drawLocalLogLine");
	    var xyAxis = {};
        var startTime = data.start;
        var interval = data.interval;
	    xyAxis.xAxis=[];
	    xyAxis.yAxis=data.data;
	    for (var i=0;i<xyAxis.yAxis.length;i++){
    	    xyAxis.xAxis.push(new Date(startTime).toISOString().substring(0, 10));
            startTime+=interval;
        }
	    drawLocalNodeLogLine("auditLocalNodeLogLine",xyAxis);
	}else{
	    var pieData = [];
	    for (var i in data.data){
	        var obj = {};
	        obj.action = i;
	        obj.times = data.data[i][0];
	        pieData.push(JSON.stringify(obj));
	    }
	    drawLocalNodeLogPie(pieData);
	}

};
var onQueryContractLogByDate = function(data){
	fillLocalContractLogData(data.data);
};
var onListLocalContractLog = function(data) {
	var dataList = filtUndefined(data.data);
	fillLocalContractLogData(dataList);
};

var fillLocalNodeLogData = function(data) {
	console.log("fillLocalNodeLogData");
	var tableHead = "<table id='localNodeLogTab' 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 html = tableHead;
	var lines = data;
	global.localNodeLog = lines;
	for (var i = 0; i < lines.length; i++) {
		var obj = (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.status);
		html += ("</td><td>");
		html += (obj.pubKey);
		html += "</td> </tr>";
	}

	html += tableTail;
	$("#localNodeLog").html(html);

	$("#localNodeLogTab").DataTable(
			{
				"language" : dtLocalLang,
				"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" : 4,
							"render" : function(data, type, row, meta) {
								if (data.length > 15)
									return "<span title='" + data + "'>"
											+ data.substring(0, 25)
											+ "  ...</span>";
								else
									return data;
							}

						} ]
			});
};

var contractLogDetail = function(key){
	var url = window.location.href.replace("/NodePortal.html", "");
	if (url.indexOf("SCIDE") != -1)
		url += "/CMManager?";
	else
		url += "/SCIDE/CMManager?";
	var arg = "action=queryContractLogByKey&key=" + key+"&pubKey="+global.sm2Key.publicKey;
	var sign = sm2.doSignature(arg,global.sm2Key.privateKey,{der:true,hash:true});
	arg = arg+"&sign="+sign;
	window.open(url+arg);
};

var fillLocalContractLogData = function(data) {
	console.log("fillLocalContractLogData");
	var tableHead = "<table id='localContractLogTab' class='table display row-border'><thead><tr><th>序号</th><th>时间</th><th>操作</th><th>合约ID</th><th>合约NAME</th><th>查看详情</th></tr></thead><tbody>";
	var tableTail = "</tbody></table>";
	var html = tableHead;
	var lines = data;
	global.localNodeLog = lines;
	for (var ii = 0; ii < lines.length; ii++) {
		var obj;
		try {
			obj = lines[ii];
		} catch (e) {
			console.log("====fillLocalContract " + ii + " LogData====");
			// console.log(lines[ii]);
		}
		html += "<tr><td>";
		html += (ii + 1);
		html += ("</td><td>");
		html += (obj.date);
		html += ("</td><td>");
		html += (obj.action);
		html += ("</td><td>");
		html += (obj.contractID);
		html += ("</td><td>");
		html += (obj.contractName);
		html += ("</td><td  style='padding:4px 12px 4px 12px'>");
		html += "<button type='button' class='btn btn-secondary' onclick='contractLogDetail(\"" + obj.key + "\")'>详情</button>";
		html += "</td></tr>";
	}

	html += tableTail;
	$("#localContractLog").html(html);
	
	$("#localContractLogTab").DataTable(
			{
				"language" : dtLocalLang,
				"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();
							}
						} ]
			});
};

var queryHashDetail = function(hash){
	var url = window.location.href.replace("/NodePortal.html", "");
	if (url.indexOf("SCIDE") != -1)
		url += "/CMManager?";
	else
		url += "/SCIDE/CMManager?";
	var arg = "action=queryDataByHash&hash=" + hash;
	window.open(url+arg);
};

var fillLedgerLogData = function(lines) {
	var tableHead = "<table id='ledgerLogTab' class='table display row-border'><thead><tr><th>序号</th><th>时间</th><th>哈希值</th><th>查看详情</th></tr></thead><tbody>";
	var tableTail = "</tbody></table>";
	var html = tableHead;

	for (var ii = 0; ii < lines.length; ii++) {
		var obj;
		try {
			obj = lines[ii];
		} catch (e) {
			console.log("====fillLocalContract " + ii + " LogData====");
			// console.log(lines[ii]);
		}

		var hash = obj.hash;
		var date = obj.date;
		
		html += "<tr><td>";
		html += (ii + 1);
		html += ("</td><td>");
		html += date;
		html += ("</td><td>");
		html += hash;
		html += ("</td><td style='padding:4px 12px 4px 12px'>");
		html += "<button type='button' class='btn btn-secondary' onclick='queryHashDetail(\"" + hash + "\")'>详情</button>";
		html += "</td></tr>";
	}

	html += tableTail;
	$("#ledgerLog").html(html);
	
	$("#ledgerLogTab").DataTable(
			{
				"language" : dtLocalLang,
				"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();
							}
						}]
			});
};

var queryDataByHash = function() {
	// var ledger = $("#ledgerInput")[0].value;
	var hash = $("#hashInput")[0].value;
	var url = window.location.href.replace("/NodePortal.html", "");
	if (url.indexOf("SCIDE") != -1)
		url += "/CMManager?";
	else
		url += "/SCIDE/CMManager?";
	var arg = "action=queryDataByHash&hash=" + hash;
	window.open(url+arg);
};