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

var WSHandler = function (event) {
    data = event.data;
    try {
        var obj = JSON.parse(data);
        switch (obj.action) {
            case "onSessionID":
                onSessionID(obj);
                break;
            case "onLogin":
                onLogin(obj);
                break;
            case "onListAllUsers":
                onListAllUsers(obj);
                break;
            case "onListApplyList":
                onListApplyList(obj);
                break;
            case "onApply":
                onApply(obj);
                break;
            case "onDelete":
                onDelete(obj);
                break;
            case "onApplyRole":
                onApplyRole(obj);
                break;
            case "onAuthNodeManager":
                onAuthNodeManager(obj);
                break;
            case "onQueryUserStat":
                onQueryUserStat(obj);
                break;
            case "onListLicence":
                onListLicence(obj);
                break;
            case "onUpdateLicence":
                onUpdateLicence(obj);
                break;
            case "onListNodes":
                onListNodes(obj);
                break;
            case 'onListManageLogPie':
                onListManageLogPie(obj);
                break;
            case 'onListCMLogPie':
                onListCMLogPie(obj);
                break;
            case 'onListManageLogLine':
                onListManageLogLine(obj);
                break;
            case 'onListCMLogLine':
                onListCMLogLine(obj);
                break;
            case "onListTrustUnits":
                onListTrustUnits(obj);
                break;
            case "onCreateTrustUnit":
                onCreateTrustUnit(obj);
                break;
            case "onDeleteTrustUnit":
                onDeleteTrustUnit(obj);
                break;
            case "onListMultiPointContractProcess":
                onListMultiPointContractProcess(obj);
                break;
            case "onCountActionLogByCategory":
            case "onQueryCMLog":
            case "onCountCMLogByCategory":
            case "onQueryActionLog":
                invokeDrawCallbacks(obj);
                break;
            case 'onException':
                handleNoPermission(obj);
                break;
            case 'onGetOtherNC':
                onGetOtherNC(obj);
                break;
            case 'onGetNCFile':
                onGetNCFile(obj);
                break;
            case 'onTransfer':
                onTransfer(obj);
                break;
            default:
                displayOutput(obj);
                break;
        }
    } catch (err) {
        console.log(err);
    }
};
var invokeDrawCallbacks = function (obj) {
    global.wscallbacks[obj.responseID](obj);
};
var handleNoPermission = function (obj) {
    global.actionName = obj.data.split(" ")[2];
    switch (global.actionName) {
        case "queryUserStat":
        case "queryCMLogSimple":
            alertNoPermission("当前角色没有" + global.actionName
                + "权限，请申请成为NodeManager");
            break;
        case "listNodes":
        case "listTrustUnits":
            alertNoPermission("当前角色没有" + global.actionName
                + "权限，请申请成为CenterManager或者NodeManager");
            break;
        default:
            alertNoPermission("当前角色没有" + global.actionName
                + "权限，请申请成为CenterManager");
            break;
    }
};


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

var getControlWsUrl = function (host) {
    var prefix = "ws://";
    if (document.location.href.startsWith("https"))
        prefix = "wss://";
    var path = document.location.pathname.lastIndexOf("/");
    path = document.location.pathname.substr(0, path + 1);
    path += "NodeCenterWS";
    return prefix + host + path;
};
var initWSocket = function () {
    console.log("[nodecenterManagement.js] initWSocket : ");
    var host = document.location.host;
    changeTitle(host);
    global.wscallbacks = {};
    var url = getControlWsUrl(host);
    global.wssocket = createWssocket(url, function () {
        getSession();
    }, WSHandler);
};

var getSession = function () {
    global.wssocket.send("{\"action\":\"getSessionID\"}");
};
var exportSMKeyPair = function () {
    $("#dialog").html("Save Your key:<br/>" + JSON.stringify(global.sm2Key))
    $("#dialog").dialog("open");
};
// ====== wsHandler
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.wssocket.send(JSON.stringify(loginParam));
};

var onLogin = function (data) {
    pubkeyDialogVue.myRole = data.data;
    loadDashBoard();
};

var onListAllUsers = function (data) {
    console.log("onListAllUsers");
    fillUserData(data.data);
};

var onListApplyList = function (data) {
    console.log("onListApplyList");
    global.result = data.data;
    fillApplyUserData(data.data);
};

var onApply = function (data) {
    myToast("申请操作", data.data);
};

var onDelete = function (data) {
    myToast("删除操作", data.data);
    if (data.data == "success") {
        var arg = {};
        arg.action = "listAllUsers";
        global.wssocket.send(JSON.stringify(arg));
    }
};

var onApplyRole = function (data) {
    myToast("申请操作", data.data);
};

var onAuthNodeManager = function (data) {
    myToast("授权/忽略操作", data.data);
    if (data.data == "success") {
        var arg = {};
        arg.action = "listApplyList";
        global.wssocket.send(JSON.stringify(arg));
        var arg = {};
        arg.action = "listAllUsers";
        global.wssocket.send(JSON.stringify(arg));
    }
};

var onQueryUserStat = function (data) {
    console.log("onQueryUserStat");
    mainVue.userCount = data.userListCount + data.applyListCount;
    var div = $("#userTypeDistribution");
    if (div.css("height") == "0px") {
        div = $("#userTypeDistributionDASH");
    }
    if (div.css("height") == "0px") {
        return;
    }
    setUserTypeDistribution(div, data);
};

var onQueryActionLog = function (data) {
    global.lastData = data;
    drawLogTable("auditLogTabDiv", data);
};

var onQueryActionLogSimple = function (data) {
    setUSERMANBar(data);
};

var onUpdateLicence = function (data) {
    console.log("==onUploadLicence");
    if (data.data == "success") {
        listLicence();
    }
    myToast("配置Licence", data.data);
};

var onQueryCMLog = function (data) {
    var tab = $("#v-pills-home-tab")[0];
    var isActive = (tab.getAttribute("aria-selected") == "true");
    if (isActive) {
        drawDashBoardCMLog(data);
    }
    tab = $("#v-pills-messages-tab")[0];
    isActive = (tab.getAttribute("aria-selected") == "true");
    if (isActive) {
        //drawLogBar("auditCMLogBarDiv", data);
        drawLogTable("auditCMLogTabDiv", data);
    }
};

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

var countChar = function (str, c) {
    var ret = 0;
    for (var i = 0; i < str.length; i++) {
        if (str.charAt(i) == c)
            ret++;
    }
    return ret;
}
var generate = function () {
    var key = sm2.generateKeyPairHex();
    global.sm2Key = key;
    localStorage.setItem("PrivKey", JSON.stringify(key));
}

function init() {
    console.log("[nodecenterManagement.js] init : ");
    initVue();
    pubkeyDialogVue.productList = [{
        id: 0,
        title: "NodeManager"
    }];
    pubkeyDialogVue.test = "0";
    initGlobal();
    initWSocket();
}

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

var changeOtherNC = function () {
    console.log("changeOtherNC");

    var str = "";
    if ($("#OtherNCInput")[0].value == undefined || $("#OtherNCInput")[0].value == "") {
        console.log("未配置OtherNC");
    } else {
        str = $("#OtherNCInput")[0].value;
    }

    global.wssocket.send(JSON.stringify({
        action: 'changeOtherNC',
        data: str
    }));
};

var getOtherNC = function () {
    setTimeout(function () {
        console.log("getOtherNC");
        global.wssocket.send(JSON.stringify({
            action: 'getOtherNC'
        }));
    }, 300);
};

var onGetOtherNC = function (obj) {
    console.log(obj);
    $("#OtherNCInput")[0].value = obj.address;
};

var changeNCFile = function () {
    console.log("changeNCFile");
    var str = "";
    if ($("#ncFileInput")[0].value == undefined || $("#ncFileInput")[0].value == "") {
        console.log("未配置NCFile");
    } else {
        str = $("#ncFileInput")[0].value;
    }


    global.wssocket.send(JSON.stringify({
        action: 'changeNCFile',
        data: str
    }));
};

var getNCFile = function () {
    setTimeout(function () {
        console.log("getNCFile");
        global.wssocket.send(JSON.stringify({
            action: 'getNCFile'
        }));
    }, 300);
};

var onGetNCFile = function (obj) {
    console.log(obj);
    $("#ncFileInput")[0].value = obj.fileName;
};