@using PAW.Contracts.Enums
@using PantheonRA.BackOffice.Enums
@using PantheonRA.BackOffice.Models
@model PantheonRA.BackOffice.Models.AdvancePaymentGridFilterModel

@{
    ViewBag.Title = Loc.AdvancePayments;
    var isLocRS = (PantheonRA.BackOffice.CurrentUser.Localization == PAW.Contracts.Enums.Localization.Code.RS);
    var isLocBG = (PantheonRA.BackOffice.CurrentUser.Localization == PAW.Contracts.Enums.Localization.Code.BG);
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("_ReceivedAdvancePaymentsTabNavigation")
        <div class="tab-content">
            <div class="row buttons-tabbed">
                <button id="openPrintOptions" type="button" onclick="openPrintOptions('@AuthorType.ReceivingAdvancePayment')" title="@Loc.Print"
                        class="btn btn-primary pull-right collapsable-form-button">
                    <i class="far fa-print m-r-xs"></i>
                    <span class="visible-lg-inline visible-md-inline">@Loc.Print</span>
                </button>

                @Html.Partial("_GridButtons", new GridButtonsViewModel
                {
                    AddButton = new PantheonRA.BackOffice.Models.FormButton
                    {
                        Url = Url.Action("CreateReceivingAdvancePayment", "AdvancePayment"),
                        Icon = "fa fa-plus",
                        Text = Loc.New
                    }
                })
            </div>

            @Html.HiddenFor(model => model.DefaultDecimalPlacesPrice)
            @Html.HiddenFor(model => model.DefaultDecimalPlacesQuantity)
            @Html.HiddenFor(model => model.DefaultDecimalPlacesValue)
            @Html.HiddenFor(model => model.OurCompIsName2)
            <div class="row document-head">
                <div class="col-md-3">
                    <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.Search, autocomplete = "off" })
                    </div>
                </div>

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

                <div class="col-md-2 dateFilter">
                    <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>
                            <input class="form-control datepicker" id="Filter_DateFrom" name="Filter.DateFrom" type="text" value="@DateTime.Now.Date.AddMonths(-1).ToString(Loc.DateFormat)">
                        </div>
                    </div>
                </div>
                <div class="col-md-2 dateFilter">
                    <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>
                            <input class="form-control datepicker" id="Filter_DateTo" name="Filter.DateTo" type="text" value="@DateTime.Now.Date.ToString(Loc.DateFormat)">
                        </div>
                    </div>
                </div>
            </div>

            <div class="project-list">
                <div class="document-list">
                    <table id="mainGrid" data-grid-id="received-advance-payments" data-url="@Url.Action("AdvancePaymentsList", "AdvancePayment")" class="list-table">
                        <thead>
                            <tr>
                                <th width="3%" data-function="openPdfPreview('@Url.Action("PAASPrintByAcKeyAndType", "Move")?fiscalize=false&preview={2}&acKey={0}&type={1}')"></th>
                                <th data-visible="@(isLocRS ? true : false)">@Loc.SDCInvoiceNumber</th>
                                <th width="10%" data-url="@Url.Action("EditReceivingAdvancePayment", "AdvancePayment")?id=">@Loc.Number</th>
                                <th data-visible="@(isLocBG ? true : false)" width="10%" data-url="@Url.Action("EditReceivingAdvancePayment", "AdvancePayment")?id=">@Loc.ProtocolNumberShort</th>
                                <th data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Index", "AdvancePayment"))&id=">@Loc.Buyer</th>
                                <th data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Index", "AdvancePayment"))&id=">@Loc.Buyer</th>
                                <th data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Index", "AdvancePayment"))&id=">@Loc.ThirdParty</th>
                                <th data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Index", "AdvancePayment"))&id=">@Loc.ThirdParty</th>
                                <th width="8%" class="dt-head-right">@Loc.PriceWithoutTax</th>
                                <th width="8%" class="dt-head-right">@Loc.ToPay</th>
                                <th width="9%">@Loc.ExpectedDelivery</th>
                                <th width="8%">@Loc.Date</th>
                                <th width="8%">@Loc.Status</th>
                            </tr>
                        </thead>
                    </table>
                </div>

                <div class="row document-footer document-footer-sm">
                    <div class="col-xs-9">
                        <div class="form-group">
                            <span class="pull-left"><span>@Loc.NumberOfRows:</span> <b class="grid-data-total-items"></b></span>
                            <span class="pull-right"><span>@Loc.VAT:</span> <b id="grid-data-vat-sum"></b></span>
                            <span class="pull-right m-r-md"><span>@Loc.Total:</span> <b id="grid-data-total-sum"></b></span>
                        </div>
                    </div>
                    <div class="col-xs-3 document-head-highlight-input">
                        <div class="form-group text-right">
                            <span>@Loc.TotalWithTax:</span> <label id="grid-data-vat-total-sum"></label>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<input type="hidden" id="customDateEnum" value="@PantheonRA.BackOffice.Enums.ItemsDisplayFilterType.CustomDate" />
<input id="locRS" value="@Localization.Code.RS" type="hidden" />
<input id="IndexMoveUrl" value="@Url.Action("Index", "Move")" type="hidden" />

@Html.Partial("~/Views/Shared/Components/_sidePanel.cshtml", new PantheonRA.BackOffice.Models.SidePanelViewModel { Id = "pdfPanel" })
@Html.Partial("~/Views/Shared/Components/_PreviewPrintMenuButton.cshtml", new PantheonRA.BackOffice.Models.PreviewReportTreeViewModel { ReportTree = Model.ReportTree })

@section pageScripts{
    <script>
        $(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);
            }

            $('.datepicker').datepicker()
                .on('click', function (e) {
                    $(this).select();
                }).on('changeDate', function () {
                    $(this).datepicker('hide');
                    $.fn.dataTable.reload($dataTable);
                });

            $dataTable = $('#mainGrid');
            $dataTable.DataTable({
                ajax: {
                    url: $dataTable.attr('data-url'),
                    data: function (d) {
                        d.Keywords = $("#Keywords").val();
                        d.DateFrom = reformatDate($("#Filter_DateFrom").val());
                        d.DateTo = reformatDate($("#Filter_DateTo").val());
                        d.DocType = $("#DocType").val();
                        d.ItemDisplayFilter = $("#customDateEnum").val();
                        d.Author = "@AuthorType.ReceivingAdvancePayment";
                    }
                },
                columns: [
                    { data: "", name: "", className: 'dt-body-center dt-head-center', render: $.fn.dataTable.render.previewReportTreeOptions("AcKey", null, null) },
                    { data: "FiscalCode", name: "FiscalCode", filtertype: "text" },
                    { data: "AcKeyDisplay", name: "AcKey", filtertype: "text", render: $.fn.dataTable.render.link("AcKey") },
                    { data: "Protocol", name: "AcProtocol", filtertype: "text", render: $.fn.dataTable.render.link("AcKey") },
                    { data: "Receiver", name: "AcReceiver", filtertype: "text", render: $.fn.dataTable.render.link("Receiver"), visible: $("#OurCompIsName2").val() === "False" },
                    { data: "ReceiverName", name: "AcReceiverNavigation.AcName2", filtertype: "text", render: $.fn.dataTable.render.link("Receiver", false, null, 30), visible: $("#OurCompIsName2").val() === "True" },
                    { data: "ThirdParty", name: "AcPrsn3", filtertype: "text", render: $.fn.dataTable.render.link("ThirdParty"), visible: $("#OurCompIsName2").val() === "False" },
                    { data: "ThirdPartyName", name: "AcPrsn3Navigation.AcName2", filtertype: "text", render: $.fn.dataTable.render.link("ThirdParty", false, null, 30), visible: $("#OurCompIsName2").val() === "True" },
                    { data: "Price", name: "AnValue", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val()), className: 'dt-body-right' },
                    { data: "PriceWithVAT", name: "AnForPay", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val()), className: 'dt-body-right' },
                    { data: "ExpectedDeliveryDate", name: "AdDateBeforeVat", filtertype: "dateTime" },
                    { data: "Date", name: "AdDate", filtertype: "dateTime" },
                    { data: "Status", name: "AcVerifyStatus" }
                ],
                colReorder: {
                    fixedColumnsLeft: 1,
                },
                createdRow: function (row, data, dataIndex) {
                    if (data.CanceledInvoice) {
                        $(row).addClass('danger');
                    }

                    if (data.AcKey == acKey) {
                        $(row).addClass('side-menu-item-active').children(":first").addClass('side-menu-item-active');
                    }

                    $(row).find(".custom-dropdown").customDropdown();
                    setPreviewDropdownToggle($(row).find(".custom-dropdown"), data.AcKey);
                }
            }).on('xhr.dt', function (e, settings, json, xhr) {
                if (json && json.prop) {
                    $('#grid-data-total-sum').html($.fn.dataTable.render.number('.', ',', 2).display(json.prop.SumAmount));
                    $('#grid-data-vat-sum').html($.fn.dataTable.render.number('.', ',', 2).display(json.prop.SumVat));
                    $('#grid-data-vat-total-sum').html($.fn.dataTable.render.number('.', ',', 2).display(json.prop.SumAmountWithVat));
                    $('.grid-data-start-items').html(json.recordsTotal === 0 ? '0' : '1');
                    $('.grid-data-total-items').html(json.recordsTotal);
                }
            });

            $("select").off("change");
            $("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);
            });
        });

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

        function openPrintOptions(formName) {
            window.location = $("#IndexMoveUrl").val() + '?formName=' + formName + '&docType=' + $("#DocType option:selected").val();
        }
    </script>
}
