import * as i1 from '@acorex/components/button';
import { AXButtonModule } from '@acorex/components/button';
import { AXDataSource } from '@acorex/cdk/common';
import * as i1$2 from '@acorex/components/data-table';
import { AXDataTableModule } from '@acorex/components/data-table';
import * as i2 from '@acorex/components/decorators';
import { AXDecoratorModule } from '@acorex/components/decorators';
import * as i3 from '@acorex/components/form';
import { AXFormModule } from '@acorex/components/form';
import { AXBasePageComponent } from '@acorex/components/page';
import * as i5 from '@acorex/core/translation';
import { AXTranslationModule } from '@acorex/core/translation';
import { AXPDataGenerator } from '@acorex/platform/core';
import * as i1$1 from '@acorex/platform/layout/widget-core';
import { AXPWidgetCoreModule } from '@acorex/platform/layout/widget-core';
import * as i1$3 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i0 from '@angular/core';
import { viewChild, ChangeDetectionStrategy, Component } from '@angular/core';
import { cloneDeep } from 'lodash-es';

class AXPTabularDataPopupComponent extends AXBasePageComponent {
    constructor() {
        super(...arguments);
        this.disabled = false;
        this.defaultRowCount = 0;
        this.getCommandRowItems = [
            {
                name: 'delete',
                text: "@general:actions.delete.title",
                icon: 'fa-light fa-trash ax-text-danger',
                //divided: boolean,
                //disabled: boolean,
                color: 'danger',
            },
        ];
        this.dataSource = new AXDataSource({
            load: async () => {
                this.context = (this.context ?? []).map((x) => {
                    return {
                        ...x,
                        id: AXPDataGenerator.uuid(),
                        options: {},
                    };
                });
                const items = this.context;
                console.log(this.context);
                return {
                    items: items ?? [],
                    total: (items ?? []).length,
                };
            },
            pageSize: 1,
            key: 'gridItem',
        });
        this.grid = viewChild('grid', ...(ngDevMode ? [{ debugName: "grid" }] : []));
    }
    ngOnInit() {
        this.columns = this.columns.filter((col) => col.name != null && col.name != '' && col.type != null);
        this.columns = this.columns.map((col) => {
            return {
                ...col,
                options: {
                    ...(col.options ?? {}),
                    validationRules: [
                        {
                            rule: 'required',
                        },
                    ],
                },
            };
        });
        this.contextDiscard = cloneDeep(this.context);
        if (this.context == null || this.context?.length == 0) {
            for (let i = 0; i < this.defaultRowCount; i++) {
                this.addRecord();
            }
        }
    }
    handleContextChange(e) {
        this.context = e.data;
    }
    onCloseDiscard() {
        this.close({
            context: this.contextDiscard,
        });
    }
    addRecord() {
        console.log(this.columns);
        const value = this.context ?? [];
        const newRecord = this.columns?.reduce((acc, column) => {
            acc[column.name] = ''; // or any default value
            return acc;
        }, {});
        console.log(value);
        this.context = [...value, newRecord];
        this.grid()?.refresh();
    }
    handleSelectionChange(e) {
        console.log(e);
    }
    async handleRowCommandClick(e) {
        if (e.name == 'delete') {
            this.context = this.context.filter((item) => item.id !== e.data.id);
            this.grid()?.refresh();
        }
    }
    async handleSaveClick(form) {
        const formResult = await form.validate();
        console.log(formResult.rules);
        if (formResult.result) {
            this.close({
                context: this.context,
            });
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.16", ngImport: i0, type: AXPTabularDataPopupComponent, deps: null, target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.16", type: AXPTabularDataPopupComponent, isStandalone: true, selector: "ng-component", viewQueries: [{ propertyName: "grid", first: true, predicate: ["grid"], descendants: true, isSignal: true }], usesInheritance: true, ngImport: i0, template: `
    <axp-widgets-container [context]="context" (onContextChanged)="handleContextChange($event)">
      <ax-form #form>
        <div class="ax-p-4">
          <ax-data-table
            #grid
            [paging]="false"
            [allowReordering]="true"
            (selectedRowsChange)="handleSelectionChange($event)"
            [dataSource]="dataSource"
            class="ax-h-96 ax-overflow-auto"
          >
            @for (column of columns; track $index) {
              <ax-text-column
                width="200px"
                [caption]="column.title"
                [dataField]="column.name"
                [cellTemplate]="cell"
                [allowResizing]="true"
              ></ax-text-column>
              <ng-template #cell let-item>
                <ng-container
                  axp-widget-renderer
                  [node]="{
                    path: item.rowIndex + '.' + column.name,
                    type: column.type,
                    options: column.options ?? {},
                  }"
                  [mode]="'edit'"
                >
                </ng-container>
              </ng-template>
            }
            <ax-command-column
              fixed="end"
              [width]="getCommandRowItems.length * 60 + 'px'"
              [items]="getCommandRowItems"
              (onItemClick)="handleRowCommandClick($event)"
            ></ax-command-column>
          </ax-data-table>
          @if (!disabled) {
            <div class="ax-flex ax-justify-end ax-py-4">
              <ax-button
                [text]="(this.context ?? []).length ? 'Start Adding Items' : 'Add Your First Item'"
                look="twotone"
                [disabled]="disabled"
                (onClick)="addRecord()"
                class="ax-col-start-10  ax-col-end-13"
              >
                <ax-prefix>
                  <ax-icon class="fa-solid fa-add"></ax-icon>
                </ax-prefix>
              </ax-button>
            </div>
          }
        </div>
        <ax-footer>
          <ax-suffix>
            <ax-button [text]="'@general:actions.discard.title' | translate | async" (onClick)="onCloseDiscard()"></ax-button>
            <ax-button
              color="primary"
              [text]="'@general:actions.ok.title' | translate | async"
              (onClick)="handleSaveClick(form)"
            ></ax-button>
          </ax-suffix>
        </ax-footer>
      </ax-form>
    </axp-widgets-container>
  `, isInline: true, dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "ngmodule", type: AXDecoratorModule }, { kind: "component", type: i2.AXDecoratorIconComponent, selector: "ax-icon", inputs: ["icon"] }, { kind: "component", type: i2.AXDecoratorGenericComponent, selector: "ax-footer, ax-header, ax-content, ax-divider, ax-form-hint, ax-prefix, ax-suffix, ax-text, ax-title, ax-subtitle, ax-placeholder, ax-overlay" }, { kind: "ngmodule", type: AXButtonModule }, { kind: "component", type: i1.AXButtonComponent, selector: "ax-button", inputs: ["disabled", "size", "tabIndex", "color", "look", "text", "toggleable", "selected", "iconOnly", "type", "loadingText"], outputs: ["onBlur", "onFocus", "onClick", "selectedChange", "toggleableChange", "lookChange", "colorChange", "disabledChange", "loadingTextChange"] }, { kind: "ngmodule", type: AXPWidgetCoreModule }, { kind: "component", type: i1$1.AXPWidgetContainerComponent, selector: "axp-widgets-container", inputs: ["context", "functions"], outputs: ["onContextChanged"] }, { kind: "directive", type: i1$1.AXPWidgetRendererDirective, selector: "[axp-widget-renderer]", inputs: ["parentNode", "index", "mode", "node"], outputs: ["onOptionsChanged", "onValueChanged", "onLoad"], exportAs: ["widgetRenderer"] }, { kind: "ngmodule", type: AXDataTableModule }, { kind: "component", type: i1$2.AXDataTableComponent, selector: "ax-data-table", inputs: ["dataSource", "selectedRows", "parentField", "rowDetailsTemplate", "rowTemplate", "emptyTemplate", "noDataTemplate", "alternative", "showHeader", "fixedHeader", "showFooter", "fixedFooter", "itemHeight", "allowReordering", "paging", "fetchDataMode", "loading", "focusedRow"], outputs: ["selectedRowsChange", "focusedRowChange", "onRowClick", "onRowDbClick", "onColumnsOrderChanged", "onColumnSizeChanged", "onPageChanged"] }, { kind: "component", type: i1$2.AXDataTableTextColumnComponent, selector: "ax-text-column", inputs: ["width", "caption", "allowSorting", "allowResizing", "fixed", "customExpandIcon", "customCollapseIcon", "dataField", "expandHandler", "wrapText", "cellTemplate", "footerTemplate", "headerTemplate", "format", "formatOptions"] }, { kind: "component", type: i1$2.AXRowCommandColumnComponent, selector: "ax-command-column", inputs: ["width", "caption", "fixed", "footerTemplate", "items"], outputs: ["onItemClick"] }, { kind: "ngmodule", type: AXTranslationModule }, { kind: "ngmodule", type: AXFormModule }, { kind: "component", type: i3.AXFormComponent, selector: "ax-form", inputs: ["disabled", "readonly", "labelMode", "look", "messageStyle", "updateOn", "inUserInteractionActive"], outputs: ["onValidate", "updateOnChange"] }, { kind: "pipe", type: i1$3.AsyncPipe, name: "async" }, { kind: "pipe", type: i5.AXTranslatorPipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.16", ngImport: i0, type: AXPTabularDataPopupComponent, decorators: [{
            type: Component,
            args: [{
                    changeDetection: ChangeDetectionStrategy.OnPush,
                    template: `
    <axp-widgets-container [context]="context" (onContextChanged)="handleContextChange($event)">
      <ax-form #form>
        <div class="ax-p-4">
          <ax-data-table
            #grid
            [paging]="false"
            [allowReordering]="true"
            (selectedRowsChange)="handleSelectionChange($event)"
            [dataSource]="dataSource"
            class="ax-h-96 ax-overflow-auto"
          >
            @for (column of columns; track $index) {
              <ax-text-column
                width="200px"
                [caption]="column.title"
                [dataField]="column.name"
                [cellTemplate]="cell"
                [allowResizing]="true"
              ></ax-text-column>
              <ng-template #cell let-item>
                <ng-container
                  axp-widget-renderer
                  [node]="{
                    path: item.rowIndex + '.' + column.name,
                    type: column.type,
                    options: column.options ?? {},
                  }"
                  [mode]="'edit'"
                >
                </ng-container>
              </ng-template>
            }
            <ax-command-column
              fixed="end"
              [width]="getCommandRowItems.length * 60 + 'px'"
              [items]="getCommandRowItems"
              (onItemClick)="handleRowCommandClick($event)"
            ></ax-command-column>
          </ax-data-table>
          @if (!disabled) {
            <div class="ax-flex ax-justify-end ax-py-4">
              <ax-button
                [text]="(this.context ?? []).length ? 'Start Adding Items' : 'Add Your First Item'"
                look="twotone"
                [disabled]="disabled"
                (onClick)="addRecord()"
                class="ax-col-start-10  ax-col-end-13"
              >
                <ax-prefix>
                  <ax-icon class="fa-solid fa-add"></ax-icon>
                </ax-prefix>
              </ax-button>
            </div>
          }
        </div>
        <ax-footer>
          <ax-suffix>
            <ax-button [text]="'@general:actions.discard.title' | translate | async" (onClick)="onCloseDiscard()"></ax-button>
            <ax-button
              color="primary"
              [text]="'@general:actions.ok.title' | translate | async"
              (onClick)="handleSaveClick(form)"
            ></ax-button>
          </ax-suffix>
        </ax-footer>
      </ax-form>
    </axp-widgets-container>
  `,
                    imports: [
                        CommonModule,
                        AXDecoratorModule,
                        AXButtonModule,
                        AXPWidgetCoreModule,
                        AXDataTableModule,
                        AXTranslationModule,
                        AXFormModule,
                    ],
                }]
        }], propDecorators: { grid: [{ type: i0.ViewChild, args: ['grid', { isSignal: true }] }] } });

export { AXPTabularDataPopupComponent };
//# sourceMappingURL=acorex-platform-layout-widgets-tabular-data-edit-popup.component-BJh1QJqp.mjs.map
