var expandedEvalPanels = {};

$(document).ready(function () {
    collapseInFirstEval();
    hoverDesc();
});

function initializeSidebarEmployeesWithGrades(activeWorker) {
    $dataTable = $('#side-employee-table');

    $dataTable.DataTable({
        buttons: [],
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.FilterDateFrom = $("#Filter_DateFrom").val();
                d.FilterDateTo = $("#Filter_DateTo").val();
            }
        },
        columns: [
            {
                data: function (data) {
                    var rowDiv = `<div onclick="clearCollapsedPanelState(); getEvaluation('${encodeURIComponent(data.Worker)}', ${true}); setSelectedWorker(this)" class="row dt-worker-row" data-worker="${data.Worker}">`;
                    var subtext = "";
                    let name = "";
                    let surname = "";
                    let grade = "";
                    let gradeStatus = "";
                    let gradeStyle = "";
                    let employeeJob = "";

                    if (data.Department && data.Job) {
                        subtext = data.Job + " • " + data.Department;
                        employeeJob = data.Job;
                    } else if (data.Job) {
                        subtext = data.Job;
                        employeeJob = data.Job;
                    } else if (data.Department) {
                        subtext = data.Department;
                    }

                    if (data.Leaders.length > 0) {
                        let leaders = data.Leaders.filter(leader => leader);

                        if ((data.Department || data.Job) && leaders.length > 0) {
                            subtext += " • " + $("#Leader").val() + " " + leaders;
                        }
                    }

                    if (data.Name) {
                        name = data.Name;
                    }

                    if (data.Surname) {
                        surname = data.Surname;
                    }

                    if (data.Grade) {
                        grade = data.Grade.toFixed(2);
                    }

                    if (data.GradeStatus) {
                        if (data.GradeStatus == $("#Finished").val()) {
                            gradeStatus = $("#GradeFinished").val();
                            gradeStyle = "eval-finished";
                        } else if (data.GradeStatus == $("#InProgress").val()) {
                            gradeStatus = $("#GradeInProgress").val();
                            gradeStyle = "eval-in-progress";
                        }
                    }

                    let gradeSection = (grade !== "" && grade !== null) ? '<span class="pull-right worker-grade ' + gradeStyle + '">' + gradeStatus + ' (' + grade + ')</span>' : "";
                    let fullName = '<span class="worker-fullname selectedEmployeeName">' + surname + " " + name + '</span>';

                    var showData = "<div class='col-md-10 col-sm-11 col-xs-10 emp-data'>" + fullName + gradeSection + "<br/><span class='text-muted selectedEmployeeSubtext'>" + subtext + "</span></div> <div class='hidden employeeJob'>" + employeeJob + "</div>";

                    if (data.ProfilePhoto) {
                        return rowDiv + "<div class='col-md-2 col-sm-1 col-xs-2 emp-avatar'><img class='dt-image-circle selectedEmployeeAvatar' src='" + data.ProfilePhoto + "' /></div>" + showData + "</div > ";
                    }
                    else {
                        return rowDiv + "<div class='col-md-2 col-sm-1 col-xs-2 emp-avatar'><div class='dt-text-avatar selectedEmployeeAvatar'>" + data.Avatar + "</div></div>" + showData + "</div>";
                    }
                },
                orderable: false,
                className: 'dt-employee-side-col',
                render: function (data) {
                    return data;
                }
            }
        ],
        "createdRow": function (row, data, dataIndex) {
            if (data.Worker === activeWorker) {
                $(row).children().addClass('side-menu-item-active');
            }
        }
    });


    var typingTimer;
    var doneTypingInterval = 600;
    $('#Keywords').off('keyup');
    $('#Keywords').on('keyup', function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () { $.fn.dataTable.reload($dataTable); }, doneTypingInterval);
    });
}

function setSelectedWorker(worker) {
    employeeName = $(worker).find('.selectedEmployeeName').text();
    employeeSubtext = $(worker).find('.employeeJob').text();

    $('#employeeName').text(employeeName);
    $('#employeeSubtext').text(employeeSubtext);
    $('#employeeSubtext').attr('title', employeeSubtext);

    if ($(worker).find('.selectedEmployeeAvatar').hasClass('dt-text-avatar')) {
        $('#employeeAvatarText').text($(worker).find('.selectedEmployeeAvatar').text());
        $('#employeeAvatarText').removeClass('hidden');
        $('#employeeAvatarImg').addClass('hidden');
    }
    else if ($(worker).find('.selectedEmployeeAvatar').hasClass('dt-image-circle')) {
        $('#employeeAvatarImg').attr('src', $(worker).find('.selectedEmployeeAvatar').attr('src'));
        $('#employeeAvatarImg').removeClass('hidden');
        $('#employeeAvatarText').addClass('hidden');
    }

}

$(".custom-monthpicker").on("hide.bs.dropdown", function () {
    var worker = $("#CurrentWorker").val();
    var dateFrom = $("#Filter_DateFrom").val();
    var dateTo = $("#Filter_DateTo").val();

    if ((dateFrom && dateTo) || (!dateFrom && !dateTo)) {
        getEvaluation(worker, false);
    }
});

function getEvaluation(worker, focusWorker) {
    var evalUrl = $("#EvaluationsUrl").val();
    var dateFrom = $("#Filter_DateFrom").val();
    var dateTo = $("#Filter_DateTo").val();

    if (focusWorker) {
        var tdParent = event.target.parentElement.closest('td');
    }

    return $.ajax({
        url: evalUrl,
        data: {
            worker: worker,
            dateFrom: dateFrom,
            dateTo: dateTo
        }, success: function (data) {
            $("#evaluations").html(data);
            select2();
            select2withAPI();
            collapseInFirstEval();

            if (focusWorker) {
                setActiveSidebarRow(tdParent);
            }

            if (dateFrom && dateTo) {
                setGradeForFilterValue($("#0-Grade").text().trim(), $("#select2-0-Status-container").text().trim());
            }
        },
        error: function () {

        }
    });
}

function reloadEvaluations() {
    var $evaluationsContent = $('#evaluations-content');
    var scrollY = $evaluationsContent.scrollTop();
    getEvaluation($("#CurrentWorker").val(), false).then(function () {
        paw.utils.iterable.iterate(expandedEvalPanels, function (elt, id) {
            collapseEvaluationAccordion(id, elt);
            $evaluationsContent.scrollTop(scrollY);
        });
    });
}

function setGradeForFilterValue(grade, status) {
    $(".side-menu-item-active .worker-grade").text(status + " (" + grade + ")");
}

var idIndex1 = '';
var idIndex2 = '';
function openNoteModal(headerId, evalId, showSaveBtn, content = "") {
    idIndex1 = headerId;
    idIndex2 = evalId;
    $("#" + headerId + "-" + evalId + "-DescApp").val();

    if (showSaveBtn) {
        $(".modal-footer").show();
        $("#item-note").attr("readonly", false);
        $("#item-note").val($("#" + headerId + "-" + evalId + "-DescApp").val());
    } else {
        $(".modal-footer").hide();
        $("#item-note").attr("readonly", true);
        $("#item-note").val(content);
    }

    $('#note-modal').modal('show');
}

function saveNote() {
    var noteValue = $("#item-note").val();
    $("#" + idIndex1 + "-" + idIndex2 + "-DescApp").val(noteValue);

    if (noteValue != "" && noteValue != null) {
        $(".desc-icon-" + idIndex1 + "-" + idIndex2).removeClass("transparent-color");
        $(".desc-icon-" + idIndex1 + "-" + idIndex2).addClass("theme-color");
    }
    else {
        $(".desc-icon-" + idIndex1 + "-" + idIndex2).removeClass("theme-color");
        $(".desc-icon-" + idIndex1 + "-" + idIndex2).addClass("transparent-color");
    }

    $("#" + idIndex1 + "-" + idIndex2 + "-Updated").val(true);
    $("#eval-form-" + idIndex1).submit();
    $("#" + idIndex1 + "-" + idIndex2 + "-Updated").val(false);
}

function hoverDesc() {
    $('.description').hover(
        function () {
            $(this).find('.description-hidden-icon').addClass('default-icon-color');
        },
        function () {
            $(this).find('.description-hidden-icon').removeClass('default-icon-color');
        }
    );
}

function collapseInFirstEval() {
    $("#collapse-0").addClass("in");
    $("#heading-0 a").removeClass("collapsed");
}

function setActiveSidebarRow(tdParent) {
    $(".side-menu-item-active").removeClass("side-menu-item-active");
    $(tdParent).addClass("side-menu-item-active");
    hoverDesc();
}

function saveEvaluationData(anQId, field, value) {
    $.ajax({
        url: "",
        method: "POST",
        data: {
            anQid: anQId,
            field: field,
            value: value
        },
        success: function () {

        },
        error: function () {

        }
    });
}

function isDropdownOpen() {
    // Checks if any dropdown related to the select element is open
    return $('.select2-container--open').length > 0;
}

function handleEvalChange(value, ponder, prsnEvalIndex, evalIndex) {
    if (value == null && isDropdownOpen()) {
        return;
    }

    calculateEvalPoints(value, ponder, prsnEvalIndex, evalIndex);
    submitEvalForm(prsnEvalIndex, evalIndex);
}

function submitEvalForm(headerId, evalId, updateHeader = false) {
    if (!paw.utils.value.strToBool($('#CanGenerallyUpdate').val())) {
        return;
    }

    if (updateHeader) {
        $("#" + headerId + "-Updated").val(true);
    } else {
        $("#" + headerId + "-" + evalId + "-Updated").val(true);
    }

    const mainCheckboxValue = $("#evaluation-checkbox").prop('checked');
    $("#evaluation-checkbox-" + headerId).prop('checked', mainCheckboxValue);
    $("#evaluation-checkbox-" + headerId).val(mainCheckboxValue);

    $("#eval-form-" + headerId).submit();
    $("#" + headerId + "-Updated").val(false);
    $("#" + headerId + "-" + evalId + "-Updated").val(false);
}

function reloadWorkersTable() {
    $dataTable = $('#side-employee-table');
    $.fn.dataTable.reload($dataTable);

    $('#side-employee-table').on('draw.dt', function () {
        focusWorkerAfterReload();
    });
}

function focusWorkerAfterReload() {
    var worker = $("#CurrentWorker").val();
    $(".side-menu-item-active").removeClass("side-menu-item-active");
    $("[data-worker='" + worker + "']").closest("td").addClass("side-menu-item-active");
}

function calculateEvalPoints(eval, ponder, prsnEvalIndex, evalIndex) {
    let points = parseInt(eval) * parseFloat(ponder);
    $("#" + prsnEvalIndex + "-" + evalIndex + "-Points").val(points);
}

function collapseEvaluationAccordion(id, element) {
    if ($(id).hasClass('in')) {
        $(id).removeClass('in');
        $(id).addClass('collapsed');
        $(element).addClass('collapsed');
        delete expandedEvalPanels[id];
    }
    else {
        $(id).addClass('in');
        $(id).removeClass('collapsed');
        $(element).removeClass('collapsed');
        expandedEvalPanels[id] = element;
    }
}

function clearCollapsedPanelState() {
    expandedEvalPanels = {};
}