let selectedDocuments = []
let attachmentGuid;
let attachmentId;
let documentQId;
let documentTypeId;

$(document).ready(function () {
    const url = new URL(window.location.href);
    const acKey = decodeURI(url.searchParams.get("acKey"));
    const dateISO = decodeURI(url.searchParams.get("date"));
    const caseNumber = decodeURI(url.searchParams.get("caseNumber"));

    initializeClassificationTypeahead($('#SearchClassificationsURL').val(), $('#ClassificationName'), $('#ClassificationId'));

    $('#createButton').on('click', function () {
        $('.new-case-document')[0].click();
    });

    $("#DocTypeSelect").change(function () {
        let selectedOption = $(this).find('option:selected');
        documentTypeId = selectedOption.val();
        $('#ClassificationId').val(selectedOption.data('classification'));
        $('#ClassificationName').val(selectedOption.data('classificationname'));
    });

    $('#template').change(function () {
        let selectedOption = $(this).find('option:selected');
        attachmentGuid = selectedOption.data('guid');
        attachmentId = selectedOption.val();
        documentQId = selectedOption.data('document');
    });

    $('.new-document-from-template').on('click', function () {
        $('#new-document-from-template-modal').modal('show');
    });

    $('#create-document-btn').on('click', function () {
        createDocumentFromTemplate();
    });

    if (dateISO != "null") {
        const date = fromISOToStandardDateFormatString(dateISO);
        $("#Filter_DateFrom").val(date);
    }

    if (caseNumber != "null") {
        $('#CaseNumber').val(caseNumber);
    }

    $dataTable = $('#mainGrid');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.DateFrom = reformatDate($("#DateFrom").val());
                d.DateTo = reformatDate($("#DateTo").val());
                d.DocTypes = $("#DocTypes").val();
                d.CaseNumber = $("#CaseNumber").val();
                d.SubjectId = $("#SubjectId").val();
                d.Users = $("#Users").val();
                d.Statuses = $("#Statuses").val();
            }
        },
        order: [[1, 'desc']],
        columns: [
            {
                data: "Id", orderable: false, className: 'dt-body-center', render: function (data) {
                    return '<input type="checkbox" class="select-checkbox" value="' + data + '">';
                }
            },
            {
                data: "AcKey", name: "AcKey", className: 'dt-body-center',
                render: function (data, type, full) {
                    if (type === 'display')
                        return $.fn.dataTable.render.previewWithOptions(full.Id, $("#paasPrintDocumentUrl").val(), full.Attachments, "getAttachmentsForDocument(" + full.Id + ")");
                    else
                        return "";
                }
            },
            { data: "AcKeyView", name: "AcKey", filtertype: "text", render: $.fn.dataTable.render.link('Id') },
            /*            { data: "Subject", name: "AcSubject", filtertype: "text" },*/
            { data: "Subject", name: "AcSubject", filtertype: "text", render: $.fn.dataTable.render.link("Subject") },
            { data: "SubjectName", name: "AcSubjectNavigation.AcName2", filtertype: "text", render: $.fn.dataTable.render.ellipsis(30, false) },
            { data: "Date", name: "AdDate", filtertype: "dateTime" },
            { data: "DateDue", name: "AdDateDue", filtertype: "dateTime" },
            { data: "Title", name: "AcTitle", filtertype: "text" },
            { data: "DocType", name: "AcDocType", filtertype: "text" },
            { data: "Classification", name: "AnClassification.AcTypeDesc", filtertype: "text", render: $.fn.dataTable.render.ellipsis(25, false) },
            {
                data: null,
                filtertype: "text",
                orderable: false,
                render: function (data, type, row) {
                    let className = '';
                    let statusName = row.StatusName;

                    if (row.Status === $("#Active").val()) {
                        className = 'status-A';
                    } else if (row.Status === $("#Inactive").val()) {
                        className = 'status-N';
                    }
                    return `<span class="${className}">${statusName}</span>`;
                }
            },
        ],
        colReorder: {
            fixedColumnsLeft: 1,
        },
        drawCallback: function () {
            $('.select-checkbox').on('change', function () {
                documentSelectionChanged(this);
            });
        },
        createdRow: function (row, data) {
            if (data.AcKey == acKey) {
                $(row).addClass('side-menu-item-active').children(":first").addClass('side-menu-item-active');
            }
        },
    });

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

    $('#SubjectId, #Users, #Statuses, #DocTypes').on('change', function () {
        $.fn.dataTable.reload($dataTable);
    });
});

function documentSelectionChanged(cb) {
    if (cb.checked) {
        selectedDocuments.push(cb.value);
    } else {
        const index = selectedDocuments.indexOf(cb.value);
        if (index !== -1) selectedDocuments.splice(index, 1);
    }

    if (selectedDocuments.length > 0) {
        $('#deleteButton').removeClass('disabled');
    } else {
        $('#deleteButton').addClass('disabled');
    }
}

function getAttachmentsForDocument(id) {
    swapPreviewIcon(true, ("previewIcon-" + id), "fa fa-eye");
    $("#previewDropdown-" + id).empty();

    $.get($("#GetAttachmentsForDocument").val(), { qid: id })
        .done(function (response) {
            let func = $("#paasPrintDocumentUrl").val().replace("{0}", id);

            if (response.length === 1) {
                openPdfPreview($("#paasPrintDocumentUrlOnly").val().replace("{0}", id).replace("{1}", response[0].AttachmentId));
            } else {
                response.forEach(attachment => {
                    $("#previewDropdown-" + id).append("<li><a onClick=\"" + func.replace("{1}", attachment.AttachmentId) + "\">" + attachment.Name + "</a></li>");
                });
            }

            swapPreviewIcon(false, ("previewIcon-" + id), "fa fa-eye");
        });
}

function swapPreviewIcon(loading, buttonId, icon) {
    const $button = $("#" + buttonId);
    const $buttonIcon = $button.find("span.eyeIcon");

    if (loading) {
        $buttonIcon.removeClass(icon).addClass("fa fa-spinner fa-spin fa-fw");
    }
    else {
        $buttonIcon.removeClass("fa fa-spinner fa-spin fa-fw").addClass(icon);
    }
}

function openPdfPreview(url) {
    loadPdfPanelContentPAAS($("#pdfPanel"), url, true);
}

function deleteDocuments() {
    $.ajax({
        type: "POST",
        data: { ids: selectedDocuments, deleteParam: false },
        url: $('#GetListOfDeletedDocuments').val(),
    }).done(function (response) {
        if (response && response.length > 0) {
            let deleteErrors = "";
            for (let i = 0; i < response.length; i++) {
                deleteErrors += response[i] + "<br />";
            }

            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: $("#LocDeleteWasNotSuccessfull").val() + "<br />" + deleteErrors,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#LocConfirm").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        $.fn.dataTable.reload($('#mainGrid'));
    });
}

function confirmDeleteDocuments() {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: $("#LocConfirmDeleteRecord").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#LocCancel").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#LocConfirm").val(),
                action: function () {
                    deleteDocuments();
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function createDocumentFromTemplate() {
    swapLoadingIcon(true, "create-document-btn", "fa fa-save");
    $.ajax({
        type: "POST",
        data: {
            attachmentId: attachmentId,
            attachmentGuid: attachmentGuid,
            documentQId: documentQId,
            classificationId: $('#ClassificationId').val(),
            documentTypeId: documentTypeId,
            classificationName: $('#ClassificationName').val(),
            case: $('#CaseNumber').val(),
            filename: $('#Filename').val(),
        },
        url: $('#CreateDocumentFromTemplateURL').val()
    }).done(function (response) {
        if (response.Success) {
            let editDocumentUrl = $('#EditDocumentURL').val();
            window.location.href = `${editDocumentUrl}?qid=${response.QId}`;
        }

        swapLoadingIcon(false, "create-document-btn", "fa fa-save");
    });
}
