@model PantheonRA.BackOffice.Models.DocumentsGridFilterModel
@using PantheonRA.BackOffice.Models
@using PantheonRA.BackOffice.Enums
@using PantheonRA.WebApi.Contracts.Enums
@using PAW.Contracts.Enums
@{
    ViewBag.Title = Loc.Documents;
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("_DocumentsTabNavigation")
        <div class="tab-content">
            @Html.HiddenFor(model => model.DefaultDecimalPlacesPrice)
            @Html.HiddenFor(model => model.DefaultDecimalPlacesQuantity)
            @Html.HiddenFor(model => model.DefaultDecimalPlacesValue)
            <div class="row document-head">
                <div class="@(PantheonRA.BackOffice.CurrentUser.HasGranule(Granules.B2BGranule) ? "col-md-4 col-xs-6" : "col-md-2 col-xs-6")">
                    <div class="form-group">
                        <label class="control-label">@Loc.SearchFilter</label>
                        @Html.TextBoxFor(model => model.Keywords, new { @id = "Keywords", @class = "form-control search-input", @placeholder = Loc.DocumentsSearch, autocomplete = "off" })
                    </div>
                </div>

                <div class="col-md-2 col-xs-6 @(PantheonRA.BackOffice.CurrentUser.HasGranule(Granules.B2BGranule) ? "hidden" : "")">
                    <div class="form-group">
                        <label>@Loc.Subject</label>
                        <input type="hidden" id="partnerPlaceholder" value="@Loc.Partner" />
                        <select id="SubjectId"
                                name="SubjectId"
                                data-placeholder="@Loc.Partner"
                                class="form-control select2withAPI"
                                data-url="@Url.Action("SearchAllSubjects", "Documents")"
                                data-column-names="@Loc.Company,@Loc.Name,@Loc.Address,@Loc.Post"
                                data-bootstrap-columns="col-md-4,col-md-4,col-md-3,col-md-1"
                                data-splitter=","
                                data-allow-clear="true"
                                data-search-width="800">
                            @if (PantheonRA.BackOffice.CurrentUser.HasGranule(Granules.B2BGranule))
                            {
                                <option value="@Model.SubjectId" selected></option>
                            }
                        </select>
                    </div>
                </div>

                <div class="col-lg-2 col-xs-6">
                    <div class="form-group">
                        @Html.LabelFor(model => model.DocTypes, Loc.DocType, new { @class = "control-label" })
                        @Html.DropDownListFor(model => model.DocTypes, new SelectList(ViewBag.DocumentTypes != null ? ViewBag.DocumentTypes : new List<string>(), "Id", "Value"),
                            HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker", "DocTypes", false, Loc.DocTypeShort, true,
                            new { @multiple = "multiple", @data_live_search = "true", @title = Loc.All }))
                        @Html.ValidationMessageFor(model => model.DocTypes, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="col-lg-2 col-xs-6 @(PantheonRA.BackOffice.CurrentUser.HasGranule(Granules.B2BGranule) ? "hidden" : "")">
                    <div class="form-group">
                        @Html.LabelFor(model => model.Classifications, Loc.Classification, new { @class = "control-label" })
                        @Html.DropDownListFor(model => model.Classifications, new SelectList(ViewBag.Classifications != null ? ViewBag.Classifications : new List<string>(), "Id", "Name"),
                            HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker", "Classifications", false, Loc.Classification, true,
                            new { @multiple = "multiple", @data_live_search = "true", @title = Loc.All }))
                        @Html.ValidationMessageFor(model => model.Classifications, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="col-lg-1 col-xs-6 @(PantheonRA.BackOffice.CurrentUser.HasGranule(Granules.B2BGranule) ? "hidden" : "")">
                    <div class="form-group">
                        @Html.LabelFor(model => model.Users, Loc.User, new { @class = "control-label" })
                        @Html.DropDownListFor(model => model.Users, new SelectList(ViewBag.Users != null ? ViewBag.Users : new List<string>(), "Id", "Name"),
                            HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker", "Users", false, Loc.User, true,
                            new { @multiple = "multiple", @data_live_search = "true", @title = Loc.All }))
                        @Html.ValidationMessageFor(model => model.Users, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="col-md-1 col-xs-6">
                    <div class="form-group selectpicker-dropdown">
                        <label class="control-label">@Loc.Status</label>
                        <select id="Statuses"
                                name="Statuses"
                                class="form-control selectpicker"
                                title="@Loc.All"
                                multiple>
                            <option value="@DocumentStatusType.Opened">@Loc.Opened</option>
                            <option value="@DocumentStatusType.Send">@Loc.Send</option>
                            <option value="@DocumentStatusType.Finished">@Loc.Finished</option>
                            <option value="@DocumentStatusType.Declined">@Loc.Rejected</option>
                            <option value="@DocumentStatusType.Exchanged">@Loc.Exchanged</option>
                            <option value="@DocumentStatusType.Error">@Loc.Failed</option>
                        </select>
                    </div>
                </div>

                <div class="col-md-1 col-xs-6">
                    <div class="form-group">
                        <label class="control-label">@Loc.DateFrom</label>
                        <div class="input-group">
                            <span class="input-group-addon"><i class="far fa-calendar alt"></i></span>
                            @Html.TextBoxFor(m => m.DateFrom, "{0:dd.MM.yyyy}", new { @class = "form-control datepicker", @autocomplete = "off" })
                        </div>
                    </div>
                </div>
                <div class="col-md-1 col-xs-6">
                    <div class="form-group">
                        <label class="control-label">@Loc.DateTo</label>
                        <div class="input-group">
                            <span class="input-group-addon"><i class="far fa-calendar alt"></i></span>
                            @Html.TextBoxFor(m => m.DateTo, "{0:dd.MM.yyyy}", new { @class = "form-control datepicker", @autocomplete = "off" })
                        </div>
                    </div>
                </div>
            </div>

            @if (!PantheonRA.BackOffice.CurrentUser.HasGranule(Granules.B2BGranule))
                            {
                <div class="row buttons-tabbed">
                    <button id="documentsDelete" type="button" onclick="confirmDeleteDocuments()" title="@Loc.DeleteWholeDocument"
                            class="btn btn-danger btn-outline pull-right" disabled>
                        <i class="far fa-trash-alt m-r-xs"></i>
                        <span class="visible-lg-inline visible-md-inline">@Loc.Delete</span>
                    </button>

                    @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.RS 
                    || PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.SI 
                    || PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.HR)
                    {
                        @Html.Partial("_FormButtons", new FormButtonsViewModel
                        {
                            ShowCloseBtn = false,
                            IsWizardVisible = true,
                            WizardButtonGroup = new FormButtonGroup
                            {
                                ButtonName = Loc.EInvoice,
                                ButtonTitle = Loc.EInvoice,
                                ButtonIcon = "fa eInvoice-icon",
                                Buttons = new List<FormButton>
                                {
                                    //RS
                                    new FormButton { Text = string.Empty, Icon = "", OnClick = "", IsHidden = true },
                                    new FormButton { Text = Loc.CheckStatusMER, Icon = "", OnClick = "checkSentStatus('" + WorkflowIdentify.MERCheckSendStatusRS + "')", IsHidden = !Model.CanCheckStatusMER, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.RS },
                                    new FormButton { Text = Loc.CheckStatusEInvoice, Icon = "", OnClick = "checkSentStatus('"+ WorkflowIdentify.CheckSendStatusEInvoiceRS + "')", IsHidden = !Model.CanCheckStatusSEF, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.RS },
                                    new FormButton { Text = Loc.MyAccountReceive, Icon = "", OnClick = "runDocumentsWF('"+ WorkflowIdentify.MERReceiveRS + "')", IsHidden = !Model.CanReceiveDocumentsMER, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.RS },
                                    new FormButton { Text = Loc.EInvoiceReceive, Icon = "", OnClick = "runDocumentsWF('"+ WorkflowIdentify.ReceiveInvoiceRS + "')", IsHidden = !Model.CanReceiveDocumentsSEF, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.RS },
                                    new FormButton { Text = Loc.MyEAccountSending, Icon = "", OnClick = "runDocumentsWF('"+ WorkflowIdentify.MERSendRS + "')", IsHidden = !Model.CanSendMER, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.RS },
                                    new FormButton { Text = Loc.EInvoiceSending, Icon = "", OnClick = "runDocumentsWF('"+ WorkflowIdentify.SendEInvoiceRS + "')", IsHidden = !Model.CanSendSEF, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.RS },
                                    new FormButton { Text = Loc.EInvoiceRejection, Icon = "", OnClick = "rejectInvoice('"+ WorkflowIdentify.InvoiceRejectionRS + "')", IsHidden = !Model.CanRejectDocumentsWF, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.RS },
                                    //SI
                                    new FormButton { Text = Loc.ReceiveFromBizBox, Icon = "", OnClick = "runDocumentsWF('"+ WorkflowIdentify.ReceiveBizBoxSI + "')", IsHidden = !Model.CanReceiveDocumentsWF, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.SI },
                                    new FormButton { Text = Loc.EInvoiceBizBox, Icon = "", OnClick = "runDocumentsWF('" + WorkflowIdentify.SendBizBoxSI + "')", IsHidden = !Model.CanSendDocumentsWF, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.SI },
                                    //HR
                                    new FormButton { Text = Loc.MyAccountReceive, Icon = "", OnClick = "runDocumentsWF('"+ WorkflowIdentify.MERReceiveHR + "')", IsHidden = !Model.CanReceiveDocumentsMER, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.HR },
                                    new FormButton { Text = Loc.FINAEAccountReceive, Icon = "", OnClick = "runDocumentsWF('"+ WorkflowIdentify.FinaReceiveHR + "')", IsHidden = !Model.CanReceiveDocumentsSEF, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.HR },
                                    new FormButton { Text = Loc.MyEAccountSending, Icon = "", OnClick = "runDocumentsWF('" + WorkflowIdentify.MERSendHR + "')", IsHidden = !Model.CanSendMER, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.HR },
                                    new FormButton { Text = Loc.FINAEAccountSending, Icon = "", OnClick = "runDocumentsWF('" + WorkflowIdentify.FinaSendHR + "')", IsHidden = !Model.CanSendSEF, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.HR },
                                }
                            }
                        })
                    }

                    <a href="@Url.Action("Create", "Documents")" class="btn btn-primary btn-outline pull-right">
                        <i class="fa fa-plus" title="@Loc.NewDocument"></i>
                        <span class="m-l-xs hidden-xs hidden-sm">@Loc.NewDocument</span>
                    </a>
                </div>
            }

            <div class="project-list">
                <div class="document-list document-list-no-footer">
                    <table id="mainGrid" data-grid-id="documents" data-url="@Url.Action("DocumentList", "Documents")" class="list-table">
                        <thead>
                            <tr>
                                <th width="3%" class="dt-head-center"></th>
                                <th width="2%" data-function="openPdfPreview('@Url.Action("PAASPrintDocument", "Documents")?docKey={0}')"></th>
                                <th width="10%" data-url="@Url.Action("Edit", "Documents")?id=">@Loc.Number</th>
                                <th width="10%">@Loc.SubjectCode</th>
                                <th width="10%">@Loc.SubjectTitle</th>
                                <th width="6%">@Loc.Date</th>
                                <th width="7%">@Loc.DateDue</th>
                                <th width="10%">@Loc.Title</th>
                                @*<th width="10%" class="dt-head-right">@Loc.Amount</th>*@
                                <th width="4%">@Loc.DocTypeShort</th>
                                <th width="7%">@Loc.Classification</th>
                                <th width="10%">@Loc.Note</th>
                                @*<th>@Loc.Department</th>*@
                                <th width="7%">@Loc.User</th>
                                <th width="7%">@Loc.Status</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal inmodal fade" id="rejectModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <input id="rejectModalIdentify" hidden />
                <input id="rejectModalQId" hidden />
                <div class="row border-bottom">
                    <h3>@Loc.RejectDocument</h3>
                </div>
                <div class="row m-t-sm">
                    <div class="col-xs-2">
                        <label class="control-label m-t-sm">@Loc.Document</label>
                    </div>
                    <div class="col-xs-6">
                        <input class="form-control" id="rejectModalAcKey" />
                    </div>
                    <div class="col-xs-12 m-t-sm">
                        <textarea class="form-control" id="rejectModalNote" rows="3" placeholder="@Loc.Note"></textarea>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-ghost" data-dismiss="modal"><i class="fa fa-times m-r-xs"></i>@Loc.Cancel</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="rejectInvoiceWF()">@Loc.Reject</button>
            </div>
        </div>
    </div>
</div>

<input id="paasPrintDocumentUrl" value="openPdfPreview('@Url.Action("PAASPrintDocument", "Documents")?docKey={0}&attachId={1}')" hidden />
<input id="paasPrintDocumentUrlOnly" value="@Url.Action("PAASPrintDocument", "Documents")?docKey={0}&attachId={1}" hidden />

@Html.Partial("~/Views/Shared/Components/_sidePanel.cshtml",
    new PantheonRA.BackOffice.Models.SidePanelViewModel {
        Id = "pdfPanel",
        Class = PantheonRA.BackOffice.CurrentUser.HasGranule(Granules.B2BGranule) ? "no-tabs" : string.Empty
    })
@Html.Partial("~/Views/TimeRecords/_NoteModal.cshtml")

@section pageScripts{
    <script>
        var selectedDocuments = [];

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

            if (urlString.includes("date")) {
                var date = fromISOToStandardDateFormatString(dateISO);
                $("#Filter_DateFrom").val(date);
            }

            $("#Filter_DocType").trigger("change");
            $("#Filter_PaymentTypeId").trigger("change");

            $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.SubjectId = $("#SubjectId").val();
                        d.Users = $("#Users").val();
                        d.Classifications = $("#Classifications").val();
                        d.Statuses = $("#Statuses").val();
                    }
                },
                order: [[1, 'desc']],
                columns: [
                    { data: "Id", orderable: false, className: 'dt-body-center', @Html.Raw(PantheonRA.BackOffice.CurrentUser.HasGranule(Granules.B2BGranule) ? "render: function(){ return ''; }" : "render: $.fn.dataTable.render.checkbox('documentSelectionChanged')") },
                    {
                        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", @Html.Raw(PantheonRA.BackOffice.CurrentUser.HasGranule(Granules.B2BGranule) ? string.Empty : "render: $.fn.dataTable.render.link('AcKey')") },
                    { data: "Subject", name: "AcSubject", filtertype: "text" },
                    { 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" },
                    //TODO: add orderby name, enable Price when we can hide it by default
                    //{ data: "Price", name: "AnAmount", orderable: false, filtertype: "number", render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val()), className: 'dt-body-right' },
                    { data: "DocType", name: "AcDocType", filtertype: "text" },
                    { data: "Classification", name: "AnClassification.AcTypeDesc", filtertype: "text", render: $.fn.dataTable.render.ellipsis(25, false) },
                    { data: "Note", name: "AcNote", filtertype: "text", render: $.fn.dataTable.render.note("Id") },
                    //{ data: "Department", name: "AcDepartment", orderable: false, filtertype: "text" }, //TODO: Enable Department when we can hide it by default
                    { data: "Clerk", name: "AnClerkUser.AcTitle", orderable: false, filtertype: "text" },
                    { data: "StatusName", name: "AcStatus", orderable: false }
                ],
                colReorder: {
                    fixedColumnsLeft: 1,
                },
                createdRow: function (row, data) {
                    if (data.AcKey == acKey) {
                        $(row).addClass('side-menu-item-active').children(":first").addClass('side-menu-item-active');
                    }
                }
            });

            $("select").on("change", function () {
                $.fn.dataTable.reload($dataTable);
            });

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

            $('.datepicker').datepicker()
                .on('click', function (e) {
                    $(this).select();
                });

            $(".datepicker").on("change", function () {
                $.fn.dataTable.reload($dataTable);
            });
        });

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

            if (selectedDocuments.length > 0)
                $("#documentsDelete").attr("disabled", false);
            else
                $("#documentsDelete").attr("disabled", true);
        }

        function confirmDocument() {
            $.ajax({
                type: "POST",
                data: { ids: selectedDocuments },
                url: "@Url.Action("ConfirmDocuments", "Documents")",
            });
        }

        function deleteDocuments() {
            $.ajax({
                type: "POST",
                data: { ids: selectedDocuments },
                url: "@Url.Action("DeleteDocuments", "Documents")",
            }).done(function (response) {
                if (response && response.length > 0) {
                    var deleteErrors = "";
                    for (let i = 0; i < response.length; i++) {
                        deleteErrors += response[i] + "<br />";
                    }

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

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

        function confirmDeleteDocuments() {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "question",
                text: '@Loc.ConfirmDeleteMessage',
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.Cancel',
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Confirm',
                        action: function () {
                            deleteDocuments();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        function format(item) { return item.Text; };

        function documentsSelectionChanged() {
            //TODO: implement when functionallity is defined
        }

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

            $.get('@Url.Action("GetAttachmentsForDocument", "Documents")', { qid: id })
                .done(function (response) {
                    var 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 checkSentStatus(identify) {
            $().customToast({
                type: 'success',
                text: (identify === "@WorkflowIdentify.MERCheckSendStatusRS" ? "@Loc.DocumentVerificationForMyAccount" : "@Loc.DocumentVerificationForEInvoice"),
                id: 'checkSentStatusToast'
            });

            $("#wizardButton").find("i").removeClass("fas fa-wand-magic").addClass("fa fa-spinner fa-spin fa-fw");

            $.get('@Url.Action("CheckSentStatus", "Documents")', { identify: identify })
                .done(function (response) {
                    $.fn.dataTable.reload($('#mainGrid'));

                    var toast = $("#checkSentStatusToast");
                    if (toast) {
                        toast.remove();
                    }

                    $("#wizardButton").find("i").removeClass("fa fa-spinner fa-spin fa-fw").addClass("fas fa-wand-magic");

                    if (response && response.Variables) {
                        $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "success",
                        text: "@Loc.DocumentStatusesHaveBeenSuccessfullyUpdated",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                    }
                });
        }

        function runDocumentsWF(identify) {
            $("#wizardButton").find("i").removeClass("fa eInvoice-icon").addClass("fa fa-spinner fa-spin fa-fw");

            $.get('@Url.Action("CheckSentStatus", "Documents")', { identify: identify })
                .done(function (response) {
                    $("#wizardButton").find("i").removeClass("fa fa-spinner fa-spin fa-fw").addClass("fa eInvoice-icon");

                    if (response && (response.Variables && response.Variables.ErrorMessages || response.Error)) {
                        var error = response.Variables ? response.Variables.ErrorMessages : response.Error;

                        $().customModal({
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "error",
                            text: error,
                            buttons: [
                                {
                                    icon: 'fa fa-check',
                                    text: "@Loc.Confirm",
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                    } else {
                        // TODO: Handle successful response
                        $.fn.dataTable.reload($('#mainGrid'));
                    }
                });
        }

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

            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 rejectInvoice(identify) {
            if (selectedDocuments.length === 0 || selectedDocuments.length > 1) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: selectedDocuments.length > 1 ? "@Loc.OnlyOneDocumentCanBeSelected" : "@Loc.DocumentMustBeSelected",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                return;
            }

            $("#rejectModalIdentify").val(identify);
            $("#rejectModalQId").val(selectedDocuments[0]);

            var row = $('#mainGrid').DataTable().row($("#cb" + selectedDocuments[0]).closest('tr'));
            var ackey = row.data()["AcKeyView"];

            $("#rejectModalAcKey").val(ackey);
            $("#rejectModalNote").val("");
            $("#rejectModal").modal("show");
        }

        function rejectInvoiceWF() {
            $("#wizardButton").find("i").removeClass("fa eInvoice-icon").addClass("fa fa-spinner fa-spin fa-fw");

            $.ajax({
                type: "POST",
                data: { WorkflowKey: $("#rejectModalIdentify").val(), DocumentQId: $("#rejectModalQId").val(), Note: $("#rejectModalNote").val() },
                url: "@Url.Action("RejectDocument", "Documents")",
            }).done(function (response) {
                $("#wizardButton").find("i").removeClass("fa fa-spinner fa-spin fa-fw").addClass("fa eInvoice-icon");
                selectedDocuments = [];

                if (response && (response.Variables && response.Variables.ErrorMessages || response.Error)) {
                    var error = response.Variables ? response.Variables.ErrorMessages : response.Error;

                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text: error,
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                } else {
                    $.fn.dataTable.reload($('#mainGrid'));

                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "success",
                        text: "@Loc.DocumentRejectedSuccessfully",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            });
        }
    </script>
}