import { r as registerInstance, e as createEvent, h, f as Host, g as getElement } from './index-04f73a26.js';
import { Action, DataUnitAction, StringUtils, ElementIDUtils, ApplicationContext, KeyboardManager } from '@sankhyalabs/core';
import { buildFieldSearch } from '@sankhyalabs/ezui/dist/collection/utils';
import './DataFetcher-5ed0a377.js';
import './ISave-5b46d691.js';
import { P as PresentationMode, E as ExporterStrategy } from './index-b40568ff.js';
import '@sankhyalabs/ezui/dist/collection/utils/constants';
import '@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata';
import './dataunit-fetcher-3b1ca96e.js';
import './filter-item-type.enum-d45e026f.js';
import './form-config-fetcher-1c81efc4.js';
import { V as VIEW_MODE } from './constants-7b422de0.js';
import { A as AutorizationType } from './auth-fetcher-9fd198d2.js';
import { C as ContinuousInsertUtils } from './ContinuousInsertUtils-bce77dc1.js';
import { S as SimpleTaskbarProcessor, D as DEFAULT_TASKBAR_BUTTONS, C as CustomTaskbarButton, b as buildNativeTaskbarManager, g as getTopTaskBarId, a as getHeaderTaskbarId } from './taskbarUtils-6652208b.js';
import { v as validateFilters } from './filter-validate-faf51fa9.js';
import { S as ServicesNumberingConfig } from './ServicesNumberingConfig-2f7b050e.js';
import { T as TaskbarElement } from './taskbar-elements-63651ca7.js';
import './PrintUtils-3e4ff0f5.js';
import '@sankhyalabs/ezui/dist/collection/components/ez-grid/utils';
import '@sankhyalabs/core/dist/utils/SortingUtils';
import './ResourceIDUtils-a114189a.js';
import './index-ea250be6.js';

const snkDynaformCss = ".sc-snk-dynaform-h{display:flex;flex-direction:column;height:100%;width:100%;overflow:hidden;scrollbar-gutter:stable both-edges}snk-grid.sc-snk-dynaform{--snk-grid-padding:0 var(--space--6, 6px) var(--space--6, 6px) var(--space--6, 6px)}ez-view-stack.sc-snk-dynaform{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden}stack-item.sc-snk-dynaform.sc-snk-dynaform{display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden}stack-item.sc-snk-dynaform.sc-snk-dynaform>snk-dynaform-guides-view.sc-snk-dynaform{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden}.snk-crud__header.sc-snk-dynaform{margin-bottom:var(--space--10, 10px)}.snk-crud__grid-stack-item.sc-snk-dynaform{display:flex;flex-direction:column;height:100%;width:100%;padding:0 var(--space--2, 2px)}.snk-crud__header-top.sc-snk-dynaform{display:flex;justify-content:space-between;align-items:center;padding:var(--space--8, 8px);padding-top:var(--space--12, 12px)}.snk-crud--hidden.sc-snk-dynaform{display:none !important}ez-record-navigation.sc-snk-dynaform,ez-grid-pagination.sc-snk-dynaform{margin-bottom:var(--space--8, 8px)}";

const SnkDynaform = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.snkShowGuide = createEvent(this, "snkShowGuide", 7);
    this.actionClick = createEvent(this, "actionClick", 7);
    this.configuratorSave = createEvent(this, "configuratorSave", 7);
    this.configuratorCancel = createEvent(this, "configuratorCancel", 7);
    this.formItemsReady = createEvent(this, "formItemsReady", 7);
    this.viewModeChanged = createEvent(this, "viewModeChanged", 7);
    this.numberingConfigChanged = createEvent(this, "numberingConfigChanged", 7);
    this._viewHistory = [];
    this._customEditors = new Map();
    this._customRenders = new Map();
    this._taskbarProcessor = new SimpleTaskbarProcessor(DEFAULT_TASKBAR_BUTTONS);
    this._taskbarCustomProcessor = new SimpleTaskbarProcessor([]);
    this.dataUnitInterceptor = {
      interceptAction: async (action) => {
        var _a;
        switch (action.type) {
          case Action.DATA_SAVED:
            return this.interceptDataSaved(action);
          case Action.LOADING_DATA:
            return (_a = await this.interceptLoadData(action)) !== null && _a !== void 0 ? _a : new DataUnitAction(Action.INVALIDATE_CLEAN);
          default:
            return action;
        }
      },
    };
    this._dataUnit = undefined;
    this._dataState = undefined;
    this.attachmentRegisterKey = undefined;
    this._currentViewMode = VIEW_MODE.GRID;
    this._canEdit = undefined;
    this._resourceID = undefined;
    this.customContainerId = `SNK-CRUD-CUSTOM-CONTAINER-${StringUtils.generateUUID()}`;
    this.numberingConfig = undefined;
    this._filterMode = 'regular';
    this._enableContinuousInsert = false;
    this._headerVisible = true;
    this.enableLockManagerLoadingComp = false;
    this.enableLockManagerTaskbarClick = false;
    this.configName = undefined;
    this.filterBarTitle = undefined;
    this.selectionToastConfig = undefined;
    this.showActionButtons = false;
    this.actionsList = undefined;
    this.taskbarManager = undefined;
    this.recordsValidator = undefined;
    this.statusResolver = undefined;
    this.multipleSelection = true;
    this.presentationMode = PresentationMode.PRIMARY;
    this.messagesBuilder = undefined;
    this.useEnterLikeTab = false;
    this.gridLegacyConfigName = undefined;
    this.filterBarLegacyConfigName = undefined;
    this.formLegacyConfigName = undefined;
    this.disablePersonalizedFilter = undefined;
    this.autoLoad = undefined;
    this.autoFocus = true;
    this.enableGridInsert = false;
    this.domainMessagesBuilder = undefined;
    this.ignoreReadOnlyFormFields = undefined;
    this.setCustomFormTitle = undefined;
    this.strategyExporter = ExporterStrategy.SERVER_SIDE;
    this.layoutFormConfig = true;
    this.multipleEditionEnabled = true;
    this.paginationCounterMode = 'auto';
    this.customGuidesConfig = [];
    this.showEntitySearch = true;
    this.disableNumberingConfig = false;
  }
  handleActionClick(evt) {
    this.executeAction(evt.detail);
  }
  /**
   * Usado para alternar a visão entre GRID e FORM externamente.
   */
  async goToView(mode) {
    this.executeAction(mode);
  }
  /**
   * Usado para abrir o configurator do CRUD
   */
  async openConfigurator() {
    var _a;
    (_a = this._snkConfigurator) === null || _a === void 0 ? void 0 : _a.open();
  }
  /**
   * Usado para fechar o configurator do CRUD
   */
  async closeConfigurator() {
    var _a;
    (_a = this._snkConfigurator) === null || _a === void 0 ? void 0 : _a.close();
  }
  /**
   * Faz o recarregamento da filter-bar do crud, buscando o state no servidor.
   */
  async reloadFilterBar() {
    var _a;
    (_a = this._snkGrid) === null || _a === void 0 ? void 0 : _a.reloadFilterBar();
  }
  /**
   * Retorna o elemento da filter-bar da grade.
   */
  async getFilterBar() {
    var _a;
    return await ((_a = this._snkGrid) === null || _a === void 0 ? void 0 : _a.getFilterBar());
  }
  /**
   * Registra um editor customizado para campos da grade e formulário.
   */
  async addCustomEditor(fieldName, customEditor) {
    if (this._guidesViewer && this._snkGrid) {
      this._guidesViewer.addCustomEditor(fieldName, customEditor);
      this._snkGrid.addCustomEditor(fieldName, customEditor);
      return;
    }
    const newCustomEditors = new Map(this._customEditors);
    newCustomEditors.set(fieldName, customEditor);
    this._customEditors = newCustomEditors;
  }
  /**
   * Registra um render customizado para colunas da grid.
   */
  async addGridCustomRender(fieldName, customRender) {
    if (this._snkGrid) {
      this._snkGrid.addGridCustomRender(fieldName, customRender);
      return;
    }
    const newCustomRenders = new Map(this._customRenders);
    newCustomRenders.set(fieldName, customRender);
    this._customRenders = newCustomRenders;
  }
  /**
   * Registra um formatador de valores para uma coluna da grid.
   */
  async addCustomValueFormatter(columnName, customFormatter) {
    var _a;
    (_a = this._snkGrid) === null || _a === void 0 ? void 0 : _a.addCustomValueFormatter(columnName, customFormatter);
  }
  /**
   * Remove o formatador de valores de uma coluna da grid.
   */
  async removeCustomValueFormatter(columnName) {
    var _a;
    (_a = this._snkGrid) === null || _a === void 0 ? void 0 : _a.removeCustomValueFormatter(columnName);
  }
  /**
   * Altera/adiciona uma propriedade nos metadados do campo.
   */
  async setFieldProp(fieldName, propName, value) {
    var _a;
    await ((_a = this._guidesViewer) === null || _a === void 0 ? void 0 : _a.setFieldProp(fieldName, propName, value));
  }
  /**
   * Retorna a configuração de numeração atual.
   */
  async getNumberingConfig() {
    return this.numberingConfig;
  }
  /**
   * Atualiza a configuração de numeração.
   */
  async updateNumberingConfig(config) {
    this.numberingConfig = config;
    this.applyNumberingConfigToFields();
  }
  currentViewModeWatcher(currentView) {
    this._viewHistory = [...this._viewHistory.slice(-1), currentView];
  }
  async gridToForm(keepFormMode = false) {
    var _a;
    this._backToGrid = !keepFormMode && await ((_a = this._viewStack) === null || _a === void 0 ? void 0 : _a.getSelectedIndex()) === VIEW_MODE.GRID;
    this.setViewMode(VIEW_MODE.FORM);
  }
  async executeAction(act) {
    var _a, _b, _c;
    switch (act) {
      case TaskbarElement.GRID_MODE:
        return this.setViewMode(VIEW_MODE.GRID);
      case TaskbarElement.FORM_MODE:
      case TaskbarElement.UPDATE:
        return this.gridToForm(act !== TaskbarElement.UPDATE);
      case TaskbarElement.UPDATE_MULTIPLE:
        if (this._dataUnit) {
          this._dataUnit.isMultipleEdition = true;
        }
        return this.setViewMode(VIEW_MODE.FORM);
      case TaskbarElement.CONFIGURATOR:
        return (_a = this._snkConfigurator) === null || _a === void 0 ? void 0 : _a.open();
      case TaskbarElement.ATTACH:
        return (_b = this._snkAttach) === null || _b === void 0 ? void 0 : _b.open();
      case CustomTaskbarButton.FILTER:
        return (_c = this._snkFilterBar) === null || _c === void 0 ? void 0 : _c.showFilterModal();
      case CustomTaskbarButton.ENTITY_SEARCH:
        return this.openSearchPopover();
    }
  }
  setViewMode(viewMode) {
    var _a, _b, _c, _d, _e;
    (_a = this._viewStack) === null || _a === void 0 ? void 0 : _a.show(viewMode);
    this._currentViewMode = viewMode;
    if (viewMode === VIEW_MODE.GRID) {
      if (this._dataUnit) {
        this._dataUnit.isMultipleEdition = false;
      }
      (_b = this._snkGrid) === null || _b === void 0 ? void 0 : _b.setFocus();
    }
    else if (viewMode === VIEW_MODE.FORM) {
      (_d = (_c = this._guidesViewer) === null || _c === void 0 ? void 0 : _c.setFocus) === null || _d === void 0 ? void 0 : _d.call(_c);
    }
    (_e = this.viewModeChanged) === null || _e === void 0 ? void 0 : _e.emit(viewMode);
  }
  openConfig(viewMode) {
    var _a, _b, _c, _d, _e, _f;
    (_b = (_a = this._snkConfigurator) === null || _a === void 0 ? void 0 : _a.close) === null || _b === void 0 ? void 0 : _b.call(_a);
    if (viewMode === VIEW_MODE.GRID) {
      (_d = (_c = this._snkGrid).showConfig) === null || _d === void 0 ? void 0 : _d.call(_c);
    }
    else if (viewMode === VIEW_MODE.FORM) {
      (_f = (_e = this._guidesViewer).showFormConfig) === null || _f === void 0 ? void 0 : _f.call(_e);
    }
  }
  addDataElementID() {
    const dataInfo = { dataUnit: this._dataUnit };
    if (this._element) {
      ElementIDUtils.addIDInfo(this._element, undefined, dataInfo);
    }
  }
  insertionModeHandler() {
    if (this.enableGridInsert)
      return;
    this.gridToForm();
  }
  cancelHandler() {
    if (this._backToGrid) {
      this.setViewMode(VIEW_MODE.GRID);
    }
  }
  async getAttachmentRegisterKey() {
    if (!this._snkDataUnit) {
      return;
    }
    const recordCriteria = await this._snkDataUnit.getSelectedRecordsIDsInfo();
    const joinedPrimaryKeys = recordCriteria.map(({ value }) => value).join('_');
    return joinedPrimaryKeys;
  }
  setCustomRenders() {
    if (!this._snkGrid) {
      return;
    }
    for (const [fieldName, customRender] of this._customRenders) {
      this._snkGrid.addGridCustomRender(fieldName, customRender);
      this._customRenders.delete(fieldName);
    }
  }
  setCustomEditors() {
    if (!this._snkGrid || !this._guidesViewer) {
      return;
    }
    for (const [fieldName, customEditor] of this._customEditors) {
      this._guidesViewer.addCustomEditor(fieldName, customEditor);
      this._snkGrid.addCustomEditor(fieldName, customEditor);
      this._customEditors.delete(fieldName);
    }
  }
  initializeTaskbarProcessor() {
    if (!this._dataState) {
      return;
    }
    const nativeTaskbarManager = buildNativeTaskbarManager(this._currentViewMode, this.taskbarManager, this.messagesBuilder);
    const topTaskbarId = getTopTaskBarId(this._dataState, this.presentationMode);
    this._taskbarProcessor.process(topTaskbarId, nativeTaskbarManager, this._dataState, undefined, []);
    const headerTaskbarId = getHeaderTaskbarId(this._dataState, this.presentationMode);
    this._taskbarCustomProcessor.process(headerTaskbarId, this.taskbarManager, this._dataState, undefined, []);
  }
  componentWillRender() {
    this.initializeTaskbarProcessor();
  }
  componentDidRender() {
    this.setCustomRenders();
    this.setCustomEditors();
  }
  componentWillLoad() {
    var _a, _b, _c, _d, _e;
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    let parent = (_a = this._element) === null || _a === void 0 ? void 0 : _a.parentElement;
    (_b = this._application) === null || _b === void 0 ? void 0 : _b.hasAccess(AutorizationType.UPDATE, this._resourceID).then(canEdit => this._canEdit = canEdit);
    while (parent) {
      if (parent.tagName.toUpperCase() === "SNK-DATA-UNIT") {
        this._snkDataUnit = parent;
        this._snkDataUnit.addEventListener("insertionMode", () => this.insertionModeHandler());
        this._snkDataUnit.addEventListener("cancelEdition", () => this.cancelHandler());
        if (this._snkDataUnit && this.domainMessagesBuilder) {
          this._snkDataUnit.domainMessagesBuilder = this.domainMessagesBuilder;
        }
        this._dataUnit = this._snkDataUnit.dataUnit;
        this._dataState = this._snkDataUnit.dataState;
        if (!this._dataUnit) {
          (_c = this._snkDataUnit) === null || _c === void 0 ? void 0 : _c.addEventListener("dataUnitReady", ((evt) => {
            this._dataUnit = evt.detail;
            this.initDataUnit();
          }));
        }
        else {
          this.initDataUnit();
        }
        (_d = this._snkDataUnit) === null || _d === void 0 ? void 0 : _d.addEventListener("dataStateChange", ((evt) => this.handleDataStateChange(evt)));
        break;
      }
      parent = parent.parentElement;
    }
    if (!this.configName) {
      this.configName = (_e = this._application) === null || _e === void 0 ? void 0 : _e.configName;
    }
    this.initContinuousInsertUtils();
  }
  componentDidLoad() {
    this.initKeyboardManager();
  }
  disconnectedCallback() {
    var _a;
    this.removeShortcuts();
    (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.removeInterceptor(this.dataUnitInterceptor);
  }
  async handleDataStateChange(evt) {
    var _a, _b, _c;
    this._dataState = evt.detail;
    if (this._dataState.selectedRecord !== undefined) {
      this.attachmentRegisterKey = (_a = await this.getAttachmentRegisterKey()) !== null && _a !== void 0 ? _a : undefined;
    }
    const fieldsWithRmPrecision = await ((_b = this._snkDataUnit) === null || _b === void 0 ? void 0 : _b.getFieldsWithRmPrecision());
    for (const field of fieldsWithRmPrecision || []) {
      if (!field) {
        continue;
      }
      const rmPrecision = (_c = this._dataState.rowMetadata) === null || _c === void 0 ? void 0 : _c.getProp('rm_precision', field);
      if (!rmPrecision && rmPrecision !== 0) {
        continue;
      }
      await this.setFieldProp(field, 'precision', rmPrecision);
      await this.setFieldProp(field, 'prettyPrecision', rmPrecision);
    }
  }
  async initKeyboardManager() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    this._keyboardManager = new KeyboardManager({ propagate: false, element: this._element });
    const dataUnit = this._dataUnit || await ((_a = this._snkDataUnit) === null || _a === void 0 ? void 0 : _a.getDataUnit());
    async function saveDataUnitHandlingFocus() {
      const element = document.activeElement;
      const isDocumentBody = (element == document.body);
      if (!isDocumentBody)
        element.blur();
      await (dataUnit === null || dataUnit === void 0 ? void 0 : dataUnit.saveData());
      if (!isDocumentBody && element.setFocus != undefined) {
        element.setFocus();
        return;
      }
      if (!isDocumentBody)
        element.focus();
    }
    async function handleAddRecord() {
      if (!(dataUnit === null || dataUnit === void 0 ? void 0 : dataUnit.hasNewRecord())) {
        dataUnit === null || dataUnit === void 0 ? void 0 : dataUnit.addRecord();
      }
    }
    if (this._keyboardManager) {
      this._keyboardManager
        .bind("F6", this.toggleView.bind(this), { description: (_b = this.getMessage("snkCrud.shortcuts.toggleView")) !== null && _b !== void 0 ? _b : "", element: this._element })
        .bind("F7", saveDataUnitHandlingFocus.bind(this), { description: (_c = this.getMessage("snkCrud.shortcuts.saveData")) !== null && _c !== void 0 ? _c : "", element: this._element })
        .bind("ctrl + \\", saveDataUnitHandlingFocus.bind(this), { description: (_d = this.getMessage("snkCrud.shortcuts.addRecord")) !== null && _d !== void 0 ? _d : "", element: this._element })
        .bind("F8", handleAddRecord.bind(this), { description: (_e = this.getMessage("snkCrud.shortcuts.addRecord")) !== null && _e !== void 0 ? _e : "", element: this._element })
        .bind("F9", dataUnit ? (_f = dataUnit.removeSelectedRecords) === null || _f === void 0 ? void 0 : _f.bind(dataUnit) : () => { }, { description: (_g = this.getMessage("snkCrud.shortcuts.removeRecord")) !== null && _g !== void 0 ? _g : "", element: this._element })
        .bind("ctrl + F9", dataUnit ? dataUnit.removeSelectedRecords.bind(dataUnit) : () => { }, { description: (_h = this.getMessage("snkCrud.shortcuts.removeRecord")) !== null && _h !== void 0 ? _h : "", element: this._element })
        .bind("F5", async () => {
        var _a;
        const currentView = await ((_a = this._viewStack) === null || _a === void 0 ? void 0 : _a.getSelectedIndex());
        if (VIEW_MODE.GRID === currentView) {
          dataUnit === null || dataUnit === void 0 ? void 0 : dataUnit.loadData();
        }
      }, { description: (_j = this.getMessage("snkCrud.shortcuts.refreshData")) !== null && _j !== void 0 ? _j : "", element: this._element })
        .bind("Escape", () => {
        if (dataUnit === null || dataUnit === void 0 ? void 0 : dataUnit.isDirty()) {
          dataUnit === null || dataUnit === void 0 ? void 0 : dataUnit.cancelEdition();
        }
      }, {
        debounceTime: 1000,
        description: (_k = this.getMessage("snkCrud.shortcuts.cancelAction")) !== null && _k !== void 0 ? _k : "", element: this._element
      });
    }
  }
  getMessage(key, params) {
    if (this.messagesBuilder)
      return this.messagesBuilder.getMessage(key, params);
    return undefined;
  }
  async removeShortcuts() {
    var _a;
    (_a = this._keyboardManager) === null || _a === void 0 ? void 0 : _a.unbindAllShortcutKeys();
  }
  async toggleView() {
    var _a;
    const currentView = await ((_a = this._viewStack) === null || _a === void 0 ? void 0 : _a.getSelectedIndex());
    this.setViewMode(VIEW_MODE.GRID === currentView ? VIEW_MODE.FORM : VIEW_MODE.GRID);
  }
  getLastRecordSaved(action) {
    var _a;
    if ((_a = action.payload) === null || _a === void 0 ? void 0 : _a.records.length) {
      return action.payload.records[action.payload.records.length - 1];
    }
    return null;
  }
  async saveNumberingConfig() {
    if (!this._snkDataUnit || !this.numberingConfig || !this._servicesNumberingConfig) {
      return;
    }
    const payload = {
      entityName: this._snkDataUnit.entityName,
      isAutoNum: this.numberingConfig.isAutoNumbering,
      numInicial: this.numberingConfig.initialNumber
    };
    await this._servicesNumberingConfig.saveConfig(payload);
  }
  updateNumberingConfigAfterInsert(action) {
    var _a, _b, _c;
    if (!((_a = action.payload) === null || _a === void 0 ? void 0 : _a.changes.length) || this.disableNumberingConfig || !((_b = this.numberingConfig) === null || _b === void 0 ? void 0 : _b.isAutoNumbering) || !this._fieldAutoNum) {
      return action;
    }
    if (!action.payload.changes.some((change) => change.operation === 'INSERT' || change.operation === 'COPY')) {
      return action;
    }
    const lastRecord = this.getLastRecordSaved(action);
    if (lastRecord && lastRecord.hasOwnProperty(this._fieldAutoNum)) {
      const currentNumber = Number(lastRecord[this._fieldAutoNum]);
      this.numberingConfig.initialNumber = currentNumber;
      this.saveNumberingConfig();
    }
    else {
      this.numberingConfig.initialNumber = this.numberingConfig.initialNumber + 1;
    }
    (_c = this.numberingConfigChanged) === null || _c === void 0 ? void 0 : _c.emit(this.numberingConfig);
    return action;
  }
  interceptDataSaved(action) {
    this.updateNumberingConfigAfterInsert(action);
    return action;
  }
  async interceptLoadData(action) {
    var _a, _b, _c, _d, _e, _f, _g;
    const hasInvalidFilters = !validateFilters((_b = (_a = this._snkFilterBar) === null || _a === void 0 ? void 0 : _a.filterConfig) !== null && _b !== void 0 ? _b : []);
    if (hasInvalidFilters) {
      const errorTitle = (_d = (_c = this.messagesBuilder) === null || _c === void 0 ? void 0 : _c.getMessage("snkGrid.requiredFiltersNotFilled.title", {})) !== null && _d !== void 0 ? _d : "";
      const errorMessage = (_f = (_e = this.messagesBuilder) === null || _e === void 0 ? void 0 : _e.getMessage("snkGrid.requiredFiltersNotFilled.message", {})) !== null && _f !== void 0 ? _f : "";
      await ((_g = this._application) === null || _g === void 0 ? void 0 : _g.error(errorTitle, errorMessage));
      return;
    }
    return action;
  }
  onDataUnitReady() {
    var _a;
    (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.addInterceptor(this.dataUnitInterceptor);
    this.loadNumberingConfig();
  }
  async initDataUnit() {
    var _a, _b, _c;
    this.addDataElementID();
    if (!this.messagesBuilder) {
      this.messagesBuilder = (_a = this._snkDataUnit) === null || _a === void 0 ? void 0 : _a.messagesBuilder;
    }
    if (this._resourceID == undefined) {
      //Tenta pegar o resourceID do snkDataUnit;
      this._resourceID = (_b = this._snkDataUnit) === null || _b === void 0 ? void 0 : _b.resourceID;
      if (this._resourceID == undefined) {
        this._resourceID = await ((_c = this._application) === null || _c === void 0 ? void 0 : _c.getResourceID());
      }
    }
    this.onDataUnitReady();
  }
  initContinuousInsertUtils() {
    if (!this._application || !this._resourceID) {
      return;
    }
    this._continuousInsertUtils = new ContinuousInsertUtils(this._application, this._resourceID, this.configName);
    if (this.enableGridInsert) {
      this._continuousInsertUtils.getConfig().then(value => this._enableContinuousInsert = value);
    }
  }
  async loadNumberingConfig() {
    if (this.numberingConfig || !this._snkDataUnit || !this._snkDataUnit.entityName || this.disableNumberingConfig || !this._application) {
      return;
    }
    if (!this._servicesNumberingConfig) {
      this._servicesNumberingConfig = new ServicesNumberingConfig(this._application, this._resourceID);
    }
    try {
      this.numberingConfig = await this._servicesNumberingConfig.getConfig(this._snkDataUnit.entityName);
      this.getFieldAutoNum();
      this.applyNumberingConfigToFields();
    }
    catch (error) {
      console.error("Error loading numbering config in snk-crud:", error);
      this.numberingConfig = {
        isAutoNumbering: false,
        initialNumber: NaN
      };
    }
  }
  getFieldAutoNum() {
    var _a;
    if (this._fieldAutoNum) {
      return;
    }
    const fieldAutoNum = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.metadata.fields.find((field) => { var _a; return ((_a = field.properties) === null || _a === void 0 ? void 0 : _a["isAutoNumField"]) === "true"; });
    this._fieldAutoNum = (fieldAutoNum === null || fieldAutoNum === void 0 ? void 0 : fieldAutoNum.name) || null;
  }
  async applyNumberingConfigToFields() {
    var _a;
    if (!this.numberingConfig || !this._snkDataUnit || !this._fieldAutoNum) {
      return;
    }
    const field = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.getField(this._fieldAutoNum);
    if (!field) {
      return;
    }
    field.readOnly = this.numberingConfig.isAutoNumbering;
    field.required = !this.numberingConfig.isAutoNumbering;
  }
  handleConfiguratorEvent(evt, type) {
    var _a, _b;
    evt.stopImmediatePropagation();
    if (type === 'SAVE') {
      (_a = this.configuratorSave) === null || _a === void 0 ? void 0 : _a.emit();
      return;
    }
    (_b = this.configuratorCancel) === null || _b === void 0 ? void 0 : _b.emit();
  }
  renderCustomGuideSlots() {
    if (!this.customGuidesConfig)
      return;
    return this.customGuidesConfig.map(g => h("slot", { name: g.id }));
  }
  getColumnSearch(item) {
    if (this._columnSearch != undefined) {
      return this._columnSearch;
    }
    this._columnSearch = buildFieldSearch(item, ({ argument }) => new Promise(accept => {
      var _a;
      (_a = this._snkGrid) === null || _a === void 0 ? void 0 : _a.filterColumns(argument).then((columns) => {
        accept(columns
          .filter(column => !column.hidden)
          .map(column => ({ label: column.label, value: column.name })));
      });
    }), (option) => {
      var _a;
      if (option != undefined) {
        (_a = this._snkGrid) === null || _a === void 0 ? void 0 : _a.locateColumn(option.value);
      }
    });
    return this._columnSearch;
  }
  buildTaskbarCustomActionsList() {
    return [this.buildSearchColumnTaskbarAction()];
  }
  buildSearchColumnTaskbarAction() {
    var _a, _b;
    return {
      value: StringUtils.generateUUID(),
      label: (_b = (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage('snkGrid.findColumn', {})) !== null && _b !== void 0 ? _b : "",
      disableCloseOnSelect: true,
      eagerInitialize: true,
      itemBuilder: (_, item) => { var _a; return (_a = this.getColumnSearch(item)) !== null && _a !== void 0 ? _a : document.createElement('div'); },
    };
  }
  isGridInsertActive() {
    var _a;
    return this.enableGridInsert && ((_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.hasNewRecord());
  }
  getActionsList() {
    var _a, _b;
    const hardList = [];
    if (this.enableGridInsert && this._continuousInsertUtils) {
      hardList.push(this._continuousInsertUtils.actionContinuousInsert(this._enableContinuousInsert, () => {
        var _a;
        this._enableContinuousInsert = !this._enableContinuousInsert;
        (_a = this._continuousInsertUtils) === null || _a === void 0 ? void 0 : _a.handleSaveConfig(this._enableContinuousInsert);
      }));
    }
    if (this.isGridInsertActive()) {
      return hardList;
    }
    if (this._dataState && this.actionsList && this.taskbarManager != undefined && this.taskbarManager.getMoreOptions != undefined) {
      const taskbarID = getTopTaskBarId(this._dataState, this.presentationMode);
      return hardList.concat(this.taskbarManager.getMoreOptions(taskbarID, (_a = this.configName) !== null && _a !== void 0 ? _a : "", this._dataState, this.actionsList));
    }
    return hardList.concat((_b = this.actionsList) !== null && _b !== void 0 ? _b : []);
  }
  async openSearchPopover() {
    var _a;
    if (!this._popoverSearchEntity) {
      return;
    }
    const buttonElement = (_a = this._element) === null || _a === void 0 ? void 0 : _a.querySelector(`[data-taskbar-element="${CustomTaskbarButton.ENTITY_SEARCH}"]`);
    await this._popoverSearchEntity.showUnder(buttonElement);
  }
  handleLoadedSearch(evt) {
    var _a;
    if (evt.detail.length === 1) {
      (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.selectFirst();
      this.gridToForm(true);
    }
  }
  renderDynamicSearch() {
    var _a;
    if (!this.showEntitySearch)
      return;
    return (h("snk-entity-search", { ref: (ref) => this._popoverSearchEntity = ref, dataUnit: this._dataUnit, entityName: (_a = this._snkDataUnit) === null || _a === void 0 ? void 0 : _a.entityName, messagesBuilder: this.messagesBuilder, onLoaded: (evt) => this.handleLoadedSearch(evt) }));
  }
  handleFilterConfigUpdated(filterConfig) {
    if (!filterConfig.length) {
      return;
    }
    if (filterConfig.length === 1 && filterConfig[0].id === 'PERSONALIZED_FILTER_GROUP') {
      this._filterMode = filterConfig[0].groupedItems.length > 0 ? 'regular' : 'button';
      return;
    }
  }
  render() {
    var _a, _b, _c, _d, _e;
    if (this._resourceID == undefined) {
      return;
    }
    if (this._snkDataUnit) {
      this._snkDataUnit.ignoreSaveMessage = (this._currentViewMode === VIEW_MODE.GRID && !this.enableGridInsert);
    }
    return (h(Host, null, h("header", { class: { 'snk-crud--hidden': !this._headerVisible, 'snk-crud__header': true } }, h("div", { class: "snk-crud__header-top" }, h("snk-taskbar", { "data-element-id": "grid_top", key: "snkGridTopTaskbar", configName: this.configName, dataUnit: this._dataUnit, messagesBuilder: this.messagesBuilder, buttons: this._taskbarProcessor.buttons, disabledButtons: this._taskbarProcessor.disabledButtons, customButtons: this._taskbarProcessor.customButtons, resourceID: this._resourceID, primaryButton: "INSERT", overflowStrategy: "hiddenItems", alignRigth: true, actionsList: this.getActionsList(), customActionsList: this.buildTaskbarCustomActionsList(), sizeButtons: 'medium' })), h("snk-filter-bar", { ref: (ref) => this._snkFilterBar = ref, title: this.filterBarTitle, dataUnit: this._dataUnit, "data-element-id": "gridFilter", class: "snk-grid__filter-bar ez-align--top", configName: this.configName, messagesBuilder: this.messagesBuilder, resourceID: this._resourceID, onConfigUpdated: evt => this.handleFilterConfigUpdated(evt.detail), disablePersonalizedFilter: this.disablePersonalizedFilter, filterBarLegacyConfigName: this.filterBarLegacyConfigName, autoLoad: this.autoLoad, enableLockManagerLoadingComp: this.enableLockManagerLoadingComp, mode: this._filterMode, hideFilterButton: true, sizeChips: 'default' })), h("ez-view-stack", { ref: (ref) => this._viewStack = ref, "data-element-id": "crud" }, h("stack-item", { class: 'snk-crud__grid-stack-item' }, h("snk-grid", { ref: (ref) => this._snkGrid = ref, class: 'ez-flex ez-flex--column ez-size-height--full ez-size-width--full', filterBarTitle: this.filterBarTitle, "data-element-id": "crud_grid", configName: this.configName, onGridDoubleClick: () => this.gridToForm(true), taskbarManager: this.taskbarManager, onActionClick: evt => this.executeAction(evt.detail), messagesBuilder: this.messagesBuilder, actionsList: this.actionsList, statusResolver: this.statusResolver, multipleSelection: this.multipleSelection, presentationMode: this.presentationMode, recordsValidator: this.recordsValidator, selectionToastConfig: this.selectionToastConfig, useEnterLikeTab: this.useEnterLikeTab, canEdit: this._canEdit, resourceID: this._resourceID, disablePersonalizedFilter: this.disablePersonalizedFilter, gridLegacyConfigName: this.gridLegacyConfigName, filterBarLegacyConfigName: this.filterBarLegacyConfigName, autoLoad: this.autoLoad, autoFocus: this.autoFocus, enableGridInsert: this.enableGridInsert, enableLockManagerTaskbarClick: this.enableLockManagerTaskbarClick, enableLockManagerLoadingComp: this.enableLockManagerLoadingComp, strategyExporter: this.strategyExporter, multipleEditionEnabled: this.multipleEditionEnabled, paginationCounterMode: this.paginationCounterMode, hideHeader: true, hideGridTaskbar: true }, h("slot", { name: "GRID_TASKBAR_CUSTOM_ELEMENTS" }), h("slot", { name: "GRID_HEADER_CUSTOM_ELEMENTS" }), h("slot", { name: "SnkGridHeader" }), h("slot", { name: "SnkGridFooter" }), h("slot", { name: "SnkGridTaskBar" }))), h("stack-item", null, h("snk-dynaform-guides-view", { ref: (ref) => this._guidesViewer = ref, customGuidesConfig: this.customGuidesConfig, entityPath: (_a = this._snkDataUnit) === null || _a === void 0 ? void 0 : _a.entityName, messagesBuilder: this.messagesBuilder, onExit: () => this.setViewMode(VIEW_MODE.GRID), dataState: this._dataState, dataUnit: this._dataUnit, actionsList: this.actionsList, taskbarManager: this.taskbarManager, configName: this.configName, onActionClick: (evt) => this.executeAction(evt.detail), presentationMode: this.presentationMode, "data-element-id": "crud_form", canEdit: this._canEdit, recordsValidator: this.recordsValidator, resourceID: this._resourceID, detailTaskbarCustomContainerId: this.customContainerId, formLegacyConfigName: this.formLegacyConfigName, enableGridInsert: this.enableGridInsert, getCustomTitle: this.setCustomFormTitle, ignoreReadOnlyFormFields: this.ignoreReadOnlyFormFields, onFormConfigVisibilityChanged: evt => this._headerVisible = !evt.detail }, h("slot", { name: "GUIDES_VIEWER_TASKBAR_CUSTOM_ELEMENTS" }), this.renderCustomGuideSlots(), h("slot", { name: "SnkFormTaskBar" })))), h("snk-attach", { ref: (ref) => this._snkAttach = ref, registerKey: (_b = this.attachmentRegisterKey) !== null && _b !== void 0 ? _b : '', messagesBuilder: this.messagesBuilder, entityName: (_d = (_c = this._snkDataUnit) === null || _c === void 0 ? void 0 : _c.entityName) !== null && _d !== void 0 ? _d : '' }), h("snk-configurator", { ref: (ref) => this._snkConfigurator = ref, entityName: (_e = this._snkDataUnit) === null || _e === void 0 ? void 0 : _e.entityName, viewMode: this._currentViewMode, messagesBuilder: this.messagesBuilder, onConfigSelected: (evt) => this.setViewMode(evt.detail), onOpenConfig: (evt) => this.openConfig(evt.detail), showActionButtons: this.showActionButtons, onSave: evt => this.handleConfiguratorEvent(evt, 'SAVE'), onCancel: evt => this.handleConfiguratorEvent(evt, 'CANCEL'), resourceID: this._resourceID, customContainerId: this.customContainerId, layoutFormConfig: this.layoutFormConfig }), this.renderDynamicSearch(), h("div", { id: `${this.customContainerId}` }, h("slot", { name: "SnkConfigContainerSlot" }), h("slot", { name: "DETAIL_GRID_HEADER_CUSTOM_ELEMENTS" }), h("slot", { name: "DETAIL_GRID_TASKBAR_CUSTOM_ELEMENTS" }), h("slot", { name: "DETAIL_TASKBAR_CUSTOM_ELEMENTS" }))));
  }
  get _element() { return getElement(this); }
  static get watchers() { return {
    "_currentViewMode": ["currentViewModeWatcher"]
  }; }
};
SnkDynaform.style = snkDynaformCss;

export { SnkDynaform as snk_dynaform };
