import { Component } from '@angular/core';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { FacetValueFormInputComponent, JobState, ProductListQueryDocument, TypedBaseListComponent, } from '@vendure/admin-ui/core';
import { EMPTY, lastValueFrom } from 'rxjs';
import { delay, switchMap } from 'rxjs/operators';
import * as i0 from "@angular/core";
import * as i1 from "@vendure/admin-ui/core";
import * as i2 from "@clr/angular";
import * as i3 from "@angular/common";
import * as i4 from "@angular/router";
import * as i5 from "@ngx-translate/core";
export class ProductListComponent extends TypedBaseListComponent {
    constructor(dataService, modalService, notificationService, jobQueueService) {
        super();
        this.dataService = dataService;
        this.modalService = modalService;
        this.notificationService = notificationService;
        this.jobQueueService = jobQueueService;
        this.pendingSearchIndexUpdates = 0;
        this.customFields = this.getCustomFieldConfig('Product');
        this.filters = this.createFilterCollection()
            .addIdFilter()
            .addDateFilters()
            .addFilters([
            {
                name: 'enabled',
                type: { kind: 'boolean' },
                label: _('common.enabled'),
                filterField: 'enabled',
            },
            {
                name: 'slug',
                type: { kind: 'text' },
                label: _('common.slug'),
                filterField: 'slug',
            },
        ])
            .addFilter({
            name: 'facetValues',
            type: {
                kind: 'custom',
                component: FacetValueFormInputComponent,
                serializeValue: value => value.map(v => v.id).join(','),
                deserializeValue: value => value.split(',').map(id => ({ id })),
                getLabel: value => {
                    if (value.length === 0) {
                        return '';
                    }
                    if (value[0].name) {
                        return value.map(v => v.name).join(', ');
                    }
                    else {
                        return lastValueFrom(this.dataService.facet
                            .getFacetValues({ filter: { id: { in: value.map(v => v.id) } } })
                            .mapSingle(({ facetValues }) => facetValues.items.map(fv => fv.name).join(', ')));
                    }
                },
            },
            label: _('catalog.facet-values'),
            toFilterInput: (value) => ({
                facetValueId: {
                    in: value.map(v => v.id),
                },
            }),
        })
            .addCustomFieldFilters(this.customFields)
            .connectToRoute(this.route);
        this.sorts = this.createSortCollection()
            .defaultSort('createdAt', 'DESC')
            .addSorts([
            { name: 'id' },
            { name: 'createdAt' },
            { name: 'updatedAt' },
            { name: 'name' },
            { name: 'slug' },
        ])
            .addCustomFieldSorts(this.customFields)
            .connectToRoute(this.route);
        this.configure({
            document: ProductListQueryDocument,
            getItems: data => data.products,
            setVariables: (skip, take) => ({
                options: {
                    skip,
                    take,
                    filter: {
                        name: {
                            contains: this.searchTermControl.value,
                        },
                        ...this.filters.createFilterInput(),
                    },
                    sort: this.sorts.createSortInput(),
                },
            }),
            refreshListOnChanges: [this.sorts.valueChanges, this.filters.valueChanges],
        });
    }
    rebuildSearchIndex() {
        this.dataService.product.reindex().subscribe(({ reindex }) => {
            this.notificationService.info(_('catalog.reindexing'));
            this.jobQueueService.addJob(reindex.id, job => {
                if (job.state === JobState.COMPLETED) {
                    const time = new Intl.NumberFormat().format(job.duration || 0);
                    this.notificationService.success(_('catalog.reindex-successful'), {
                        count: job.result.indexedItemCount,
                        time,
                    });
                    this.refresh();
                }
                else {
                    this.notificationService.error(_('catalog.reindex-error'));
                }
            });
        });
    }
    deleteProduct(productId) {
        this.modalService
            .dialog({
            title: _('catalog.confirm-delete-product'),
            buttons: [
                { type: 'secondary', label: _('common.cancel') },
                { type: 'danger', label: _('common.delete'), returnValue: true },
            ],
        })
            .pipe(switchMap(response => (response ? this.dataService.product.deleteProduct(productId) : EMPTY)), 
        // Short delay to allow the product to be removed from the search index before
        // refreshing.
        delay(500))
            .subscribe(() => {
            this.notificationService.success(_('common.notify-delete-success'), {
                entity: 'Product',
            });
            this.refresh();
        }, err => {
            this.notificationService.error(_('common.notify-delete-error'), {
                entity: 'Product',
            });
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.2", ngImport: i0, type: ProductListComponent, deps: [{ token: i1.DataService }, { token: i1.ModalService }, { token: i1.NotificationService }, { token: i1.JobQueueService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.2.2", type: ProductListComponent, selector: "vdr-products-list", usesInheritance: true, ngImport: i0, template: "<vdr-page-block>\n    <vdr-action-bar>\n        <vdr-ab-left>\n            <vdr-language-selector\n                [availableLanguageCodes]=\"availableLanguages$ | async\"\n                [currentLanguageCode]=\"contentLanguage$ | async\"\n                (languageCodeChange)=\"setLanguage($event)\"\n            ></vdr-language-selector>\n        </vdr-ab-left>\n        <vdr-ab-right>\n            <vdr-action-bar-items locationId=\"product-list\"></vdr-action-bar-items>\n            <a\n                class=\"button primary mr-1\"\n                [routerLink]=\"['./create']\"\n                *vdrIfPermissions=\"['CreateCatalog', 'CreateProduct']\"\n            >\n                <clr-icon shape=\"plus\"></clr-icon>\n                {{ 'catalog.create-new-product' | translate }}\n            </a>\n            <vdr-dropdown>\n                <button class=\"icon-button\" vdrDropdownTrigger>\n                    <clr-icon shape=\"ellipsis-vertical\"></clr-icon>\n                </button>\n                <vdr-dropdown-menu vdrPosition=\"bottom-right\">\n                    <button type=\"button\" vdrDropdownItem (click)=\"rebuildSearchIndex()\">\n                        <clr-icon shape=\"refresh\" class=\"\"></clr-icon>\n                        {{ 'catalog.rebuild-search-index' | translate }}\n                    </button>\n                </vdr-dropdown-menu>\n            </vdr-dropdown>\n        </vdr-ab-right>\n    </vdr-action-bar>\n</vdr-page-block>\n<vdr-data-table-2\n    class=\"mt-2\"\n    id=\"product-list\"\n    [items]=\"items$ | async\"\n    [itemsPerPage]=\"itemsPerPage$ | async\"\n    [totalItems]=\"totalItems$ | async\"\n    [currentPage]=\"currentPage$ | async\"\n    [filters]=\"filters\"\n    (pageChange)=\"setPageNumber($event)\"\n    (itemsPerPageChange)=\"setItemsPerPage($event)\"\n>\n    <vdr-bulk-action-menu\n        locationId=\"product-list\"\n        [hostComponent]=\"this\"\n        [selectionManager]=\"selectionManager\"\n    ></vdr-bulk-action-menu>\n    <vdr-dt2-search\n        [searchTermControl]=\"searchTermControl\"\n        [searchTermPlaceholder]=\"'catalog.filter-by-name' | translate\"\n    />\n    <vdr-dt2-column [heading]=\"'common.id' | translate\" id=\"id\" [hiddenByDefault]=\"true\" [sort]=\"sorts.get('id')\">\n        <ng-template let-product=\"item\">\n            {{ product.id }}\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column\n        [heading]=\"'common.created-at' | translate\" id=\"created-at\"\n        [hiddenByDefault]=\"true\"\n        [sort]=\"sorts.get('createdAt')\"\n    >\n        <ng-template let-product=\"item\">\n            {{ product.createdAt | localeDate : 'short' }}\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column\n        [heading]=\"'common.updated-at' | translate\" id=\"updated-at\"\n        [hiddenByDefault]=\"true\"\n        [sort]=\"sorts.get('updatedAt')\"\n    >\n        <ng-template let-product=\"item\">\n            {{ product.updatedAt | localeDate : 'short' }}\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column [heading]=\"'common.image' | translate\" id=\"image\">\n        <ng-template let-product=\"item\">\n            <div class=\"image-placeholder\">\n                <img\n                    *ngIf=\"product.featuredAsset as asset; else imagePlaceholder\"\n                    [src]=\"asset | assetPreview : 'tiny'\"\n                />\n                <ng-template #imagePlaceholder>\n                    <div class=\"placeholder\">\n                        <clr-icon shape=\"image\" size=\"48\"></clr-icon>\n                    </div>\n                </ng-template>\n            </div>\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column [heading]=\"'catalog.name' | translate\" id=\"name\" [optional]=\"false\" [sort]=\"sorts.get('name')\">\n        <ng-template let-product=\"item\">\n            <a class=\"button-ghost\" [routerLink]=\"['./', product.id]\"\n                ><span>{{ product.name }}</span\n                ><clr-icon shape=\"arrow right\"\n            /></a>\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column [heading]=\"'common.slug' | translate\" id=\"slug\" [sort]=\"sorts.get('slug')\">\n        <ng-template let-product=\"item\">\n            {{ product.slug }}\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column [heading]=\"'common.enabled' | translate\" id=\"enabled\">\n        <ng-template let-product=\"item\">\n            <vdr-chip *ngIf=\"product.enabled\" colorType=\"success\">{{\n                'common.enabled' | translate\n            }}</vdr-chip>\n            <vdr-chip *ngIf=\"!product.enabled\" colorType=\"warning\">{{\n                'common.disabled' | translate\n            }}</vdr-chip>\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column [heading]=\"'catalog.number-of-variants' | translate\" id=\"number-of-variants\">\n        <ng-template let-product=\"item\">\n            {{ 'catalog.variant-count' | translate : { count: product.variantList?.totalItems } }}\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-custom-field-column\n        *ngFor=\"let customField of customFields\"\n        [customField]=\"customField\"\n        [sorts]=\"sorts\"\n    />\n</vdr-data-table-2>\n", styles: [".image-col{width:70px}.image-placeholder{width:50px;height:50px;margin-top:calc(var(--space-unit) * -1);margin-bottom:calc(var(--space-unit) * -1);background-color:var(--color-component-bg-200)}.image-placeholder img{border-radius:var(--border-radius-img)}.image-placeholder .placeholder{text-align:center;color:var(--color-grey-300)}.search-form{display:flex;align-items:center;width:100%}vdr-product-search-input{min-width:300px}@media screen and (max-width: 768px){vdr-product-search-input{min-width:100px}}.search-settings-menu{margin:0 12px}td.disabled{background-color:var(--color-component-bg-200)}.search-index-button{position:relative}.search-index-button vdr-status-badge{right:0;top:0}.run-updates-button{position:relative}.run-updates-button vdr-status-badge{left:10px;top:10px}.edit-button{margin-inline-end:24px}.sku{color:var(--color-text-300)}\n"], dependencies: [{ kind: "directive", type: i2.ClrIconCustomTag, selector: "clr-icon" }, { kind: "directive", type: i3.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i3.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i4.RouterLink, selector: "[routerLink]", inputs: ["target", "queryParams", "fragment", "queryParamsHandling", "state", "relativeTo", "preserveFragment", "skipLocationChange", "replaceUrl", "routerLink"] }, { kind: "component", type: i1.ActionBarComponent, selector: "vdr-action-bar" }, { kind: "component", type: i1.ActionBarLeftComponent, selector: "vdr-ab-left", inputs: ["grow"] }, { kind: "component", type: i1.ActionBarRightComponent, selector: "vdr-ab-right", inputs: ["grow"] }, { kind: "component", type: i1.ChipComponent, selector: "vdr-chip", inputs: ["icon", "invert", "colorFrom", "colorType"], outputs: ["iconClick"] }, { kind: "component", type: i1.LanguageSelectorComponent, selector: "vdr-language-selector", inputs: ["currentLanguageCode", "availableLanguageCodes", "disabled"], outputs: ["languageCodeChange"] }, { kind: "component", type: i1.DropdownComponent, selector: "vdr-dropdown", inputs: ["manualToggle"] }, { kind: "component", type: i1.DropdownMenuComponent, selector: "vdr-dropdown-menu", inputs: ["vdrPosition", "customClasses"] }, { kind: "directive", type: i1.DropdownTriggerDirective, selector: "[vdrDropdownTrigger]" }, { kind: "directive", type: i1.DropdownItemDirective, selector: "[vdrDropdownItem]" }, { kind: "directive", type: i1.IfPermissionsDirective, selector: "[vdrIfPermissions]", inputs: ["vdrIfPermissions", "vdrIfPermissionsElse"] }, { kind: "component", type: i1.ActionBarItemsComponent, selector: "vdr-action-bar-items", inputs: ["locationId"] }, { kind: "component", type: i1.BulkActionMenuComponent, selector: "vdr-bulk-action-menu", inputs: ["locationId", "selectionManager", "hostComponent"] }, { kind: "component", type: i1.DataTable2Component, selector: "vdr-data-table-2", inputs: ["id", "items", "itemsPerPage", "currentPage", "totalItems", "emptyStateLabel", "filters", "activeIndex"], outputs: ["pageChange", "itemsPerPageChange"] }, { kind: "component", type: i1.DataTable2ColumnComponent, selector: "vdr-dt2-column", inputs: ["id", "expand", "heading", "align", "sort", "optional", "hiddenByDefault", "orderable"], exportAs: ["row"] }, { kind: "component", type: i1.DataTable2SearchComponent, selector: "vdr-dt2-search", inputs: ["searchTermControl", "searchTermPlaceholder"] }, { kind: "component", type: i1.DataTableCustomFieldColumnComponent, selector: "vdr-dt2-custom-field-column", inputs: ["customField", "sorts"], exportAs: ["row"] }, { kind: "component", type: i1.PageBlockComponent, selector: "vdr-page-block" }, { kind: "pipe", type: i3.AsyncPipe, name: "async" }, { kind: "pipe", type: i5.TranslatePipe, name: "translate" }, { kind: "pipe", type: i1.AssetPreviewPipe, name: "assetPreview" }, { kind: "pipe", type: i1.LocaleDatePipe, name: "localeDate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.2", ngImport: i0, type: ProductListComponent, decorators: [{
            type: Component,
            args: [{ selector: 'vdr-products-list', template: "<vdr-page-block>\n    <vdr-action-bar>\n        <vdr-ab-left>\n            <vdr-language-selector\n                [availableLanguageCodes]=\"availableLanguages$ | async\"\n                [currentLanguageCode]=\"contentLanguage$ | async\"\n                (languageCodeChange)=\"setLanguage($event)\"\n            ></vdr-language-selector>\n        </vdr-ab-left>\n        <vdr-ab-right>\n            <vdr-action-bar-items locationId=\"product-list\"></vdr-action-bar-items>\n            <a\n                class=\"button primary mr-1\"\n                [routerLink]=\"['./create']\"\n                *vdrIfPermissions=\"['CreateCatalog', 'CreateProduct']\"\n            >\n                <clr-icon shape=\"plus\"></clr-icon>\n                {{ 'catalog.create-new-product' | translate }}\n            </a>\n            <vdr-dropdown>\n                <button class=\"icon-button\" vdrDropdownTrigger>\n                    <clr-icon shape=\"ellipsis-vertical\"></clr-icon>\n                </button>\n                <vdr-dropdown-menu vdrPosition=\"bottom-right\">\n                    <button type=\"button\" vdrDropdownItem (click)=\"rebuildSearchIndex()\">\n                        <clr-icon shape=\"refresh\" class=\"\"></clr-icon>\n                        {{ 'catalog.rebuild-search-index' | translate }}\n                    </button>\n                </vdr-dropdown-menu>\n            </vdr-dropdown>\n        </vdr-ab-right>\n    </vdr-action-bar>\n</vdr-page-block>\n<vdr-data-table-2\n    class=\"mt-2\"\n    id=\"product-list\"\n    [items]=\"items$ | async\"\n    [itemsPerPage]=\"itemsPerPage$ | async\"\n    [totalItems]=\"totalItems$ | async\"\n    [currentPage]=\"currentPage$ | async\"\n    [filters]=\"filters\"\n    (pageChange)=\"setPageNumber($event)\"\n    (itemsPerPageChange)=\"setItemsPerPage($event)\"\n>\n    <vdr-bulk-action-menu\n        locationId=\"product-list\"\n        [hostComponent]=\"this\"\n        [selectionManager]=\"selectionManager\"\n    ></vdr-bulk-action-menu>\n    <vdr-dt2-search\n        [searchTermControl]=\"searchTermControl\"\n        [searchTermPlaceholder]=\"'catalog.filter-by-name' | translate\"\n    />\n    <vdr-dt2-column [heading]=\"'common.id' | translate\" id=\"id\" [hiddenByDefault]=\"true\" [sort]=\"sorts.get('id')\">\n        <ng-template let-product=\"item\">\n            {{ product.id }}\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column\n        [heading]=\"'common.created-at' | translate\" id=\"created-at\"\n        [hiddenByDefault]=\"true\"\n        [sort]=\"sorts.get('createdAt')\"\n    >\n        <ng-template let-product=\"item\">\n            {{ product.createdAt | localeDate : 'short' }}\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column\n        [heading]=\"'common.updated-at' | translate\" id=\"updated-at\"\n        [hiddenByDefault]=\"true\"\n        [sort]=\"sorts.get('updatedAt')\"\n    >\n        <ng-template let-product=\"item\">\n            {{ product.updatedAt | localeDate : 'short' }}\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column [heading]=\"'common.image' | translate\" id=\"image\">\n        <ng-template let-product=\"item\">\n            <div class=\"image-placeholder\">\n                <img\n                    *ngIf=\"product.featuredAsset as asset; else imagePlaceholder\"\n                    [src]=\"asset | assetPreview : 'tiny'\"\n                />\n                <ng-template #imagePlaceholder>\n                    <div class=\"placeholder\">\n                        <clr-icon shape=\"image\" size=\"48\"></clr-icon>\n                    </div>\n                </ng-template>\n            </div>\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column [heading]=\"'catalog.name' | translate\" id=\"name\" [optional]=\"false\" [sort]=\"sorts.get('name')\">\n        <ng-template let-product=\"item\">\n            <a class=\"button-ghost\" [routerLink]=\"['./', product.id]\"\n                ><span>{{ product.name }}</span\n                ><clr-icon shape=\"arrow right\"\n            /></a>\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column [heading]=\"'common.slug' | translate\" id=\"slug\" [sort]=\"sorts.get('slug')\">\n        <ng-template let-product=\"item\">\n            {{ product.slug }}\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column [heading]=\"'common.enabled' | translate\" id=\"enabled\">\n        <ng-template let-product=\"item\">\n            <vdr-chip *ngIf=\"product.enabled\" colorType=\"success\">{{\n                'common.enabled' | translate\n            }}</vdr-chip>\n            <vdr-chip *ngIf=\"!product.enabled\" colorType=\"warning\">{{\n                'common.disabled' | translate\n            }}</vdr-chip>\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-column [heading]=\"'catalog.number-of-variants' | translate\" id=\"number-of-variants\">\n        <ng-template let-product=\"item\">\n            {{ 'catalog.variant-count' | translate : { count: product.variantList?.totalItems } }}\n        </ng-template>\n    </vdr-dt2-column>\n    <vdr-dt2-custom-field-column\n        *ngFor=\"let customField of customFields\"\n        [customField]=\"customField\"\n        [sorts]=\"sorts\"\n    />\n</vdr-data-table-2>\n", styles: [".image-col{width:70px}.image-placeholder{width:50px;height:50px;margin-top:calc(var(--space-unit) * -1);margin-bottom:calc(var(--space-unit) * -1);background-color:var(--color-component-bg-200)}.image-placeholder img{border-radius:var(--border-radius-img)}.image-placeholder .placeholder{text-align:center;color:var(--color-grey-300)}.search-form{display:flex;align-items:center;width:100%}vdr-product-search-input{min-width:300px}@media screen and (max-width: 768px){vdr-product-search-input{min-width:100px}}.search-settings-menu{margin:0 12px}td.disabled{background-color:var(--color-component-bg-200)}.search-index-button{position:relative}.search-index-button vdr-status-badge{right:0;top:0}.run-updates-button{position:relative}.run-updates-button vdr-status-badge{left:10px;top:10px}.edit-button{margin-inline-end:24px}.sku{color:var(--color-text-300)}\n"] }]
        }], ctorParameters: function () { return [{ type: i1.DataService }, { type: i1.ModalService }, { type: i1.NotificationService }, { type: i1.JobQueueService }]; } });
//# sourceMappingURL=data:application/json;base64, 