function applyRole(role) {
    global.wssocket.send("{\"action\":\"applyNodeRole\",\"role\":\"" + role
        + "\",\"pubKey\":\"" + global.sm2Key.publicKey + "\"}");
}

function WSHandler(event) {
    // console.log("++++++++++" + event);
    data = event.data;
    // console.log(" -->" + data);
    try {
        var obj = JSON.parse(data);
        // console.log(obj.action);
        switch (obj.action) {
            case 'onGetHashCount':
                onGetHashCount(obj);
                break;
            case 'onStartSync':
                onStartSync(obj);
                break;
            case 'onGetSyncType':
                onGetSyncType(obj);
                break;
            case 'onChangeSyncType':
                onChangeSyncType(obj);
                break;
            case 'onRecoverBySync':
                onRecoverBySync(obj);
                break;
            case 'onStopSync':
                onStopSync(obj);
                break;
            case 'onTransferTo':
                onTransferTo(obj);
                break;
            case 'onHashResult':
                onHashResult(obj);
                break;
            case 'onListMemoryFiles':
                onListMemoryFiles(obj);
                break;
            case 'onDumpContract':
                onDumpContract(obj);
                break;
            case 'onChangeDumpPeriod':
                onChangeDumpPeriod(obj);
                break;
            case 'onGetDumpPeriod':
                onGetDumpPeriod(obj);
                break;
            case 'onStaticVerifyResult':
                onStaticVerifyResult(obj);
                break;
            case 'onListCompiledFiles':
                onListCompiledFiles(obj);
                break;
            case "onListContractProcess":
                onListContractProcess(obj);
                break;
            case "onDeleteFile":
                onDeleteFile(obj);
                break;
            case "onCancelAuth":
                onCancelAuth(obj);
                break;
            case "onDownloadContract":
                onDownloadFile(obj);
                break;
            case "onChangePublic":
                onChangePublic(obj);
                break;
            case "onListProjects":
                onListProjects(obj);
                break;
            case "onListProject":
                onListProject(obj);
                break;
            case "onCountNodeLogGroupByCategory":
                onCountNodeLogGroupByCategory(obj);
                break;
            case "onQueryNodeLogByDate":
                onListLocalNodeLog(obj);

                break;
            case "onListLocalNodeLog":
                onListLocalNodeLog(obj);
                break;
            case "onListLocalNodeLogPie":
                onListLocalNodeLogPie(obj);
                break;
            case "onListLocalNodeLogLine":
                onListLocalNodeLogLine(obj);
                break;
            case "onQueryContractLogByDate":
                onQueryContractLogByDate(obj);
                break;
            case "onCountContractLogGroupByAction":
                onListLocalContractLogPie(obj);
                break;
            case "onListLocalContractLogPie":
                onListLocalContractLogPie(obj);
                break;
            case "onCountContractLogGroupByCategory":
                onListLocalContractLogLine(obj);
                break;
            case "onListLocalContractLogLine":
                onListLocalContractLogLine(obj);
                break;
            case "onSessionID":
                onGetNodeSessionID(obj);
                break;
            case "onLogin":
                onNodeLogin(obj);
                break;
            case "onApplyRole":
                onApplyRole(obj);
                break;
            case "onGetP2PNodes":
                onGetP2PNodes(obj);
                break;
            case "onListAllAuthRole":
                onListAllAuthRole(obj);
                break;
            case "onListUnAuthRole":
                onListUnAuthRole(obj);
                break;
            case "onDeleteRole":
                onDeleteRole(obj);
                break;
            case "onCountRole":
                onCountRole(obj);
                break;
            case "onAuthNodeRole":
                onAuthNodeRole(obj);
                break;
            case "onApplyNet":
                onApplyNet(obj);
                break;
            case "onLoadNodeConfig":
                onLoadNodeConfig(obj);
                break;
            case "onChangeNodeName":
                onChangeNodeName(obj);
                break;
            case "onChangeYJSPath":
                onChangeYJSPath(obj);
                break;
            case "onGetLicenceExpiredDate":
                $("#expiredDate").html(convertDate(data.data));
                break;
            case "onGetPeerID":
                global.peerID = obj.data;
                // getNodeTrustUnits();//still connecting to centerportalws
                break;
            case "onViewContractInstance":
                onViewContractInstance(obj);
                break;
            case 'onExecuteResult':
                onExecuteResult(obj);
                break;
            case 'onUploadFile':
                onUploadFile(obj);
                break;
            case 'onStartContract':
                onStartContract(obj);
                break;
            case 'onStartContractConfig':
                onStartContractConfig(obj);
                break;
            case 'onKillContractProcess':
                onStopContract(obj);
                break;
            case 'onKillAllContract':
                onKillAllContract(obj);
                break;
            case 'onSetPermission':
                onSetPermission(obj);
                break;
            case 'onOutputStream':
                displayOutput(obj);
                break;
            case 'onChangeNodeCenter':
                console.log("onChangeNodeCenter");
                onChangeNodeCenter(obj);
                break;
            case 'onException':
                handleNoPermission(obj);
                break;
            case 'onStartContractTrustfullyResult':
                onStartContractTrustfullyResult(obj);
                break;
            case 'onStartTrustfulContract':
                onStartTrustfulContract(obj);
                break;
            case 'onDistributeContract':
                onDistributeContract(obj);
                break;
            case 'onDistributeFinish':
                onDistributeFinish(obj);
                break;
            case 'onListLeakContractProcess':
                onListLeakContractProcess(obj);
                break;
            default:
                displayOutput(obj);
                break;
        }
    } catch (err) {
        console.log(err);
    }
}

function handleNoPermission(obj) {
    if (!obj.data.startsWith("unauthorised action")) {
        // console.log(obj);
        return;
    }
    global.actionName = obj.data.split(" ")[2];
    // console.log("_______" + global.actionName);
    switch (global.actionName) {
        case "startContract":
        case "killContract":
        case "killAllContract":
        case "listContractProcess":
        case "listProjects":
        case "showNodeTrustUnits":
        case "getDumpPeriod":
        case "changeDumpPeriod":
        case "dumpContract":
        case "loadMemory":
        case "listLocalContractLogPie":
        case "listLocalContractLogLine":
        case "listLocalContractLog":
        case "listMemoryList":
        case "listCompiledFiles":
            alertNoPermission(`当前角色没有${global.actionName}权限，请申请成为ContractInstanceManager`);
            break;
        case "deleteFile":
        case "downloadContract":
        case "uploadFile":
        case "staticVerifyContract":
            alertNoPermission(`当前角色没有${global.actionName}权限，请申请成为ContractProvider`);
            break;
        case "executeContract":
        case "ListContractLog":
        case `queryRecent&count=${global.ledgerCount}`:
            // console.log(`queryRecent&count=${global.ledgerCount}`);
            alertNoPermission(`当前角色没有${global.actionName}权限，请申请成为ContractUser`);
            break;
        default:
            alertNoPermission(`当前角色没有${global.actionName}权限，请申请成为相关角色`);
            break;
    }
}

function displayOutput(obj) {
    console.log(obj);
}

function getControlWsUrl(host) {
    let prefix = "ws://";
    if (document.location.href.startsWith("https")) {
        prefix = "wss://";
    }
    let path = document.location.pathname.lastIndexOf("/");
    path = document.location.pathname.substr(0, path + 1);
    if (path.indexOf("SCIDE") < 0) {
        path += "SCIDE/";
    }
    path += "SCExecutor";
    return prefix + host + path;
}

function initWSocket() {
    const host = document.location.host;
    const url = getControlWsUrl(host);
    // console.log("connect ws:" + url);
    global.wssocket = createWssocket(url, function () {
        getSession();
        //  loadNodeConfig();// get center portal & create centerportalsocket in
        // onLoadNodeConfig
    }, WSHandler);
}

function getSession() {
    global.wssocket.send("{\"action\":\"getSessionID\"}");
}

function exportSMKeyPair() {
    const dialogEl = $("#dialog");
    dialogEl.html(`Save Your key:<br/>${JSON.stringify(global.sm2Key)}`)
    dialogEl.dialog("open");
}

// ====== wsHandler
function onGetNodeSessionID(data) {
    console.log("onGetSessionID");
    global.session = data.session;
    global.wssocket.send(JSON.stringify({
        pubKey: global.sm2Key.publicKey,
        signature: sm2.doSignature(global.session, global.sm2Key.privateKey,{hash:true,der:true}),
        action: "login"
    }));
}

function onNodeLogin(data) {
    console.log("onNodeLogin");
    pubkeyDialogVue.myRole = data.data;
    global.myRole = data.data;
    loadUserMan();
    loadNodeConfig();
}

function apply() {
    const apply = $("#roleGroupSelect04")[0].value;
    console.log(apply);
    // console.log("onGetNodeRole" + global.myRole);
}

function onCountNodeLogGroupByCategory(data) {
    const userManTab = $("#v-pills-userManager-tab")[0];
    if (userManTab.getAttribute("aria-selected") === "true") {
        drawUserActivityGraph(data);
    } else {
        drawLocalLogLine(data);
    }
}

function onListLocalNodeLog(data) {
    const userManTab = $("#v-pills-userManager-tab")[0];
    if (userManTab.getAttribute("aria-selected") === "true") {
        drawUserActivityGraph(data);
    } else {
        fillLocalNodeLogData(data.data);
    }
}

function onListAllAuthRole(data) {
    console.log("onListAllAuthRole");
    fillAuthRoleData(data.data);
}

function onListUnAuthRole(data) {
    console.log("onListUnAuthRole");
    fillUnAuthRoleData(data.data);
}

// var onApplyNet = function(data) {
// console.log("onApplyNet");
// };
function onCountRole(data) {
    console.log("onCountRole");
    setUserTypeDistribution(data.data);
}

function onAuthNodeRole(data) {
    myToast("授权/忽略操作", data.data);
    if (data.data === "success") {
        global.wssocket.send(JSON.stringify({
            action: "listAllAuthRole"
        }));
        global.wssocket.send(JSON.stringify({
            action: "listUnAuthRole"
        }));
    }
}

function onApplyRole(data) {
    // console.log(data.data);
    myToast("申请操作", data.data);
}

function onDeleteRole(data) {
    myToast("删除操作", data.data);
    var loginAllUser = {};
    loginAllUser.action = "listAllAuthRole";
    global.wssocket.send(JSON.stringify(loginAllUser));
}

// ====== wsHandler done!
function myToast(title, msg) {
    toastVue.toastTitle = title;
    toastVue.toastMessage = msg;
    $("#alertDiv").toast("show");
}

function countChar(str, c) {
    let ret = 0;
    for (const ch of str) {
        if (ch === c) {
            ret++;
        }
    }
    return ret;
}

function generate() {
    const key = sm2.generateKeyPairHex();
    global.sm2Key = key;
    localStorage.setItem("PrivKey", JSON.stringify(key));
}

function killAllContract() {
    dialogBodyDiv.innerHTML = "请谨慎操作，是否停止全部实例？";
    showDialog("提示", function () {
        setTimeout(function () {
            var request = {};
            request.action = "killAllContract";
            global.wssocket.send(JSON.stringify(request));
        }, 500);
    });
}

function init() {
    initVue();
    initGlobal();
    initWSocket();
}

function getRequestParameters() {
    const arr = (location.search || "").replace(/^\?/, '').split("&");
    const params = {};
    for (const par of arr) {
        const data = par.split("=");
        if (data.length === 2) {
            params[data[0]] = data[1];
        }
    }
    return params;
}


function onCPLogin(data) {
    if (data.data.indexOf("NodeManager") === -1) {
        customAlert("请先前往准入控制中心，认证成为该网络中的NodeManager");
    } else {
        getNodeTrustUnits();
        global.centerportalws.send(JSON.stringify({
            action: "addNode",
            nodePubKey: global.config.nodePubKey
        }));
    }
}

function onCPGetRole(data) {
    // console.log(data);
}

function centerportalWSHandler(event) {
    // console.log(event);
    data = event.data;
    try {
        const obj = JSON.parse(data);
        switch (obj.action) {
            case "onGetNodeTrustUnits":
                onGetNodeTrustUnits(obj);
                break;
            case 'onSessionID':
                onSessionID(obj);
                break;
            case 'onLogin':
                onCPLogin(obj);
                break;
            case 'onStartContract':
                onStartContract(obj);
                break;
            case 'onStartTrustfulContract':
                onStartTrustfulContract(obj);
                break;
            case 'onDistributeContract':
                onDistributeContract(obj);
                break;
            case 'onDistributeFinish':
                onDistributeFinish(obj);
                break;
            case 'onStartContractTrustfullyResult':
                onStartContractTrustfullyResult(obj);
                break;
            case 'onException':
                handleNoPermission(obj);
                //logException(obj);
                break;
            case 'onStartTestADSP':
                onStartTestADSP(obj);
                break;
            default:
                // console.log(obj);
                break;
        }
    } catch (err) {
        console.log(err);
    }
}

function addNodeUnit(obj) {
    if (!global.units) {
        global.units = {};
    }
    var x=document.getElementById("selectUnits");
    for (i = 0; i < x.length; ++i){
        if (x.options[i].value == obj.key){
          return;
        }
    }
    var option=document.createElement("option");
    var type = obj.type;
    if (type == "TCP") {
        var at_ = obj.key.indexOf("_");
        var key = obj.key.substr(at_+1);
        global.units[key] = obj.value;
        option.text = obj.type + ":" + key;
    } else {
        global.units[obj.key] = obj.value;
        option.text = obj.type + ":" + obj.key + ":" +obj.value.length + "nodes";
    }
    option.value = obj.key;
    x.add(option,null);
}



