/* ФУНКЦИЯ НА КАСТОМНЫЕ ЗАПРОСЫ */
function api(method, options) {
    var host = 'http://127.0.0.1:8080/Synergy/rest/api/';
    if (!options) options = {};
    if (!options.type) options.type = 'GET';
    var client = new org.apache.commons.httpclient.HttpClient();
    var creds = new org.apache.commons.httpclient.UsernamePasswordCredentials(login, password);
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(org.apache.commons.httpclient.auth.AuthScope.ANY, creds);
    switch (options.type) {
        case 'GET':
            var api = new org.apache.commons.httpclient.methods.GetMethod(host + method);
            api.setRequestHeader('Content-type', 'application/json');
            client.executeMethod(api);
            var result = api.getResponseBodyAsString();
            break;
        case 'POST':
            var api = new org.apache.commons.httpclient.methods.PostMethod(host + method);
            api.setRequestBody(JSON.stringify(options.body));
            api.setRequestHeader("Content-type", "application/json");
            var result = client.executeMethod(api);
            break;
        default:
    }
    api.releaseConnection();
    return options.dataType && options.dataType == 'text' ? '' + result : JSON.parse(result);
}

try {

    let currentFormData = API.getFormData(dataUUID);
    let contract, paymentDate, paymentSum, docID;

/* ДОСТАЕМ ДАННЫЕ ПО dataUUID, ОБРАЩАЕМСЯ К КОНКРЕТНЫМ КОМПОНЕНТАМ И СОХРАНЯЕМ В ПЕРЕМЕННЫЕ */
    for(let i=0; i<currentFormData.data.length; i++){
        switch (currentFormData.data[i].id) {
            case 'reglink_contract':
                docID = currentFormData.data[i].key;
                break;
            case 'date_payment_in_graph':
                paymentDate = currentFormData.data[i];
                break;
            case 'numericinput_sum_payment_in_graph':
                paymentSum = currentFormData.data[i];
        }
    }

/* ДОСТАЕМ DocumentID С ПОМОЩЬЮ DataUUID */
    docUUID = API.getAsfDataId(docID);

/* ДОБАВЛЯЕМ СТРОКУ В ID КОМПОНЕНТА */
    paymentDate.id += "-b1";
    paymentSum.id += "-b1";

/* ЗАДАЕМ ПАРАМЕТРЫ ЗАПРОСА (ВКЛЮЧАЯ КОНТЕНТ) */
    var params = {
        "type": 'POST',
        "body": {
            "uuid": docUUID,
            "tableId": "table_payment",
            "data": [ paymentDate, paymentSum ]
        }
    };

/* ДЕЛАЕМ ЗАПРОС С НАШИМИ  ПАРАМЕТРАМИ*/
    var appendTable = api("asforms/data/append_table", params);
    var result = true;

} catch (err) {
    if (typeof (err) == "object") {
        console.error(JSON.stringify(err));
        var message = JSON.stringify(err);
    } else {
        console.error(err.toString());
        var message = err.toString();
    }
    var result = false;
}