var initUnitsocket = function() {
	if (global.config == undefined) {
		var param = {};
		param.action = "loadNodeConfig";
		global.wssocket.send(JSON.stringify(param));
		setTimeout(initUnitsocket, 1000);
		return;
	}
	var port = global.config.nodeCenter.replace(/.*:/g, "");
	var len = global.config.nodeCenter.length - port.length;
	port = port - 1;
	var url = global.config.nodeCenter.substring(0, len) + port
			+ "/NodeCenterWS";
	if (window.location.origin == "https://contract.internetapi.cn") {
		url = "wss://cluster.contract.internetapi.cn/NodeCenterWS";
	}
	if (window.location.origin == "http://contract.internetapi.cn") {
		url = "ws://cluster.contract.internetapi.cn/NodeCenterWS";
	}
	console.log("connect :" + url);
	global.unitsocket = createWssocket(url, function() {
		getUnitSession();
	}, WSUnitHandler);
}

// TODO we should get the address from config!
var getUnitWsUrl = function(host) {
	var prefix = "ws://";
	if (document.location.href.startsWith("https"))
		prefix = "wss://";
	var path = "NodeCenterWS";
	var port = ":18001";
	if (host == "contract.internetapi.cn") {
		host = "cluster.contract.internetapi.cn";
		port = "";
	}
	return prefix + host + port + "/" + path;
};

var getUnitSession = function() {
	if(global.centerportalws == undefined || global.centerportalws == null || global.centerportalws.send == undefined || global.centerportalws.send == null){

	}
	global.centerportalws.send("{\"action\":\"getSessionID\"}");
};

var onSessionID = function(data) {
	global.session = data.session;

	var loginParam = {};
	loginParam.pubKey = global.sm2Key.publicKey;
	loginParam.signature = sm2.doSignature(global.session,
			global.sm2Key.privateKey,{hash:true,der:true});
	loginParam.action = "login";
	global.centerportalws.send(JSON.stringify(loginParam));

};

var onLogin = function(data) {
	// console.log(data);
};

var distributeContract = function() {
	var place = $("#selectUnits")[0].value;
	if (place == "选择节点集群") {
		myToast("提示","请选择集群分发合约!");
		return;
	}

	if(global.ypkName == undefined || global.ypkName == "请选择ypk文件"){
		myToast("提示","请选择文件!");
		return;
	}

	var unitsID = place.split(":")[1];
	var nodeIDs = "";  //公钥
	for ( var i in global.units[unitsID]) {
		if(global.units[unitsID][i].nodeName == global.config.nodeName)
			continue;
		nodeIDs += global.units[unitsID][i].pubKey + ",";
	}

	if(nodeIDs == ""){
		myToast("提示","集群中无需要分发的节点!");
		return;
	}

	var request = {};
	request.action = "distributeContract";
	request.nodeIDs = nodeIDs;
	request.projectName = global.ypkName;
	request.isPrivate = global.ypkIsPrivate;
	//request.sponsorName = global.config.nodeName;
	request.signature = sm2.doSignature("DistributeContract|"
			+ request.projectName + "|" + global.sm2Key.publicKey,
			global.sm2Key.privateKey,{hash:true,der:true}); // 合约的签名
	console.log(request);
	//global.centerportalws.send(JSON.stringify(request));
	global.wssocket.send(JSON.stringify(request));
};

var onDistributeContract = function(obj) {
	updateResultDisplay(obj);
};

var onDistributeFinish = function(obj) {
	customAlert("合约分发完成!");
};

// 将所选周期转化为毫秒
var switchPeriod = function(per) {
	switch (per) {
	case '/12hours自动保存':
		return (12 * 3600 * 1000) + "";
	case '/1day自动保存':
		return (24 * 3600 * 1000) + "";
	case '/2days自动保存':
		return (48 * 3600 * 1000) + "";
	default:
		return "";
	}
};

// 本地启动
var startContractAtSlave = function() {
	//this is for fixed contract,not for the unit contract
	var period = $("#selectDumpPeriod")[0].value;
	if (period == "选择状态保存模式") {
		myToast("提示","请选择状态保存模式!");
		return;
	}
	var dumpPeriod = switchPeriod(period);
	var project = global.ypkName;

    $("#result")[0].innerHTML="正在启动，请稍候";
	var request = {};
	request.action = "startContractByYPK";
	request.dumpPeriod = dumpPeriod;
	request.isPrivate = global.ypkIsPrivate;
	request.owner = global.sm2Key.publicKey;
	request.requestID = new Date().getTime() + "";
	// request.contractid = $("#tabdiv")[0].value;
	// request.script = global.scriptEditor.getValue();
	request.path = "/" + project;
	localStorage.setItem("persisStatus", JSON.stringify(request));
	{
		request.signature = sm2.doSignature("Fixed|" + request.path + "|"
				+ global.sm2Key.publicKey, global.sm2Key.privateKey,{hash:true,der:true});
		request.script = "empty";
	}
	console.log(request);
	global.wssocket.send(JSON.stringify(request));
};

var onStartContract = function(obj) {
	listContractProcess();
	updateResultDisplay(obj);
};

// 集群启动合约
var startContractUnits = function(place) {
	// ZYX
	var unitsID = $("#selectUnits")[0].value.split(":")[1];
	if(unitsID == undefined || unitsID == "选择节点集群"){
		myToast("提示","请选择节点集群!");
		return;
	}

	var peersID = "";
	for ( var i in global.units[unitsID]) {
		peersID += global.units[unitsID][i].pubKey + ",";
	}

	var request = {};

	request.action = "startContractMultiPoint";
	request.peersID = peersID;
	request.type  = $("#sequence")[0].value;
	console.log(request.type);
	if (request.type==0){
        myToast("提示","请选择集群合约模式!");
        return;
	}
	request.projectName = global.ypkName;
	if (request.projectName==undefined || request.projectName == "请选择ypk文件"){
		myToast("提示","请选择合约!");
		return;
	}
	request.isPrivate = global.ypkIsPrivate;
	request.sponsorPeerID = global.peerID;   //peerID of the node
	console.log(request);
	global.wssocket.send(JSON.stringify(request));
};

var onStartTrustfulContract = function(obj) {
	console.log(obj);
	 $("#dialogBodyDiv").html("");
	customAlert("集群启动合约已完成!请等待各节点的结果(<span id='countDown'>20</span>)");
    setTimeout(decreaseCountDown,1000);
};
var decreaseCountDown = function(){
    if ($("#countDown").length!=1){
        return;
    }
    var val = $("#countDown").html();
    val/=1;
    if (val>0) val--;
    $("#countDown").html(val);
    setTimeout(decreaseCountDown,1000);
}
var onStartContractTrustfullyResult = function(obj){
    var data = JSON.parse(obj.data);
    $("#countDown").remove();
    $("#customAlertSpan").html("集群启动合约已完成!总共用时("+obj.executionTime+"ms)");
    if ($("#startP2PResultTable").length>0){
    }else{
        var html = "<table id='startP2PResultTable' style='width:100%'  ><thead><tr><td>PubKey</td><td>结果</td></tr></thead><tbody>";
        html+="</tbody></table>";
        $("#customAlertSpan").parent().append(html);
        $("#startP2PResultTable").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 : [ [ 1, 'desc' ] ],
     				"columnDefs" : []
     			});
    }
    var p =  $("#startP2PResultTable").DataTable();
    p.row.add([data.pubKey.substr(0,6),data.result]);
    p.row().draw();
};

var customAlert = function(msg){
    if ($("#customAlertSpan").length>0){
        $("#customAlertSpan").append("<br/>"+msg);
    } else {
        var body = "<div class='row'><div class='col-sm-12'><span id='customAlertSpan'>";
    	body +=msg;
    	body += "</span></div></div>";
    	$("#dialogBodyDiv").html(body);
        showDialog("提示",function(){
            $("#dialogBodyDiv").html("");
        });
    }
};

var startContractConfig = function() {
    if (global.ypkIsPrivate) {
        myToast("提示","私有合约不支持随机执行");
        return
    }
    var project = global.ypkName;
    if(project==undefined) {
        myToast("提示","未选择合约");
        return
    }
    var num = document.getElementById("selectUnitNum").value;
    var re = /^[0-9]+.?[0-9]*/;//判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/
    if (!re.test(num)) {
        myToast("提示","请选择合理节点数量");
        return
    }
    var nameParts = $("#selectUnits")[0].value.split("_");
    var unitsID = nameParts[1];
    var request = {};
    var peers;
    var network = $("#network")[0].value;
    if (unitsID == undefined) {
        console.log("unitsID " + unitsID);
    } else if (network == 1) {
        peers = global.p2pNodes;
    } else {
        peers = global.units[unitsID];
    }
    if (peers.length < num) {
        myToast("失败","节点数量 > 集群节点数量");
        return
    }
    var peersID = "";
    for ( var i in peers) {
        if (peers[i].peerID) {
            peersID += peers[i].peerID +" ";
        } else {
            peersID += peers[i] + " ";
        }
    }
    console.log("peers ", peersID)
    request.action = "startContractConfig";
    request.type = network;
    request.peersID = peersID;
    request.num = num;
    request.path = "/" + project;
    request.contractName = project;
    request.signature = sm2.doSignature("Trusted|" + request.path + "|"
        + global.sm2Key.publicKey, global.sm2Key.privateKey); // 合约的签名
    request.sequencing = $("#sequence")[0].value;
    request.response = $("#response")[0].value;
    console.log("startContractConfig",request)
    global.wssocket.send(JSON.stringify(request));
}

var onStartContractConfig = function(obj) {
	updateResultDisplay(obj);
	listContractProcess();
};

var onHashResult = function(obj) {
	$("#hashDisplayDiv").html("溯源指纹:"+obj.data);
};

var startTestADSP = function(obj){
	var request = {};
	request.action = "startTestADSP";
	global.centerportalws.send(JSON.stringify(request));
};

var onStartTestADSP = function(obj){
	myToast("提示","开始测试ADSP!");
};