var loadContractList = function (e) {
    var param = {};
    param.action = "listNodes";
    param.pubKey = global.sm2Key.publicKey;
    global.wssocket.send(JSON.stringify(param));
    if (!global.nodeInfo) {
        setTimeout(loadContractList, 300);
        return;
    }
    setTimeout(function () {
        var list = [];
        for (var i = 0; i < global.nodeInfo.online.length; i++) {
            var node = global.nodeInfo.online[i];
            if (node.contracts)
                for (var j = 0; j < node.contracts.length; j++) {
                    list.push(node.contracts[j]);
                }
        }
        drawContractListStatusPie(list);
        drawContractListTable(global.nodeInfo.online);
    }, 200);
};

var toSimple = function (name) {
    switch (name) {
        case 'Sharding':
            return "Sharding";
        case 'RequestAllResponseAll':
            return "RARA";
        case 'RequestAllResponseHalf':
            return "RARH";
        case 'RequestAllResponseFirst':
            return "RARF";
        case 'RequestOnce':
        case 'Responseonce':
        case "Sole":
        default:
            return name;
    }
}
var drawContractListStatusPie = function (obj) {
    var id = "contractStatusPieDiv";
    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 = {};
    for (var i = 0; i < obj.length; i++) {
        if (result[obj[i].type] == undefined)
            result[obj[i].type] = 0;
        result[obj[i].type]++;
    }
    var dataList = [];
    var valDataList = [];
    for (var key in result) {
        dataList.push(toSimple(key));
        var l = {};
        l.name = toSimple(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 jumpToContractClient = function (nodeAddr, contractID) {
    console.log("[jumpToContractClient] " + nodeAddr + " " + contractID);
    var ip = nodeAddr.split(":")[0];
    var port = nodeAddr.split(":")[1] - 1;
    var url = "./client/bdwareclient.html?";
    url += "nodeAddr=" + ip + ":" + port;
    url += "&contract=" + contractID;
    window.open(url);
}
var drawContractListTable = function (list) {
    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": ": 以降序排列此列"
        }
    };
    const tableHead = "<table id='contractListTabDivTab' 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;
    var count = 0;
    for (var i = 0; i < list.length; i++) {
        var node = list[i];
        if (node.contracts)
            for (var j = 0; j < node.contracts.length; j++) {
                var c = node.contracts[j];
                if (c.type && c.type.startsWith("RequestAll") && !c.isMaster)
                    continue;
                html += "<tr><td>";
                html += (++count);
                html += "</td><td>";
                html += c.contractID;
                html += "</td><td>";
                html += `<a onclick='jumpToContractClient("${node.masterAddress}","${c.contractID}")' style='cursor: pointer'>`
                html += c.contractName + (c.type && c.type.startsWith("SelfAdaptive") && c.isMaster ? "(M)" : "");
                html += "</a>"
                html += "</td><td>";
                html += c.type;
                html += "</td><td>";
                html += c.yjsType
                // if (c.events!=undefined)
                // html+=c.events.length
                // else html+=0;
                html += "</td><td>";
                if (c.exportedFunctions) {
                    html += c.exportedFunctions.length;
                } else {
                    html += "-1";
                }
                html += "</td></tr>";
            }
    }

    html += tableTail;
    $("#contractListTabDiv").html(html);
    $("#contractListTabDivTab").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) {
                        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 > 10)
                            return "<span title='" + data + "'>"
                                + data.substring(0, 10)
                                + "  ...</span>";
                        else
                            return data;
                    }

                }
            ]

        });


}