// функция расширенного поиска по записям реестра с SQL-запросом  
    function searchUsersWithCourse(str){

        let body = {
//            query: " WHERE (kw_form_userCard_competenceName.TEXT = '1eace0ab-dcb6-4ff8-ab51-3f79a7eae7fc' OR kw_form_userCard_competenceName_other.TEXT = '1eace0ab-dcb6-4ff8-ab51-3f79a7eae7fc') AND code = 'kw_form_userCard'",
            query: " WHERE (kw_form_userCard_competenceName.DATE LIKE '%" + str + "%') OR (kw_form_userCard_competenceName_other.DATE LIKE '%" + str + "%') AND code = 'kw_form_userCard'",
            parameters: [],
            dynParams: [["kw_form_userCard_competenceName.DATE", "kw_form_userCard_competenceName_other.DATE"]],
            startRecord: 0,
            recordsCount: 1000, //ограничение на кол-во найденных записей
            showDeleted: false,
//            registryRecordStatus: ["STATE_SUCCESSFUL", "NO_ROUTE", "STATE_UNSUCCESSFUL", "STATE_NOT_FINISHED"],
            registryRecordStatus: ["STATE_SUCCESSFUL"],
            searchInRegistry: true
        };

        let client = API.getHttpClient();
        let post = new org.apache.commons.httpclient.methods.PostMethod("http://127.0.0.1:8080/Synergy/rest/api/asforms/search/advanced");
        post.setRequestHeader("Content-type", "application/json; charset=utf-8");
        post.setRequestBody(JSON.stringify(body));
        client.executeMethod(post);
        let resp = post.getResponseBodyAsString();
        post.releaseConnection();
        return JSON.parse(resp);
    }


var result = true;
var message = "OK";


try {
    let currentFormData = API.getFormData(dataUUID);

//  курс, который ищем в карточках пользователей
    let searchingCourse = UTILS.getValue(currentFormData, 'kw_form_protocol_course');
//    log.info ('Ищем курс по key ', searchingCourse.key);
//    log.info ('=====================');

//  подразделение, которое ищем в карточках пользователей
    let searchingDepartment = UTILS.getValue(currentFormData, 'kw_form_protocol_course_department');


// формируем дин.таблицу для найденных пользователей с нуля
    let asfData = [];
    let table = {
        "id": "kw_form_protocol_table2",
        "type": "appendable_table",
        "data": []
    }
    let ind = 0; //индекс для полей строк таблицы

//  поиск 
    let searchResult = searchUsersWithCourse(searchingCourse.key);
    if(searchResult.length > 0) {
//        log.info ('==========Результат поиска ========== ', searchResult);
//        log.info ('=====================');
//        log.info ('searchResult.length = ', searchResult.length);

//      пройтись по всем результатам (коих searchResult.length) и взять данные
        for (let i = 0; i < searchResult.length;i++){
            let userCardUUID = searchResult[i].dataUUID;
//            log.info ('=====================');
//            log.info ('uuid user card = ', userCardUUID);
            let userCardFormData = API.getFormData(userCardUUID);

            let userFromCard = UTILS.getValue(userCardFormData, 'kw_form_userCard_user');
//            log.info ('=========USER============', userFromCard);
            let departmentFromCard = UTILS.getValue(userCardFormData, 'kw_form_userCard_department');

            let competenceTable = UTILS.getValue(userCardFormData, 'kw_form_userCard_competenceTable');
//            log.info ('=========ОСНОВНАЯ_ТАБЛИЦА============', competenceTable);

// это пока для основной таблицы, нужно ещё для дополнительной
            if(competenceTable.hasOwnProperty('data') && departmentFromCard.key == searchingDepartment.key){
            for (let j = 1; j < UTILS.getTableBlockIndex(competenceTable, 'kw_form_userCard_competenceName'); j++){
                let user_course = UTILS.getValue(competenceTable, 'kw_form_userCard_competenceName-b' + j);
                if(user_course && user_course.hasOwnProperty('value') && user_course.key == searchingCourse.key) {
                    ind++;
//                    log.info ('=====================');
//                    log.info ('=== index ===', ind);
                    let users_status = UTILS.getValue(competenceTable, 'kw_form_userCard_status-b' + j);
//                    log.info ('=====================');
//                    log.info ('=== users course status = ', user_course, 'status =', users_status);
                
                    table.data.push({
                        "id": "fio-b"+ind,
                        "type": "entity",
                        "value": userFromCard.value,
                        "key": userFromCard.key,
                    });

                    table.data.push({
                        "id": "number-b"+ind,
                        "type": "numericinput",
                        "value": ind,
                        "key": ind,
                    });

                    if(users_status.key == 2 || users_status.key == 3){
                        table.data.push({
                            "id": "mark-b"+ind,
                            "type": "listbox",
                            "value": "Сдал",
                            "key": 1
                        });
                    } else {
                        table.data.push({
                            "id": "mark-b"+ind,
                            "type": "listbox",
                            "value": "Не сдал",
                            "key": 0
                        });
                    }

                }
            }// цикл по j
            }// проверка на существование data в таблице competenceTable

            let competenceTable_other = UTILS.getValue(userCardFormData, 'kw_form_userCard_competenceTable_other');
//            log.info ('=========ДОПОЛНИТЕЛЬНАЯ_ТАБЛИЦА============', competenceTable_other);
// для доп.таблицы
            if(competenceTable_other.hasOwnProperty('data') && departmentFromCard.key == searchingDepartment.key){
            for (let k = 1; k < UTILS.getTableBlockIndex(competenceTable_other, 'kw_form_userCard_competenceName_other'); k++){
                let user_course = UTILS.getValue(competenceTable_other, 'kw_form_userCard_competenceName_other-b' + k);
                if(user_course && user_course.hasOwnProperty('value') && user_course.key == searchingCourse.key) {
                    ind++;
//                    log.info ('=====================');
//                    log.info ('=== index ===', ind);
                    let users_status = UTILS.getValue(competenceTable_other, 'kw_form_userCard_status_other-b' + k);
//                    log.info ('=====================');
//                    log.info ('=== users course status = ', user_course, 'status =', users_status);
                
                    table.data.push({
                        "id": "fio-b"+ind,
                        "type": "entity",
                        "value": userFromCard.value,
                        "key": userFromCard.key,
                    });

                    table.data.push({
                        "id": "number-b"+ind,
                        "type": "numericinput",
                        "value": ind,
                        "key": ind,
                    });

                    if(users_status.key == 2 || users_status.key == 3){
                        table.data.push({
                            "id": "mark-b"+ind,
                            "type": "listbox",
                            "value": "Сдал",
                            "key": 1
                        });
                    } else {
                        table.data.push({
                            "id": "mark-b"+ind,
                            "type": "listbox",
                            "value": "Не сдал",
                            "key": 0
                        });
                    }

                }
            }// цикл по k
            }// проверка на существование data в таблице competenceTable_other


        }
        
        asfData.push(table);
    } else
        log.info ('====НИЧЕГО====НЕ====НАЙДЕНО====');


   let saveResult = API.mergeFormData({uuid: dataUUID, data: asfData});
        if(saveResult && saveResult.errorCode == '0') {
            message = 'Данные записаны';
        } else {
        message = 'Произошла ошибка сохранения'; 
    }

} catch (err) {
  log.error(err.message);
  message = err.message;
}
