function loadNodeConfig(event) {
    setTimeout(function () {
        console.log("loadNodeConfig");
        global.wssocket.send(JSON.stringify({
            action: 'loadNodeConfig'
        }));
        getPeerID();
    }, 300);
}

function onLoadNodeConfig(data) {
    global.config = data.data;
    if (!global.centerportalws) {
        let port = global.config.nodeCenter.replace(/.*:/g, "");
        const len = global.config.nodeCenter.length - port.length;
        port = port - 1;
        let 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("centerportalws:", url)
        global.centerportalws = createWssocket(url, function () {
            global.centerportalws.send(JSON.stringify({
                action: 'getSessionID'
            }));
        }, centerportalWSHandler);
    }
    showNodeConfig(data);
}

function showNodeConfig(data) {
    if (global.config) {
        const nodeCenterInputEl = $("#nodeCenterInput");

        $("#nodeNameInput")[0].value = global.config.nodeName;
        $("#ipPortInput")[0].value = global.config.ipPort;
        $("#doipConfigInput")[0].value = global.config.doipConfig;
        $("#masterAddrInput")[0].value = global.config.masterAddress;
        $("#peerIDInput")[0].value = global.config.peerID;
        $("#licence")[0].value = global.config.licence
        $("#expireTime").html(global.config.expireTime);
        $("#yjsInput")[0].value = global.config.yjsPath;
        nodeCenterInputEl[0].value = global.config.nodeCenter;
        if (global.config.clusterConnected && global.config.clusterConnected === "true") {
            nodeCenterInputEl.css("color", "green");
        } else {
            nodeCenterInputEl.css("color", "red");
        }

        $("#bdledgerPeersInput")[0].value = global.config.bdledger;
        showNodeTrustUnits();
    }

//			switch (data) {
//			case "onGetLicenceExpiredDate":
//				$("#expiredDate").html(convertDate(data.data));
//				break;
//			case "onGetEncodedUUID":
//				localStorage.setItem("EncodedUUID", data.data);
//				global.EncodedUUID = localStorage.getItem("EncodedUUID");
//				break;
//			case "jiedianguanliyuan":
//				$("#projectDirInput")[0].value = (data.data.projectDir);
//				$("#yjsInput")[0].value = (data.data.yjsPath);
//				$("#dataChainInput")[0].value = data.data.datachainConf;
//				$("#nodeCenterInput")[0].value = data.data.nodeCenter;
//				
//				break;
//			case "onUpdateConfig":
//				if (data.status==false){
//					alert("updata failed! please check the file.");
//				}
//				
//				break;
//			default:
//				console.log("Unknown msg:");
//				console.log(event);
//			}

}


function changeNodeName(event) {
    console.log("changeNodeName");
    global.wssocket.send(JSON.stringify({
        action: 'changeNodeName',
        data: $("#nodeNameInput")[0].value
    }));
}

function changeIpPort(event) {
    var input = $("#ipPortInput")[0].value
    var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/
    if (!reg.test(input)) {
        myToast("无效地址", "不符合xxx.xxx.xxx.xxx:xxxx格式")
        return
    }
    console.log("changeIpPort");
    global.wssocket.send(JSON.stringify({
        action: 'changeIpPort',
        data: input
    }));
}

function changeDOIPConfig(event) {
    var input = $("#doipConfigInput")[0].value
    console.log("changeDOIPConfig");
    global.wssocket.send(JSON.stringify({
        action: 'changeDOIPConfig',
        data: input
    }));
}

function changeMasterAddress(event) {
    global.wssocket.send(JSON.stringify({
        action: 'updateConfig',
        key: 'masterAddress',
        val: $("#masterAddrInput")[0].value
    }));
}

function onChangeNodeName(data) {
    console.log("onChangeNodeName", data);
    //$("#nodeNameInput")[0].value = data;
    myToast("成功", "修改NodeName成功")
}

function onChangeIpPort(data) {
    console.log("onChangeIpPort", data);
    myToast("成功", "修改IP端口成功")
}

function onChangeDOIPConfig(data) {
    console.log("onChangeDOIPConfig", data);
    myToast("成功", "修改IP端口成功")
}

var changeYJSPath = function (event) {
    console.log("changeYJSPath");
    global.wssocket.send(JSON.stringify({
        action: 'changeYJSPath',
        data: $("#yjsInput")[0].value
    }));
};

function onChangeYJSPath(data) {
    //$("#yjsInput")[0].value = data;
    //	loadNodeConfig();
    //showNodeConfig();
    let body = "<div class='row'><div class='col-sm-12'><span id='onChangeYJSPathResult'>";
    body += "修改YJS路径, " + ((data.data === true ? "成功" : "失败，请检查路径"));
    body += "</span></div></div>";
    $("#dialogBodyDiv").html(body);
    showDialog("提示", function () {
        loadNodeConfig();
    });
}

function changeNodeCenter(event) {
    console.log("changeNodeCenter");
    global.wssocket.send(JSON.stringify({
        action: 'changeNodeCenter',
        data: $("#nodeCenterInput")[0].value
    }));
}

function onChangeNodeCenter(event) {
    // console.log("onChangeNodeCenter", data);
    myToast("成功", "修改NodeCenter成功")
    loadNodeConfig();
    //刷新整个页面
}

function changeBDledger(event) {
    console.log("changeBDledger");
    global.wssocket.send(JSON.stringify({
        action: 'changeBDledger',
        data: $("#bdledgerPeersInput")[0].value
    }));
    loadNodeConfig();
}

function onChangeBDledger(event) {
    console.log("onChangeBDledger", data);
    myToast("成功", "修改数链节点成功")
}

function getLicenceExpiredDate() {
    global.cmsocket.send("{\"action\":\"getLicenceExpiredDate\"}");
}

function uploadLicence() {
    console.log("uploadLicence");
    global.wssocket.send(JSON.stringify({
        action: 'uploadLicence',
        data: $("#licence")[0].value
    }));
}

function onUploadLicence(data) {
    console.log("onUploadLicence");
    myToast("成功", "上传Licence成功")
}

function getPeerID(data) {
    global.wssocket.send(JSON.stringify({
        action: 'getPeerID'
    }));
}

function getNodeTrustUnits(data) {
    const param = {
        action: 'getNodeTrustUnits',
        data: global.peerID
    };
    // console.log("getNodeTrustUnits", JSON.stringify(param));
    global.centerportalws.send(JSON.stringify(param));
}

function onGetNodeTrustUnits(obj) {
    // mainVue
    mainVue.unitCount = obj.data.length;
    addTcpNodeUnits(obj.data);
    global.nodeUnits = obj.data;
    //showNodeTrustUnits();
    var json = {};
    json.action = "updateNodeUnits";
    json.data = JSON.stringify(obj.data);
    global.wssocket.send(JSON.stringify(json));
}

function showNodeTrustUnits(obj) {
    // console.log("[showNodeTrustUnits]" + obj);
    const 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": ": 以降序排列此列"
        }
    };
    let html = "<table class='table display row-border' id='trustNodesUnitTabDivTab'>" +
        "<thead><tr><th>序号</th><th>ID</th><th>类型</th><th>创建者</th><th>节点数目</th><th>节点公钥</th></tr></thead>" +
        "<tbody>";
    const tableTail = "</tbody></table>";
    if (global.nodeUnits) {
        for (let i = 0; i < global.nodeUnits.length; i++) {
            const at_ = global.nodeUnits[i].key.indexOf("_");
            const nodes = JSON.parse(global.nodeUnits[i].value);
            html += `<tr>
            <td>${i + 1}</td>
            <td>${global.nodeUnits[i].key.substring(at_ + 1)}</td>
            <td>TCP</td>
            <td>${global.nodeUnits[i].key.substring(0, at_ - 1)}</td>
            <td>${nodes.length}</td>
            <td>${JSON.stringify(nodes)}</td>
            </tr>`
        }
    }
    if (global.p2pNodes) {
            html += "<tr><td>" + (i+1) + "</td> <td>P2PUnit</td><td>P2P</td> <td>bdledger</td> <td>" + global.p2pNodes.length + "</td> <td>" + JSON.stringify(global.p2pNodes) + "</td> </tr>";
        }
    html += tableTail;
    $("#trustNodesUnitTabDiv").html(html);
    $("#trustNodesUnitTabDivTab").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": 3,
                "render": function (data, type, row, meta) {
                    if (data.length > 15)
                        return "<span title='" + data + "'>"
                            + data.substring(0, 15)
                            + "  ...</span>";
                    else
                        return data;
                }

            },
            {
                "targets": 5,
                "render": function (data, type, row, meta) {
                    if (data.length > 40)
                        return "<span title='" + data + "'>"
                            + data.substring(0, 40)
                            + "  ...</span>";
                    else
                        return data;
                }

            }]
    });
}

submitReq = function () {
    const request = {};
    request.action = "executeContract";
    request.requestID = new Date().getTime() + "";
    request.contractID = "LicenceService";
    const localArg = {};
    localArg.action = "apply";
    localArg.arg = {};
//	localArg.arg.remark = $("#remark")[0].value;
    localArg.arg.uuid = global.EncodedUUID;
    localArg.arg = JSON.stringify(localArg.arg);
    request.arg = JSON.stringify(localArg);

    request.publicKey = global.privKey.publicKey;
    request.signature = sm2.doSignature(`${request.contractID}|${localArg.action}|${localArg.arg}|${global.privKey.publicKey}`,
        global.privKey.privateKey);
    global.wssocket.send(JSON.stringify(request));
};

flushLicence = function () {
    const request = {};
    request.action = "executeContract";
    request.requestID = new Date().getTime() + "";
    request.contractID = "LicenceService";
    const localArg = {};
    localArg.action = "request";
    localArg.arg = global.EncodedUUID;
    request.arg = JSON.stringify(localArg);
    request.publicKey = global.privKey.publicKey;
    request.signature = sm2.doSignature(`${request.contractID}|${localArg.action}|${localArg.arg}|${global.privKey.publicKey}`,
        global.privKey.privateKey);
    global.lastReqID = request.requestID;
    global.wssocket.send(JSON.stringify(request));
};


downloadUUID = function () {
    window.open(window.location.href.replace("/licence.html", "/SCManager?action=downloadUUID"));
};


