var expandOrCollapse = function () {
    if ($("#outputNav").hasClass("col-2")) {
        $("#outputNav").removeClass("col-2").addClass("col-6");
        $("#mainBox").removeClass("col-8").addClass("col-4");
        $("#expand").html("收起");
    } else {
        $("#outputNav").removeClass("col-6").addClass("col-2");
        $("#mainBox").removeClass("col-4").addClass("col-8");
        $("#expand").html("展开");
    }
};
var listContracts = function () {
    var request = {};
    request.action = "listContractProcess";
    global.wssocket.send(JSON.stringify(request));
};

var startContract = function () {
    var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
    var sm2Key = JSON.parse(key.sm2Key);
    var projectId = $("#selectedProject")[0].value;
    var project = global.projects[projectId];
    startResult.innerText = "正在启动合约:" + project;

    var request = {};
    request.action = "startContract";
    request.isPrivate = $("#privateprojecttab").hasClass("active");

    request.owner = sm2Key.publicKey;
    request.requestID = new Date().getTime() + "";
    // request.contractid = $("#tabdiv")[0].value;
    // request.script = global.scriptEditor.getValue();
    request.path = "/" + project + "/mainfest.json";
    localStorage.setItem("persisStatus", JSON.stringify(request));
    {
        request.signature = sm2.doSignature("Fixed|" + request.path + "|"
            + sm2Key.publicKey, sm2Key.privateKey);
        request.script = "empty";
    }
    global.wssocket.send(JSON.stringify(request));

};

var startContractAsDebug = function () {
    var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
    var sm2Key = JSON.parse(key.sm2Key);
    var projectId = $("#selectedProject")[0].value;
    var project = global.projects[projectId];
    startResult.innerText = "正在以调试模式启动合约:" + project;

    var request = {};
    request.action = "startContractAsDebug";
    request.isPrivate = $("#privateprojecttab").hasClass("active");

    request.owner = sm2Key.publicKey;
    request.requestID = new Date().getTime() + "";
    // request.contractid = $("#tabdiv")[0].value;
    // request.script = global.scriptEditor.getValue();
    request.path = "/" + project + "/mainfest.json";
    localStorage.setItem("persisStatus", JSON.stringify(request));
    {
        request.signature = sm2.doSignature("Fixed|" + request.path + "|"
            + sm2Key.publicKey, sm2Key.privateKey);
        request.script = "empty";
    }
    global.wssocket.send(JSON.stringify(request));

};
var stopContract = function () {
    var request = {};
    request.action = "killContractProcess";
    request.requestID = new Date().getTime() + "";
    request.name = mainVue.contracts[selectedContract.value].name;
    request.id = mainVue.contracts[selectedContract.value].id;
    global.wssocket.send(JSON.stringify(request));
};

var genReadme = function () {

    var request = {};
    request.isPrivate = global.currentFile.isPrivate;
    request.path = global.currentFile.path;
    var tmpIndex = request.path.lastIndexOf('/');
    var yjsName = request.path.substring(tmpIndex + 1, request.path.length - 4);
    request.path = request.path.substring(0, tmpIndex);
    var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
    var sm2Key = JSON.parse(key.sm2Key);

    for (c of mainVue.contracts) {
      //  这里假设合约名同文件名
      if (yjsName == c.name) {
          var exportedFunction = c.exportedFunctions;
          ReadmeFunction = [];
          for (let f of exportedFunction) {
              let description = "暂无描述";
              let readmeFunc = {};
              readmeFunc.functionName = f.functionName;
              readmeFunc.description = description;
              for (let anno of f.annotations) {
                  if (anno.type == 'Param') {
                      readmeFunc.args = anno.args[0];
                  }
                  else if (anno.type == 'Description') {
                      readmeFunc.description = anno.args[0];
                  }
                  else if (anno.type == 'Result') {
                      readmeFunc.result = anno.args[0];
                  }
              }
              ReadmeFunction.push(readmeFunc);
          }
          request.action = "generateReadme";

          request.contractID = c.id;
          request.contractName = c.name;
          request.pubkey = sm2Key.publicKey;
          global.wssocket.send(JSON.stringify(request));
          return;
      }
    }
    myToast("生成文档失败", "请启动合约并检查合约与文件名是否一致！");
};

var genData = function () {
    var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
    var sm2Key = JSON.parse(key.sm2Key);
    var value = selectedContract.value;
    if (value != undefined && value != "选择合约实例") {
        var request = {};
        request.action = "generateDataFromRM";
        request.requestID = new Date().getTime() + "_"
            + Math.floor(Math.random() * 10000);
        var contract = mainVue.contracts[selectedContract.value];
        request.isPrivate = $("#privateprojecttab").hasClass("active");
        request.contractID = contract.id;
        request.contractName = mainVue.contracts[selectedContract.value].name;
        var arg = {};
        if ($('#gasLimit').val() == undefined || $('#gasLimit').val() == "") {
            arg.gasLimit = '1000';
        } else {
            arg.gasLimit =$('#gasLimit').val();
        }
        // console.log("[arg.gasLimit]"+arg.gasLimit);
        request.pubkey = sm2Key.publicKey;
        request.signature = sm2.doSignature(request.contractID + "|" + arg.action
            + "|" + arg.arg + "|" + sm2Key.publicKey, sm2Key.privateKey);
        request.arg = JSON.stringify(arg);
        localStorage.setItem("persisArg", JSON.stringify(request));
        global.wssocket.send(JSON.stringify(request));
    }
};


var queryContractInstanceDOI = function () {
    var request = {};
    request.action = "queryContractInstanceDOI";
    request.requestID = new Date().getTime() + "";
    request.name = mainVue.contracts[selectedContract.value].name;
    request.id = mainVue.contracts[selectedContract.value].id;
    global.wssocket.send(JSON.stringify(request));
};

var queryContractInstanceInfoByDOI = function () {
    var request = {};
    request.action = "queryContractInstanceInfoByDOI";
    request.requestID = new Date().getTime() + "";
    request.doi = contractInstanceDOIInput.value;
    global.wssocket.send(JSON.stringify(request));
};

var importContractInstanceCodeByDOI = function () {
    var request = {};
    request.action = "importContractInstanceCodeByDOI";
    request.requestID = new Date().getTime() + "";
    request.doi = contractInstanceDOIInput.value;
    global.wssocket.send(JSON.stringify(request));
};

var openinClient = function () {
    var path  = document.location.pathname;
    path = path.replace("/SCIDE","");
    path = path.replace("/OnlineIDE.html","");
    var url = path + "/client/bdwareclient.html?self=true&contract="
        + mainVue.contracts[selectedContract.value].id;
    window.open(url);
};

var stopAllContract = function () {
    var request = {};
    request.action = "killAllContract";
    global.wssocket.send(JSON.stringify(request));
};
var selectContractToExecute = function () {
    var value = selectedContractAtExecute.value;
    if (value != undefined && value != "选择实例") {
        var exportedFunction = mainVue.contracts[value].exportedFunctions;
        mainVue.contractFunctions = exportedFunction;

        var pingObj = {};
        pingObj.action = "connectTo";
        pingObj.name = mainVue.contracts[value].name;
        pingObj.id = mainVue.contracts[value].id;
        global.wssocket.send(JSON.stringify(pingObj));

    }
};

var executeContract = function () {
    if (selectedFunction.value == undefined) {
        myToast("调用合约失败", "请选择合约方法");
        return;
    }
    if (selectedContractAtExecute.value == undefined) {
        myToast("调用合约失败", "请选择合约");
        return;
    }
    var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
    var sm2Key = JSON.parse(key.sm2Key);

    var request = {};



    request.action = "executeContract";
    request.requestID = new Date().getTime() + "_"
        + Math.floor(Math.random() * 10000);
    var contract = mainVue.contracts[selectedContractAtExecute.value];

    request.contractID = contract.id;
    var arg = {};
    arg.action = contract.exportedFunctions[selectedFunction.value].functionName;
    arg.arg = executeContractArgInput.value;
    if ($('#gasLimit').val() == undefined || $('#gasLimit').val() == "") {
        arg.gasLimit = '1000';
    } else {
        arg.gasLimit =$('#gasLimit').val();
    }
    // console.log("[arg.gasLimit]"+arg.gasLimit);
    request.pubkey = sm2Key.publicKey;
    request.signature = sm2.doSignature(request.contractID + "|" + arg.action
        + "|" + arg.arg + "|" + sm2Key.publicKey, sm2Key.privateKey,{hash:true,der:true});
    request.arg = JSON.stringify(arg);

    localStorage.setItem("persisArg", JSON.stringify(request));
    global.wssocket.send(JSON.stringify(request));
};
var executeContractWithDynamicResult = function () {
    if (selectedFunction.value == undefined) {
        myToast("调用合约失败", "请选择合约方法");
        return;
    }
    if (selectedContractAtExecute.value == undefined) {
        myToast("调用合约失败", "请选择合约");
        return;
    }
    console.log("executeContractWithDynamicResult");
    var request = {};
    request.action = "executeContract";
    request.requestID = new Date().getTime() + "";

    var contract = mainVue.contracts[selectedContractAtExecute.value];
    request.contractName = contract.id;

    var arg = {};
    arg.action = contract.exportedFunctions[selectedFunction.value].functionName;
    arg.arg = executeContractArgInput.value;

    request.withDyanmicAnalysis = true;
    request.arg = "{\"action\":\"" + arg.action + "\",\"arg\":\"" + arg.arg
        + "\"}";
    request.pubkey = global.sm2Key.publicKey;
    request.signature = sm2.doSignature(request.contractID + "|" + arg.action
        + "|" + arg.arg + "|" + global.sm2Key.publicKey,
        global.sm2Key.privateKey,{hash:true,der:true});
    localStorage.setItem("persisArg", JSON.stringify(request));
    global.wssocket.send(JSON.stringify(request));
};
var testEvaluates = function () {
    if (selectedFunction.value == undefined) {
        myToast("调用合约失败", "请选择合约方法");
        return;
    }
    if (selectedContractAtExecute.value == undefined) {
        myToast("调用合约失败", "请选择合约");
        return;
    }
    console.log("Evaluates");
    var contract = mainVue.contracts[selectedContractAtExecute.value];

    var request = {};
    request.action = "evaluates";
    request.contractName = contract.id;
    request.functionName = contract.exportedFunctions[selectedFunction.value].functionName;
    request.args = executeContractArgInput.value;

    global.wssocket.send(JSON.stringify(request));
};

