@model BulkEditListModel
@inject AdminAreaSettings adminAreaSettings
@{
    //page title
    ViewBag.Title = Loc["Admin.Catalog.BulkEdit"];
}
<form asp-area="@Constants.AreaAdmin" asp-controller="Product" asp-action="BulkEdit" method="post">
    
    <div class="row">
        <div class="col-md-12">
            <div class="x_panel light form-fit popup-window">
                <div class="x_title">
                    <div class="caption level-caption">
                        <i class="fa fa-cubes"></i>
                        @Loc["Admin.Catalog.BulkEdit"]
                    </div>
                    <vc:admin-widget widget-zone="product_bulk_edit_buttons" additional-data="null" />
                </div>
                <div class="x_content form">
                    <div class="form-horizontal">
                        <div class="form-body">
                            <div class="main-header col-12 px-0">
                                <div class="row align-items-end">
                                    <div class="col-md-8 col-ms-12 col-12">
                                        <div class="form-group mb-0">
                                            <admin-label asp-for="SearchProductName" class="control-label" />
                                            <admin-input asp-for="SearchProductName" />
                                        </div>
                                    </div>
                                    <div class="col-md-4 col-sm-12 col-12">
                                        <div class="form-actions">
                                            <div class="btn-group">
                                                <button class="btn btn-success filter-submit" id="search-products">
                                                    <i class="fa fa-search"></i> @Loc["Admin.Common.Search"]
                                                </button>
                                                <button class="btn btn-info" type="button" data-toggle="collapse" data-target="#filterCollapse" aria-expanded="false" aria-controls="filterCollapse">
                                                    <i class="fa fa-filter"></i>&nbsp; @Loc["Admin.Common.Filters"]
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="collapse" id="filterCollapse">
                                <div class="drop-filters-container w-100">
                                    <div class="form-group">
                                        <admin-label asp-for="SearchCategoryId" class="col-sm-3 control-label" />
                                        <div class="col-md-9 col-sm-9">
                                            <admin-input asp-for="SearchCategoryId" class="col-sm-3 control-label" />
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <admin-label asp-for="SearchBrandId" class="col-sm-3 control-label" />
                                        <div class="col-md-9 col-sm-9">
                                            <admin-input asp-for="SearchBrandId" />
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <admin-label asp-for="SearchCollectionId" class="col-sm-3 control-label" />
                                        <div class="col-md-9 col-sm-9">
                                            <admin-input asp-for="SearchCollectionId" />
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <admin-label asp-for="SearchProductTypeId" class="col-sm-3 control-label" />
                                        <div class="col-md-9 col-sm-9">
                                            <admin-select asp-for="SearchProductTypeId" asp-items="Model.AvailableProductTypes" />
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <admin-label asp-for="SearchStoreId" class="col-sm-3 control-label" />
                                        <div class="col-md-9 col-sm-9">
                                            <admin-select asp-for="SearchStoreId" asp-items="Model.AvailableStores" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="x_content">
                                <div id="products-grid"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
            @{
                var methods = ManageInventoryMethod.DontManageStock.ToSelectList(Context);
            }
            var allInventoryMethod = [
                @foreach (var method in methods)
                {
                        <text>
                        {
                            Id: '@(method.Value)',
                            Name: "@Html.Raw(method.Text)"
                        },
                        </text>
                }
            ];

        $(document).ready(function() {
            var _grid = $("#products-grid").kendoGrid({
                dataSource: {
                    transport: {
                        read: {
                            url: "@Html.Raw(Url.Action("BulkEditSelect", "Product", new { area = Constants.AreaAdmin }))",
                            type: "POST",
                            dataType: "json",
                            data: additionalData
                        },
                        update: {
                            url: "@Html.Raw(Url.Action("BulkEditUpdate", "Product", new { area = Constants.AreaAdmin }))",
                            type: "POST",
                            dataType: "json"
                        },
                        destroy: {
                            url: "@Html.Raw(Url.Action("BulkEditDelete", "Product", new { area = Constants.AreaAdmin }))",
                            type: "POST",
                            dataType: "json"
                        },
                        parameterMap: function(data, operation) {
                            if (operation != "read") {

                                var result = {};

                                for (var i = 0; i < data.models.length; i++) {
                                    var entity = data.models[i];

                                    for (var member in entity) {
                                        result["products[" + i + "]." + member] = entity[member];
                                        if (member == 'Price' || member == 'OldPrice') {
                                            result["products[" + i + "]." + member] = kendo.toString(entity[member], "n4");
                                        }

                                    }
                                }

                                addAntiForgeryToken(result);
                                return result;
                            } else {
                                addAntiForgeryToken(data);
                                //return JSON.stringify(data);
                                return data;
                            }
                        }
                    },
                    schema: {
                        data: "Data",
                        total: "Total",
                        errors: "Errors",
                        model: {
                            id: "Id",
                            fields: {
                                Name: { editable: true, type: "string" },
                                ProductId: { editable: false, type: "string" },
                                Sku: { editable: true, type: "string" },
                                Price: { editable: true, type: "number" },
                                OldPrice: { editable: true, type: "number" },
                                ManageInventoryMethodId: { editable: true, type: "int" },
                                ManageInventoryMethod: { editable: true, type: "string" },
                                StockQuantity: { editable: true, type: "number" },
                                Published: { editable: true, type: "boolean" },
                                Id: { editable: false, type: "string" }
                            }
                        }
                    },
                    requestEnd: function (e) {
                        if (e.type == "update") {
                            this.read();
                        }
                    },
                    error: function(e) {
                        display_kendoui_grid_error(e);
                        // Cancel the changes
                        this.cancelChanges();
                    },
                    //bulk editing
                    batch: true,
                    pageSize: @(adminAreaSettings.DefaultGridPageSize),
                    serverPaging: true,
                    serverFiltering: true,
                    serverSorting: true
                },
                pageable: {
                    refresh: true,
                    pageSizes: [@(adminAreaSettings.GridPageSizes)]
                },
                toolbar: ["save", "cancel"],
                editable: {
                    confirmation: true,
                    //bulk editing
                    mode: "incell"
                },
                scrollable: true,
                columns: [ {
                    field: "Name",
                    title: "@Loc["Admin.Catalog.BulkEdit.Fields.Name"]",
                    width: 200
                }, {
                    field: "ProductId",
                    title: "@Loc["Admin.Common.View"]",
                    width: 80,
                    template: '<a href="@Url.Action("Edit", "Product", new { area = Constants.AreaAdmin })/#=Id#">@Loc["Admin.Common.View"]</a>'
                },{
                    field: "Sku",
                    title: "@Loc["Admin.Catalog.BulkEdit.Fields.Sku"]",
                    width: 100
                }, {
                    field: "Price",
                    title: "@Loc["Admin.Catalog.BulkEdit.Fields.Price"]",
                    width: 100,
                    editor: function (container, options) {
                        $('<input name="' + options.field + '"/>')
                            .appendTo(container)
                            .kendoNumericTextBox({
                                format: "{0:n4}",
                                decimals: 4
                            });
                    }
                }, {
                    field: "OldPrice",
                    title: "@Loc["Admin.Catalog.BulkEdit.Fields.OldPrice"]",
                    width: 100,
                    editor: function (container, options) {
                        $('<input name="' + options.field + '"/>')
                            .appendTo(container)
                            .kendoNumericTextBox({
                                format: "{0:n4}",
                                decimals: 4
                            });
                    }
                }, {
                    field: "StockQuantity",
                    title: "@Loc["Admin.Catalog.BulkEdit.Fields.StockQuantity"]",
                    //integer format
                    format: "{0:0}",
                    width: 100
                }, {
                    field: "ManageInventoryMethod",
                    title: "@Loc["Admin.Catalog.BulkEdit.Fields.ManageInventoryMethod"]",
                    width: 150,
                    editor: function (container, options) {
                        $("<input data-bind='value:ManageInventoryMethod' />")
                            .attr("id", "ddl_ManageInventoryMethod")
                            .appendTo(container)
                            .kendoDropDownList({
                                dataSource: allInventoryMethod,
                                dataTextField: "Name",
                                dataValueField: "Name",
                                template: "<span data-id='${data.id}'>${data.Name}</span>",
                                select: function (e) {
                                    var product = _grid.dataItem($(e.sender.element).closest("tr"));
                                    product.ManageInventoryMethodId = e.dataItem.Id;
                                }
                            });
                    }
                },{
                    field: "Published",
                    title: "@Loc["Admin.Catalog.BulkEdit.Fields.Published"]",
                    width: 90
                }, {
                    command: { name: "destroy", text: "@Loc["Admin.Common.Delete"]" },
                    title: "@Loc["Admin.Common.Delete"]",
                    width: 100
                }
                ]
            }).data("kendoGrid");
        });
    </script>

    <script>

        $(document).ready(function () {
            $('#search-products').click(function () {
                    var grid = $('#products-grid').data('kendoGrid');
                    grid.dataSource.page(1); //new search. Set page size to 1
                                             //grid.dataSource.read(); we already loaded the grid above using "page" function
                    return false;
                });

            $("#@Html.IdFor(model => model.SearchProductName)").keydown(function (event) {
                    if (event.keyCode == 13) {
                    $("#search-products").click();
                        return false;
                    }
                });
            });

            function additionalData() {
                var data = {
                SearchProductName: $('#@Html.IdFor(model => model.SearchProductName)').val(),
                SearchCategoryId: $('#SearchCategoryId').val(),
                SearchBrandId: $('#SearchBrandId').val(),
                SearchCollectionId: $('#SearchCollectionId').val(),
                SearchProductTypeId: $('#SearchProductTypeId').val(),
                SearchStoreId: $('#SearchStoreId').val(),
            };
            addAntiForgeryToken(data);
            return data;
        }
    </script>
</form>