@using PantheonRA.BackOffice.Enums
@using PantheonRA.BackOffice.Models
@model PantheonRA.BackOffice.Models.WholesaleGridFilterModel
@{
    ViewBag.Title = Loc.PurchaseReceivedBills;
    var isLocBG = (PantheonRA.BackOffice.CurrentUser.Localization == PAW.Contracts.Enums.Localization.Code.BG);
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("_RecievedBillsTabNavigation")

        <div class="row buttons-tabbed">
            @Html.Partial("_GridButtons", new GridButtonsViewModel {
                AddButton = new PantheonRA.BackOffice.Models.FormButton{
                    Url = Url.Action("Create", "ReceivedBills"),
                    Icon = "fa fa-plus",
                    Text = Loc.New
                }
                // TODO: Enable when implemented multi confirm
                //,
                //GridActionsGroup = new FormButtonGroup
                //{
                //    Buttons = new List<FormButton>()
                //    {
                //        new FormButton
                //        {
                //            Text = Loc.ConfirmReceivedBills,
                //            Icon = "fa fa-check",
                //            OnClick = "confirmBills()"
                //        }
                //    }
                //}
            })
        </div>
        <div class="tab-content">
            @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-2 col-xs-4">
                    @Html.Partial("~/Views/Reports/_IssuedBillsTabNavigation.cshtml", new IssuedBillsTabModel() { Type = IssuedBillsTabType.Summary, Author = AuthorType.ReceivedBills })
                </div>

                <div class="col-md-3 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.Search, autocomplete = "off" })
                    </div>
                </div>

                <div class="col-lg-2 col-md-3 col-xs-6">
                    <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 selectpicker", "DocType", false, Loc.DocType, true, 
                            new { @multiple = "multiple", @title = Loc.Select }))
                        @Html.ValidationMessageFor(model => model.DocType, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="col-lg-1 col-xs-6">
                    <div class="form-group">
                        <label>@Loc.Currency</label>
                        @Html.DropDownListFor(model => model.Currency, new SelectList(ViewBag.CurrencyTypes, "Value", "Text", ""), Loc.Currency,
                            HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "Currency", false))
                    </div>
                </div>

                <div class="col-md-2 col-xs-6 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 col-xs-6 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-bills" data-url="@Url.Action("ReceivedBillsList", "ReceivedBills")" 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-url="@Url.Action("Edit", "ReceivedBills")?id=" width="10%">@Loc.Number</th>
                                <th data-visible="@(isLocBG ? true : false)" data-url="@Url.Action("Edit", "ReceivedBills")?id=" width="10%">@Loc.ProtocolNumberShort</th>
                                <th width="16%" data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Index", "ReceivedBills"))&id=">@Loc.Supplier</th>
                                <th width="16%" data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Index", "ReceivedBills"))&id=">@Loc.Supplier</th>
                                <th width="16%" data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Index", "ReceivedBills"))&id=">@Loc.ThirdParty</th>
                                <th width="16%" data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Index", "ReceivedBills"))&id=">@Loc.ThirdParty</th>
                                <th class="dt-head-right" width="8%">@Loc.PriceWithoutTax</th>
                                <th class="dt-head-right" width="10%">@Loc.ForPayment</th>
                                <th width="8%">@Loc.TakeoverDate</th>
                                <th width="8%">@Loc.BillReceivedDate</th>
                                <th width="8%">@Loc.DateDue</th>
                                <th width="8%">@Loc.OrderFormDate</th>
                                <th width="8%">@Loc.DocumentOne</th>
                                <th width="8%">@Loc.DocumentTwo</th>
                                <th width="13%">@Loc.Warehouse</th>
                                <th width="6%">@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" />

@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({
                format: 'dd.mm.yyyy',
                language: $('#languageDate').val()
            }).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() ? $("#DocType").val().join(",") : $("#DocType").val();
                        d.WholesaleFilter = $("#customDateEnum").val();
                        d.Currency = $("#Currency").val();
                    }
                },
                columns: [
                    { data: "", name: "", className: 'dt-body-center dt-head-center', render: $.fn.dataTable.render.previewReportTreeOptions("AcKey", null) },
                    { 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: "Supplier", name: "AcIssuer", filtertype: "text", render: $.fn.dataTable.render.link("Supplier"), visible: $("#OurCompIsName2").val() === "False" },
                    { data: "SupplierName", name: "AcIssuerNavigation.AcName2", filtertype: "text", render: $.fn.dataTable.render.link("Supplier", 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: function (data, type, full) {
                            return $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val(), '', " " + full.Currency).display(data);
                        },
                        className: 'dt-body-right'
                    },
                    {
                        data: "PriceWithVAT",
                        name: "AnForPay",
                        filtertype: "number",
                        render: function (data, type, full) {
                            return $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val(), '', " " + full.Currency).display(data);
                        },
                        className: 'dt-body-right'
                    },
                    { data: "IssueDate", name: "AdDate", filtertype: "dateTime" },
                    { data: "Received", name: "AdDateInv", filtertype: "dateTime" },
                    { data: "DateDue", name: "AdDateDue", filtertype: "dateTime" },
                    { data: "OrderFormDate", name: "AdDateDoc1", filtertype: "text" },
                    { data: "Order", name: "AcDoc1", filtertype: "text" },
                    { data: "OrderForm", name: "AcDoc2", filtertype: "text" },
                    { data: "Receiver", name: "AcReceiver", filtertype: "text" },
                    { data: "StatusDisplay", 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);
        }
    </script>
}