var loadNodesListMan = function (event) {
    console.log("loadNodesListMan");
    listNodes();
    listTrustUnits();
    listMultiCP();
};

var listMultiCP = function () {
    setTimeout(function () {
        var listMPContractProcess = {};
        listMPContractProcess.action = "listMultiPointContractProcess";
        global.wssocket.send(JSON.stringify(listMPContractProcess));
    });
};

var listNodes = function (event) {
    console.log("listNodes");
    setTimeout(function () {
        var param = {};
        param.action = "listNodes";
        param.pubKey = global.sm2Key.publicKey;
        global.wssocket.send(JSON.stringify(param));
    }, 300);
};

var listTrustUnits = function (event) {
    console.log("listTrustUnits");
    setTimeout(function () {
        var param = {};
        param.action = "listTrustUnits";
        param.pubKey = global.sm2Key.publicKey;
        global.wssocket.send(JSON.stringify(param));
    }, 300);
};

function queryNodeByName(name) {
    for (let i = 0; i < global.nodeInfo.online.length; i++) {
        const node = global.nodeInfo.online[i];
        if (node.nodeName === name)
            return node;
    }
    return undefined;
}

var submitTrustUnitNodes = function (event) {
    const options = document.querySelector('#selectTrustUnitNodes').options;
    var list = [];
    for (let i = 0; i < options.length; i++) {
        // 如果该option被选中，则将它的value存入数组
        if (options[i].selected) {
            const node = queryNodeByName(options[i].text);
            if (!node) {
                console.log("Error, can't find node:" + option.text);
                continue;
            }
            // item.masterAddress = node.masterAddress;
            // item.peerID = node.peerID;
            // item.udpID = node.udpID;
            // item.ipPort = node.ipPort;
            list.push({
                nodeName: node.nodeName,
                // masterAddress: node.masterAddress,
                // peerID: node.peerID,
                // udpID: node.udpID,
                // ipPort: node.ipPort,
                pubKey: node.pubKey
            });
        }
    }
    const param = {
        action: 'createTrustUnit',
    };
    param.action = "createTrustUnit";
    param.data = list;
    const name = $("#newUnitName")[0].value;
    if (!name) {
        myToast("失败", "请输入集群名称");
    }
    param.msg = name;
    global.wssocket.send(JSON.stringify(param));

};

var onCreateTrustUnit = function (event) {
    myToast("Success", "创建可信集群成功")
    listTrustUnits();
};

// if ($("#nodesStatusPieDiv").css("height") == "0px") {
var drawNodesStatusPie = function (id, obj) {
    // if ($("#nodesStatusPieDiv").css("height") == "0px") {
    if ($("#" + id).css("height") == "0px") {
        console.log("drawNodesStatusPie: ignore");
        return;
    }
    $("#" + id)
        .html(
            "<div class='col-12' id='"
            + id
            + "Canv' style='width:100%; min-height: 150px; padding: 0px'></div>");
    var result = {};
    if (obj.offline.length > obj.online.length) {
        result["Offline"] = obj.offline.length - obj.online.length;
        result["Online"] = obj.online.length;
    } else {
        result["Offline"] = 0;
        result["Online"] = obj.online.length;
    }
    global.result = result;
    var dataList = [];
    var valDataList = [];
    for (var key in result) {
        dataList.push(key);
        var l = {};
        l.name = key
        l.value = result[key];
        valDataList.push(l);
    }

    var myChart = echarts.init($("#" + id + "Canv")[0], 'walden');
    var option222 = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 10,
            data: dataList
        },
        series: [{
            name: '节点数目',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
                normal: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    show: true,
                    textStyle: {
                        fontSize: '15',
                        fontWeight: 'bold'
                    }
                }
            },
            labelLine: {
                normal: {
                    show: false
                }
            },
            data: valDataList
        }]
    };
    myChart.setOption(option222);
};

var onListNodes = function (obj) {
    // mainVue
    console.log("onListNodes");
    console.log(obj);
    global.nodeInfo = obj;
    var len = 0;
    if (obj.offline) {
        len += obj.offline.length;
    }
    if (obj.online) {
        len += obj.online.length;
    }
    mainVue.nodeCount = len;
    var count = 0;
    let i;
    if (obj.online) {
        for (i = 0; i < obj.online.length; i++) {
            count += obj.online[i].contracts.length;
        }
    }
    mainVue.contractCount = count;
    // nodesStatusPieDiv
    // dashNodesStatusPieDiv
    drawNodesStatusPie("nodesStatusPieDiv", obj);
    drawNodesStatusPie("dashNodesStatusPieDiv", obj);

    if ($("#nodesTabDiv").css("height") === "0px") {
        console.log("nodesTabDiv: ignore");
        return;
    }
    var 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='nodesTabDivTab'>" +
        "<thead>" +
        "<tr><th>序号</th>" +
        "<th>Name</th>" +
        "<th>状态</th>" +
        "<th>合约数目</th>" +
        "<th>事件数目</th>" +
        // "<th>PeerID</th>" +
        // "<th>UDPID</th>" +
        "<th>TCP地址</th>" +
        "<th>公钥</th></tr>" +
        "</thead>" +
        "<tbody>";
    var tableTail = "</tbody></table>";
    var contractCount = 0;
    var eventCount = 0;
    $("#selectTrustUnitNodes").html("");
    var x = document.getElementById("selectTrustUnitNodes");
    x.options.length = 0;
    for (i = 0; i < obj.online.length; i++) {
        let node = obj.online[i];
        let nodeEventCount = node.events | '-';
        let nameHtml = ''
        if (node.masterAddress) {
            const ipPort = node.masterAddress.split(":")
            nameHtml =
                `<a href="http://${ipPort[0]}:${Number(ipPort[1]) - 1}/NodePortal.html" target="_blank">` +
                `${node.nodeName}</a>`
        } else {
            nameHtml = node.nodeName;
        }
        html += `<tr><td>${i + 1}</td>
            <td>${nameHtml}</td>
            <td>Online</td>
            <td>${node.contracts ? node.contracts.length : 0}</td>
            <td>${nodeEventCount}</td>
<!--            <td>${node.peerID}</td>-->
<!--            <td>${node.udpID ? node.udpID : ''}</td>-->
            <td>${node.masterAddress}</td>
            <td>${node.pubKey}</td>
            </tr>`
        if (node.contracts && node.contracts.length) {
            contractCount += node.contracts.length;
        }
        eventCount += nodeEventCount;

        var option = document.createElement("option");
        option.text = node.nodeName;
        option.value = node.peerID;
        x.add(option);// new
        // Option(obj.online[i].pubKey,obj.online[i].pubKey),0);
        // option += '<option value="' + obj.online[i].pubKey + '">' +
        // obj.online[i].pubKey.substring(0,15) + '</option>';

    }

    console.log("offline: ", obj.offline.length);
    for (var j = 0; j < obj.offline.length; j++) {
        html += `<tr>
            <td>${i + j + 1}</td>
            <td>${obj.offline[j]}</td>
            <td>Offline</td>
            <td>-</td>
            <td>-</td>
<!--            <td>-</td>-->
<!--            <td>-</td>-->
            <td>-</td>
            <td>${obj.offline[j]}</td>
            </tr>`
    }
    $("#selectTrustUnitNodes").selectpicker('refresh');
    mainVue.contractCount = contractCount;
    mainVue.eventCount = eventCount;
    html += tableTail;
    $("#nodesTabDiv").html(html);

    function abbrRender(data, type, row, meta) {
        if (data.length > 8)
            return "<span title='" + data + "'>"
                + data.substring(0, 8)
                + "  ...</span>";
        else
            return data;
    }

    $("#nodesTabDivTab").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": 1,
                    "render": function (data, type, row, meta) {
                        const firstBg = data.indexOf(">");
                        const secondSl = data.substring(1).indexOf("<");
                        const aTag = firstBg === -1 ? "" : data.substring(0, firstBg + 1);
                        const aTagTail = secondSl === -1 ? "" : data.substring(secondSl + 1);
                        const name = firstBg === -1 || secondSl === -1 ?
                            data :
                            data.substring(firstBg + 1, secondSl + 1);
                        const html = name.length > 15 ?
                            `<span title='${name}'>${name.substring(0, 15)}  ...</span>` :
                            name;
                        return aTag + html + aTagTail;
                    }

                },
                // { // for PeerID
                //     "targets": 5,
                //     "render": abbrRender
                // },
                {
                    "targets": 6,
                    "render": abbrRender
                }]

        });
};

var onListTrustUnits = function (obj) {
    // mainVue
    mainVue.unitCount = obj.data.length;
    if ($("#trustNodesUnitTabDiv").css("height") == "0px") {
        console.log("trustNodesUnitTabDiv: ignore");
        return;
    }
    var 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": ": 以降序排列此列"
        }
    };
    var tableHead = `<table id='trustNodesUnitTabDivTab' class='table display row-border'><thead><tr>
        <th>序号</th>
        <th>ID</th>
        <th>创建者</th>
        <th>节点数目</th>
        <th>节点列表</th>
        <th></th></tr></thead><tbody>`;
    var tableTail = "</tbody></table>";
    var html = tableHead;
    for (var i = 0; i < obj.data.length; i++) {
        var at_ = obj.data[i].key.indexOf("_");
        var nodes = JSON.parse(obj.data[i].value);
        html += `<tr><td>${i + 1}</td>
            <td>${obj.data[i].key.substring(at_ + 1)}</td>
            <td>${obj.data[i].key.substring(0, at_ - 1)}</td>
            <td>${nodes.length}</td>
            <td>${nodes.map(x => x.nodeName).sort().join(",")}</td>
            <td style="padding: 2px 12px;">
                <button class="btn btn-outline-danger" onclick="deleteTrustUnit('${obj.data[i].key}')">删除</button>
            </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": 2,
                    "render": function (data, type, row, meta) {
                        if (data.length > 15)
                            return "<span title='" + data + "'>"
                                + data.substring(0, 15)
                                + "  ...</span>";
                        else
                            return data;
                    }

                },
                {
                    "targets": 4,
                    "render": function (data, type, row, meta) {
                        let arr = data.split(',')
                        if (arr.length > 2) {
                            arr = [arr[0], arr[1], '...']
                        }
                        for (let i = 0; i < arr.length; ++i) {
                            if (arr[i].length > 20) {
                                arr[i] = arr[i].substring(0, 20) + '  ...';
                            }
                        }
                        return arr.join(',<br>')
                    }

                }]
        });
};

var deleteTrustUnit = function (data) {
    var param = {};
    param.action = "deleteTrustUnit";
    param.data = data;
    global.wssocket.send(JSON.stringify(param));
};

var onDeleteTrustUnit = function (event) {
    myToast("Success", "删除可信集群成功")
    listTrustUnits();
};

var onListMultiPointContractProcess = function (data) {
    var 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": ": 以降序排列此列"
        }
    };
    var tableHead = "<table id='MPContractTabDivTab' class='table display row-border'><thead><tr><th>序号</th><th>合约名称</th><th>合约ID</th><th>管理</th></tr></thead><tbody>";
    var tableTail = "</tbody></table>";
    var html = tableHead;
    var list = JSON.parse(data.data);
    for (var i = 0; i < list.length; i++) {
        var nodes = list[i];
        html += "<tr><td>";
        html += (i + 1);
        html += "</td> <td><a style='cursor:pointer' onclick='openclient(\"" + nodes.contractID + "\")'>";
        html += nodes.contractName;
        html += "</a></td> <td>";
        html += nodes.contractID;
        html += "</td> <td style='padding:2px 12px'>";
        html += "<button class='btn btn-outline-danger' onclick='stopMultiPointCP(\"" + nodes.contractID
            + "\")'>停止</button>";
        html += "</td> </tr>";
    }
    html += tableTail;
    $("#MPContractTabDiv").html(html);
    $("#MPContractTabDivTab").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": 2,
                    "render": function (data, type, row, meta) {
                        if (data.length > 15)
                            return "<span title='" + data + "'>"
                                + data.substring(0, 15)
                                + "  ...</span>";
                        else
                            return data;
                    }

                }]
        });

};

var openclient = function (contractID) {
    var path = document.location.origin;
    var url = path + "/client/bdwareclient.html?self=true&contract="
        + contractID + "&withNodeCenterWS=true";
    window.open(url);
};

var stopMultiPointCP = function (contractID) {
    var arg = {};
    arg.action = "stopMultiPointContractProcess";
    arg.contractID = contractID;
    global.wssocket.send(JSON.stringify(arg));
};