import { proxyCustomElement, HTMLElement, createEvent, h, Fragment } from '@stencil/core/internal/client';
import { KeyboardManager, Action, ElementIDUtils, ApplicationContext, StringUtils } from '@sankhyalabs/core';
import { SelectionMode } from '@sankhyalabs/core/dist/dataunit/DataUnit';
import { buildFieldSearch } from '@sankhyalabs/ezui/dist/collection/utils';
import './DataFetcher.js';
import { P as PresentationMode, E as ExporterStrategy } from './ISave.js';
import { a as CommonsExporter, T as TaskbarProcessor, b as CrudUtils, S as SnkMultiSelectionListDataSource, R as RmPrecisionCustomValueFormatter, C as ContinuousInsertUtils, c as ClientSideExporterProvider } from './ContinuousInsertUtils.js';
import '@sankhyalabs/ezui/dist/collection/utils/constants';
import '@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata';
import './dataunit-fetcher.js';
import './filter-item-type.enum.js';
import './form-config-fetcher.js';
import './constants.js';
import { C as ConfigStorage } from './ConfigStorage.js';
import { s as store } from './index2.js';
import { g as getSelectedRecordsIDsInfo } from './GetSelectedRecordsIDsInfo.js';
import { v as validateFilters, d as defineCustomElement$b } from './snk-filter-modal2.js';
import { T as TaskbarElement, d as defineCustomElement$4 } from './snk-taskbar2.js';
import { d as defineCustomElement$n } from './snk-actions-button2.js';
import { d as defineCustomElement$m } from './snk-data-exporter2.js';
import { d as defineCustomElement$l } from './snk-default-filter2.js';
import { d as defineCustomElement$k } from './snk-exporter-email-sender2.js';
import { d as defineCustomElement$j } from './snk-expression-group2.js';
import { d as defineCustomElement$i } from './snk-expression-item2.js';
import { d as defineCustomElement$h } from './snk-filter-advanced-mode2.js';
import { d as defineCustomElement$g } from './snk-filter-assistent-mode2.js';
import { d as defineCustomElement$f } from './snk-filter-bar2.js';
import { d as defineCustomElement$e } from './snk-filter-detail2.js';
import { d as defineCustomElement$d } from './snk-filter-field-search2.js';
import { d as defineCustomElement$c } from './snk-filter-item2.js';
import { d as defineCustomElement$a } from './snk-filter-modal-item2.js';
import { d as defineCustomElement$9 } from './snk-filter-param-config2.js';
import { d as defineCustomElement$8 } from './snk-grid-config2.js';
import { d as defineCustomElement$7 } from './snk-personalized-filter2.js';
import { d as defineCustomElement$6 } from './snk-select-box2.js';
import { d as defineCustomElement$5 } from './snk-simple-bar2.js';
import { d as defineCustomElement$3 } from './snk-taskbar-skeleton2.js';
import { d as defineCustomElement$2 } from './taskbar-actions-button2.js';
import { d as defineCustomElement$1 } from './taskbar-split-button2.js';

class ServerSideExporterProvider extends CommonsExporter {
  getFilters() {
    var _a;
    return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getAppliedFilters();
  }
  getOrders() {
    var _a;
    return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getSort();
  }
  getResourceURI() {
    var _a;
    return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.name;
  }
  getSelectedNumber() {
    return this.dataUnit.getSelectionInfo().length;
  }
  getTotalRecords() {
    var _a, _b, _c;
    const { total } = ((_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getPaginationInfo()) || {};
    return total !== null && total !== void 0 ? total : (_c = (_b = this.dataUnit) === null || _b === void 0 ? void 0 : _b.records) === null || _c === void 0 ? void 0 : _c.length;
  }
  getSelectedIDs() {
    return getSelectedRecordsIDsInfo(this.dataUnit);
  }
  getOffset() {
    return this.getExporterOffset(this.getPaginationInfo());
  }
  getPageSize() {
    var _a;
    return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.pageSize;
  }
  getExportLimit() {
    return 5000;
  }
  getRecordID() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.records) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.__record__id__;
  }
  getPaginationInfo() {
    var _a;
    return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getPaginationInfo();
  }
  getExporterOffset(paginationInfo) {
    if (paginationInfo == undefined) {
      return;
    }
    const offset = paginationInfo.firstRecord;
    if (offset > 0) {
      return (offset - 1);
    }
    return offset;
  }
}

const snkGridCss = ".sc-snk-grid-h{--snk-grid-min-height:300px;--snk-grid-padding:unset;--snk-grid-margin:var(--space--small);--snk-grid-box-shadow:var(--shadow--small);--snk-grid__header-padding:unset}.snk-grid__container.sc-snk-grid{display:flex;height:100%;margin:var(--snk-grid-margin);outline:none;border:1px solid var(--color--strokes, #E1E2E5);border-radius:var(--border--radius-12, 12px);box-shadow:var(--snk-grid-box-shadow);padding:var(--snk-grid-padding);--snk-grid-header--min-height:var(--space--52)}.snk-grid__header.sc-snk-grid{width:100%;display:flex;flex-wrap:nowrap;justify-content:flex-end;align-items:flex-start;min-height:var(--snk-grid-header--min-height);padding-top:var(--snk-grid__header-padding);padding-right:var(--snk-grid__header-padding)}.snk-grid__filter-bar.sc-snk-grid{width:100%}.snk-grid__header-divider.sc-snk-grid{margin-bottom:var(--space--medium);margin-right:var(--space--0);align-self:stretch}.snk-grid__header.sc-snk-grid snk-taskbar.sc-snk-grid{display:flex;align-items:flex-start;min-height:var(--snk-grid-header--min-height)}.snk-grid__header.sc-snk-grid ez-tooltip.sc-snk-grid{width:auto;margin-inline:var(--space--8, 8px)}.snk-grid__table.sc-snk-grid{min-height:var(--snk-grid-min-height)}.snk-grid-container__without-shadow.sc-snk-grid{--ezgrid__container--shadow:unset}.snk-grid-container__footer.sc-snk-grid{background-color:var(--background--xlight, #FFF);border-radius:0 0 var(--border--radius-medium) var(--border--radius-medium)}.snk-grid-container__footer.sc-snk-grid:has(*){border-top:1px solid var(--color--strokes, #E1E2E5)}";

const SnkGrid = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.actionClick = createEvent(this, "actionClick", 7);
    this.gridDoubleClick = createEvent(this, "gridDoubleClick", 7);
    this.componentReady = createEvent(this, "componentReady", 7);
    this._customEditors = new Map();
    this._customRenders = new Map();
    this._keyboardManager = new KeyboardManager();
    this._topTaskbarProcessor = new TaskbarProcessor({
      'snkGridTopTaskbar.regular': ['FORM_MODE', 'CONFIGURATOR', 'INSERT'],
      'snkGridTopTaskbar.regular.secondary': ['FORM_MODE', 'CONFIGURATOR', 'INSERT'],
      'snkGridTopTaskbar.regular.singleTaskbar': [],
      'snkGridTopTaskbar.finish_edition': ['CANCEL', 'SAVE', this.handleAddFormMode()],
      'snkGridTopTaskbar.finish_edition.secondary': [],
      'snkGridTopTaskbar.finish_edition.singleTaskbar': [],
    });
    this._headerTaskbarProcessor = new TaskbarProcessor({
      'snkGridHeaderTaskbar.unselected': ['REFRESH', 'DATA_EXPORTER', 'ACTIONS_BUTTON', 'MORE_OPTIONS'],
      'snkGridHeaderTaskbar.selected': this.getGridHeaderSelectedBtns(),
      'snkGridHeaderTaskbar.detail.unselected': ['REFRESH', 'ACTIONS_BUTTON', 'MORE_OPTIONS'],
      'snkGridHeaderTaskbar.detail.selected': this.getDetailGridSelectedBtns(),
      'snkGridHeaderTaskbar.singleTaskbar.unselected': ['INSERT', 'FORM_MODE', 'CONFIGURATOR', 'REFRESH', 'DATA_EXPORTER', 'ACTIONS_BUTTON', 'MORE_OPTIONS'],
      'snkGridHeaderTaskbar.singleTaskbar.selected': ['UPDATE', 'CLONE', 'REMOVE', 'MORE_OPTIONS', 'DIVIDER', 'ATTACH', 'FORM_MODE', 'CONFIGURATOR', 'REFRESH', 'DATA_EXPORTER', 'ACTIONS_BUTTON'],
      'snkGridHeaderTaskbar.singleTaskbar.detail.unselected': ['INSERT', 'FORM_MODE', 'CONFIGURATOR', 'REFRESH', 'ACTIONS_BUTTON', 'MORE_OPTIONS'],
      'snkGridHeaderTaskbar.singleTaskbar.detail.selected': ['UPDATE', 'ATTACH', 'CLONE', 'REMOVE', 'MORE_OPTIONS', 'DIVIDER', 'FORM_MODE', 'CONFIGURATOR', 'REFRESH', 'ACTIONS_BUTTON'],
      'snkGridHeaderTaskbar.singleTaskbar.finish_edition': ['CANCEL', 'SAVE', this.handleAddFormMode()],
    });
    this.dataUnitInterceptor = {
      interceptAction: async (action) => {
        if (action.type === Action.METADATA_LOADED) {
          return await this.interceptMetadataLoaded(action);
        }
        if (action.type === Action.LOADING_DATA) {
          return await this.interceptLoadData(action);
        }
        return action;
      },
    };
    this._dataUnit = undefined;
    this._dataState = undefined;
    this._gridConfig = undefined;
    this._popUpGridConfig = false;
    this._showSnkFilterBar = true;
    this._enableContinuousInsert = false;
    this._filterMode = 'regular';
    this.columnFilterDataSource = undefined;
    this.enableLockManagerLoadingComp = false;
    this.enableLockManagerTaskbarClick = false;
    this.configName = undefined;
    this.filterBarTitle = undefined;
    this.resourceID = undefined;
    this.selectionToastConfig = undefined;
    this.actionsList = undefined;
    this.isDetail = undefined;
    this.taskbarManager = undefined;
    this.statusResolver = undefined;
    this.multipleSelection = undefined;
    this.presentationMode = PresentationMode.PRIMARY;
    this.messagesBuilder = undefined;
    this.useEnterLikeTab = false;
    this.recordsValidator = undefined;
    this.canEdit = true;
    this.taskbarCustomContainerId = undefined;
    this.gridHeaderCustomSlotId = 'GRID_HEADER_CUSTOM_ELEMENTS';
    this.gridHeaderDynamicSearchSlotId = 'GRID_HEADER_DYNAMIC_SEARCH';
    this.topTaskbarCustomSlotId = 'GRID_TASKBAR_CUSTOM_ELEMENTS';
    this.disablePersonalizedFilter = undefined;
    this.gridLegacyConfigName = undefined;
    this.filterBarLegacyConfigName = undefined;
    this.autoLoad = undefined;
    this.autoFocus = true;
    this.enableGridInsert = false;
    this.outlineMode = false;
    this.suppressHorizontalScroll = false;
    this.strategyExporter = ExporterStrategy.SERVER_SIDE;
    this.useSearchColumn = true;
    this.multipleEditionEnabled = true;
    this.paginationCounterMode = 'auto';
    this.suppressCheckboxColumn = undefined;
    this.suppressFilterColumn = false;
    this.compact = undefined;
    this.filterCustomConfig = undefined;
    this.filterCustomConfigInterceptor = undefined;
    this.hidePagination = false;
    this.hideHeader = false;
    this.hideGridTaskbar = false;
  }
  getDetailGridSelectedBtns() {
    const btns = [
      TaskbarElement.UPDATE, TaskbarElement.ATTACH, TaskbarElement.CLONE, TaskbarElement.MORE_OPTIONS,
      TaskbarElement.DIVIDER, TaskbarElement.REFRESH, TaskbarElement.ACTIONS_BUTTON
    ];
    if (this.multipleEditionEnabled)
      btns.unshift(TaskbarElement.UPDATE_MULTIPLE);
    return btns;
  }
  getGridHeaderSelectedBtns() {
    const btns = [
      TaskbarElement.UPDATE, TaskbarElement.CLONE, TaskbarElement.REMOVE,
      TaskbarElement.MORE_OPTIONS, TaskbarElement.DIVIDER, TaskbarElement.ATTACH, TaskbarElement.FORM_MODE,
      TaskbarElement.CONFIGURATOR, TaskbarElement.REFRESH, TaskbarElement.DATA_EXPORTER, TaskbarElement.ACTIONS_BUTTON,
    ];
    if (this.multipleEditionEnabled)
      btns.unshift(TaskbarElement.UPDATE_MULTIPLE);
    return btns;
  }
  async refreshColumnFilterDataSource() {
    await this._grid.refreshColumnFilterDataSource();
  }
  /**
   * Recarrega a configuração da grade.
   * @description Este método força o recarregamento da configuração da grade a partir do `ConfigStorage`. A operação é assíncrona, mas o método não aguarda sua conclusão.
   */
  reloadConfig() {
    this.loadConfig();
  }
  /**
   * Exibe a janela de configurações da grade.
   * @async
   * @description Este método abre o pop-up de configuração de colunas da grade, permitindo ao usuário ajustar a visibilidade, ordem e largura das colunas.
   * @returns {Promise<void>} Uma promessa que é resolvida quando a janela de configuração é exibida.
   */
  async showConfig() {
    if (this._grid == undefined) {
      return;
    }
    await this.openGridConfig();
  }
  /**
   * Fecha a janela de configurações da grade.
   * @async
   * @description Este método fecha o pop-up de configuração de colunas da grade.
   * @returns {Promise<void>} Uma promessa que é resolvida quando a janela de configuração é fechada.
   */
  async hideConfig() {
    if (this._grid == undefined) {
      return;
    }
    this.closeGridConfig();
  }
  /**
   * Define a configuração da grade.
   * @async
   * @description Aplica uma nova configuração de colunas e ordenação à grade.
   * @param {IGridConfig} config O objeto de configuração a ser aplicado na grade.
   * @returns {Promise<void>} Uma promessa que é resolvida quando a configuração é aplicada.
   */
  async setConfig(config) {
    this.setGridConfig(config);
  }
  /**
   * Recarrega a barra de filtros da grade, buscando o estado do servidor.
   * @async
   * @description Força o recarregamento da barra de filtros, atualizando suas configurações e filtros a partir do servidor.
   * @returns {Promise<void>} Uma promessa que é resolvida quando a barra de filtros é recarregada.
   */
  async reloadFilterBar() {
    var _a;
    (_a = this._snkFilterBar) === null || _a === void 0 ? void 0 : _a.reload();
  }
  /**
   * Retorna o elemento da barra de filtros da grade.
   * @async
   * @description Este método permite acessar o elemento da barra de filtros, que pode ser útil para manipulações adicionais ou para obter o estado atual dos filtros aplicados.
   * @returns {Promise<HTMLSnkFilterBarElement>} O elemento da barra de filtros.
   */
  async getFilterBar() {
    return this._snkFilterBar;
  }
  /**
   * Registra um editor customizado para um campo da grade ou formulário.
   * @async
   * @description Adiciona um componente de edição personalizado para um campo específico. Este editor será usado tanto na edição em linha na grade quanto em formulários de detalhe.
   * @param {string} fieldName O nome do campo que receberá o editor customizado.
   * @param {ICustomEditor} customEditor A instância do editor customizado.
   * @param {string} [detailContext] O contexto de detalhe onde o editor será aplicado (opcional).
   * @returns {Promise<void>} Uma promessa que é resolvida quando o editor é registrado.
   */
  async addCustomEditor(fieldName, customEditor, detailContext) {
    if (this._grid) {
      this._grid.addCustomEditor(fieldName, customEditor, detailContext);
      return;
    }
    const newCustomEditors = new Map(this._customEditors);
    newCustomEditors.set(fieldName, { customEditor, detailContext });
    this._customEditors = newCustomEditors;
  }
  /**
   * Registra um renderizador customizado para uma coluna da grade.
   * @async
   * @description Adiciona um componente de renderização personalizado para uma coluna específica, permitindo a exibição de conteúdo customizado nas células.
   * @param {string} fieldName O nome do campo (coluna) que receberá o renderizador customizado.
   * @param {ICustomRender} customRender A instância do renderizador customizado.
   * @param {string} [detailContext] O contexto de detalhe onde o renderizador será aplicado (opcional).
   * @returns {Promise<void>} Uma promessa que é resolvida quando o renderizador é registrado.
   */
  async addGridCustomRender(fieldName, customRender, detailContext) {
    if (this._grid) {
      this._grid.addGridCustomRender(fieldName, customRender, detailContext);
      return;
    }
    const newCustomRenders = new Map(this._customRenders);
    newCustomRenders.set(fieldName, { customRender, detailContext });
    this._customRenders = newCustomRenders;
  }
  /**
   * Registra um formatador de valor customizado para uma coluna da grade.
   * @async
   * @description Adiciona uma função de formatação personalizada para os valores de uma coluna específica, afetando como os dados são exibidos.
   * @param {string} columnName O nome da coluna que receberá o formatador.
   * @param {ICustomFormatter} customFormatter A instância do formatador de valor.
   * @returns {Promise<void>} Uma promessa que é resolvida quando o formatador é registrado.
   */
  async addCustomValueFormatter(columnName, customFormatter) {
    this._grid.addCustomValueFormatter(columnName, customFormatter);
  }
  /**
   * Remove um formatador de valor customizado de uma coluna da grade.
   * @async
   * @description Remove uma função de formatação personalizada previamente registrada para uma coluna.
   * @param {string} columnName O nome da coluna da qual o formatador será removido.
   * @returns {Promise<void>} Uma promessa que é resolvida quando o formatador é removido.
   */
  async removeCustomValueFormatter(columnName) {
    this._grid.removeCustomValueFormatter(columnName);
  }
  /**
   * Atribui o foco para a grade.
   * @async
   * @description Move o foco do navegador para o componente da grade, permitindo a navegação por teclado.
   * @returns {Promise<void>} Uma promessa que é resolvida quando o foco é atribuído.
   */
  async setFocus() {
    this._grid.setFocus();
  }
  /**
   * Manipula a mudança de página da grid.
   */
  async handlePageChange() {
    await this._grid.handlePageChange();
  }
  /**
   * Localiza determinada coluna tornando-a visível.
   */
  async locateColumn(columnName) {
    return this._grid.locateColumn(columnName);
  }
  /**
   * Usa um argumento para filtrar as colunas por label
   */
  async filterColumns(search) {
    return this._grid.filterColumns(search);
  }
  async handleClick(event) {
    var _a;
    if (this.hasToBlockEvent(event)) {
      event.preventDefault();
      event.stopPropagation();
      if (!await this._dataUnit.cancelEdition())
        return;
      const newEvent = new event.constructor(event.type, event);
      (_a = event.target) === null || _a === void 0 ? void 0 : _a.dispatchEvent(newEvent);
    }
    if (this._grid && !this._grid.contains(event.target)) {
      this._grid.stopEdit();
    }
  }
  hasToBlockEvent(event) {
    var _a;
    return ((_a = this._snkFilterBar) === null || _a === void 0 ? void 0 : _a.contains(event.target)) && this.enableGridInsert && this._dataUnit.hasNewRecord();
  }
  async handleGridLegacyConfigName(newLegacyConfig, oldLegacyConfig) {
    if (!newLegacyConfig) {
      return;
    }
    if (newLegacyConfig === oldLegacyConfig) {
      return;
    }
    this.addGridLegacyConfigName();
    this.loadConfig();
  }
  handleAddFormMode() {
    return this.enableGridInsert ? TaskbarElement.FORM_MODE : '';
  }
  async openGridConfig() {
    const originalColumns = await this._grid.getColumns();
    const gridColumns = await this._grid.getColumnsState();
    this._snkGridConfig.columns = gridColumns.filter(c => c.name);
    this._snkGridConfig.originalColumns = originalColumns.filter(c => c.name);
    this._popUpGridConfig = true;
  }
  closeGridConfig() {
    this._popUpGridConfig = false;
  }
  setGridConfig(config) {
    this._gridConfig = config;
    CrudUtils.assertDefaultSorting(this._gridConfig, this._dataUnit);
  }
  fixColumNameCharset(columnName) {
    try {
      return decodeURIComponent(escape(columnName));
    }
    catch (e) {
      return columnName;
    }
  }
  normalizeGridConfig(config) {
    if (!config)
      return config;
    const columnsMapped = config.columns.map(column => (Object.assign(Object.assign({}, column), { name: this.fixColumNameCharset(column.name) })));
    return Object.assign(Object.assign({}, config), { columns: columnsMapped });
  }
  loadConfig() {
    ConfigStorage.loadGridConfig(this.configName, this.resourceID)
      .then((config) => {
      this.setGridConfig(this.normalizeGridConfig(config));
    })
      .catch((error) => {
      console.warn(error);
    });
  }
  addGridLegacyConfigName() {
    if (this.gridLegacyConfigName && this.configName) {
      ConfigStorage.addGridLegacyConfig(this.configName, this.gridLegacyConfigName);
    }
  }
  hasCalculatedFields(columnNames) {
    let hasCalculatedFields = false;
    columnNames.forEach(name => {
      var _a;
      const field = this._dataUnit.getField(name);
      if (((_a = field.properties) === null || _a === void 0 ? void 0 : _a.calculated) === 'true') {
        hasCalculatedFields = true;
      }
    });
    return hasCalculatedFields;
  }
  gridConfigChangeHandler(evt) {
    const config = this.normalizeGridConfig(evt.detail);
    ConfigStorage.saveGridConfig(config, this.configName, this.resourceID);
    evt.stopPropagation();
  }
  modalConfigChangeHandler(evt) {
    const config = this.normalizeGridConfig(evt.detail);
    this._grid.setColumnsState(config.columns)
      .then(() => {
      this.setGridConfig(config);
      this.closeGridConfig();
      this.dataExporterProviderStore();
    });
    evt.stopPropagation();
  }
  async hasToForceClientSideExporter() {
    if (!this._grid) {
      return false;
    }
    const filters = await this._grid.getAppliedColumnFilters();
    const columnNames = filters.map(filter => filter.name.replace('FILTRO_COLUNA_', ''));
    return this.hasCalculatedFields(columnNames);
  }
  async dataExporterProviderStore() {
    /**
     * O ServerSideExporterProvider do SankhyaOm não suporta a filtragem de campos calculados.
     * Por esse motivo, precisamos verificar os filtros aplicados no momento e recriar o dataExporterProvider conforme necessário.
     * Se houver campos calculados, forçamos o uso do clientSide, caso contrário é seguido o fluxo padrão.
     */
    const forceClientSide = await this.hasToForceClientSideExporter();
    const dataExporterProvider = (forceClientSide || this.strategyExporter === ExporterStrategy.CLIENT_SIDE)
      ? new ClientSideExporterProvider(this._dataUnit, this._grid)
      : new ServerSideExporterProvider(this._dataUnit, this._grid);
    store.set('exporterProviders', Object.assign(Object.assign({}, store.get('exporterProviders')), { [this.configName]: dataExporterProvider }));
  }
  addElementID() {
    const dataInfo = { dataUnit: this._dataUnit };
    ElementIDUtils.addIDInfo(this._element, null, dataInfo);
  }
  loadGridCustomFormatters(fields) {
    if (!fields || !this._grid) {
      return;
    }
    fields.forEach((field) => {
      var _a;
      if ((_a = field.properties) === null || _a === void 0 ? void 0 : _a.rm_precision) {
        this.addCustomValueFormatter(field.name, this._rmPrecisionCustomValueFormatter);
      }
    });
  }
  async interceptMetadataLoaded(action) {
    this.loadGridCustomFormatters(action.payload.fields);
    return action;
  }
  async interceptLoadData(action) {
    var _a;
    const hasInvalidFilters = !validateFilters((_a = this._snkFilterBar) === null || _a === void 0 ? void 0 : _a.filterConfig);
    if (hasInvalidFilters) {
      const errorTitle = this.messagesBuilder.getMessage("snkGrid.requiredFiltersNotFilled.title", {});
      const errorMessage = this.messagesBuilder.getMessage("snkGrid.requiredFiltersNotFilled.message", {});
      await this._application.error(errorTitle, errorMessage);
      return;
    }
    return action;
  }
  initializeColumnFilterDataSource() {
    var _a, _b, _c;
    const isInMemoryDataUnit = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.name.includes("InMemoryDataUnit");
    if (!this.columnFilterDataSource && !isInMemoryDataUnit) {
      this.columnFilterDataSource = new SnkMultiSelectionListDataSource();
    }
    (_b = this.columnFilterDataSource) === null || _b === void 0 ? void 0 : _b.setApplication(this._application);
    (_c = this.columnFilterDataSource) === null || _c === void 0 ? void 0 : _c.setDataUnit(this._dataUnit);
  }
  finishLoading() {
    this._dataUnit.addInterceptor(this.dataUnitInterceptor);
    CrudUtils.assertDefaultSorting(this._gridConfig, this._dataUnit);
    this.addElementID();
    this.initializeColumnFilterDataSource();
  }
  setCustomRenders() {
    if (!this._grid) {
      return;
    }
    for (const [fieldName, customRenderProps] of this._customRenders) {
      this._grid.addGridCustomRender(fieldName, customRenderProps.customRender, customRenderProps.detailContext);
      this._customRenders.delete(fieldName);
    }
  }
  setCustomEditors() {
    if (!this._grid) {
      return;
    }
    for (const [fieldName, customEditorProps] of this._customEditors) {
      this._grid.addCustomEditor(fieldName, customEditorProps.customEditor, customEditorProps.detailContext);
      this._customEditors.delete(fieldName);
    }
  }
  componentWillLoad() {
    this._application = ApplicationContext.getContextValue('__SNK__APPLICATION__');
    //TODO: substituir pelo metodo nativo closest
    let parent = this._element.parentElement;
    while (parent) {
      if (parent.tagName.toUpperCase() === 'SNK-DATA-UNIT') {
        this._snkDataUnit = parent;
        this._dataUnit = this._snkDataUnit.dataUnit;
        if (!this._dataUnit) {
          this._snkDataUnit.addEventListener('dataUnitReady', (evt) => {
            this._dataUnit = evt.detail;
            this.finishLoading();
          });
        }
        else {
          this.finishLoading();
        }
        if (!this.messagesBuilder)
          this.messagesBuilder = this._snkDataUnit.messagesBuilder;
        this._snkDataUnit.addEventListener('dataStateChange', this.handleDataStateChange.bind(this));
        this._snkDataUnit.addEventListener('cancelEdition', () => {
          var _a;
          if ((_a = this._dataState) === null || _a === void 0 ? void 0 : _a.recordsIsEmpty) {
            this._dataUnit.clearSelection();
          }
        });
        break;
      }
      parent = parent.parentElement;
    }
    this._rmPrecisionCustomValueFormatter = new RmPrecisionCustomValueFormatter();
    this.addGridLegacyConfigName();
    this.loadConfig();
    this._continuousInsertUtils = new ContinuousInsertUtils(this._application, this.resourceID, this.configName);
    if (this.enableGridInsert) {
      this._continuousInsertUtils.getConfig().then(value => this._enableContinuousInsert = value);
    }
  }
  componentDidRender() {
    var _a, _b;
    this._rmPrecisionCustomValueFormatter.setGrid(this._grid);
    this.loadGridCustomFormatters((_b = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.fields);
    this.setCustomRenders();
    this.setCustomEditors();
  }
  async handleDataStateChange(evt) {
    this._dataState = evt.detail;
    this._rmPrecisionCustomValueFormatter.setDataState(this._dataState);
  }
  getHeaderDisabledButtons() {
    var _a;
    const disabledButtons = [];
    if ((_a = this._dataState) === null || _a === void 0 ? void 0 : _a.selectionInfo) {
      if (this._dataState.selectionInfo.length > 1) {
        disabledButtons.push(TaskbarElement.CLONE, TaskbarElement.ATTACH, TaskbarElement.UPDATE);
      }
      if (this._dataState.selectionInfo.isAllRecords()) {
        disabledButtons.push(TaskbarElement.REMOVE);
      }
    }
    return disabledButtons;
  }
  getInvisibleButtons() {
    var _a, _b, _c;
    let invisibleButtons = [];
    if (!this._dataUnit || this._dataUnit.records.length === 0)
      invisibleButtons.push(TaskbarElement.DATA_EXPORTER);
    if (((_a = this._dataState) === null || _a === void 0 ? void 0 : _a.selectionInfo.mode) === SelectionMode.ALL_RECORDS)
      invisibleButtons.push(TaskbarElement.ACTIONS_BUTTON);
    if (((_b = this._dataState) === null || _b === void 0 ? void 0 : _b.selectionInfo.length) === 1)
      invisibleButtons.push(TaskbarElement.UPDATE_MULTIPLE);
    if (!((_c = this._dataState) === null || _c === void 0 ? void 0 : _c.selectionInfo.length))
      invisibleButtons.push(TaskbarElement.FORM_MODE);
    return invisibleButtons;
  }
  componentWillRender() {
    const invisibleButtons = this.getInvisibleButtons();
    this._headerTaskbarProcessor.process(this.getHeaderTaskbarId(), this.taskbarManager, this._dataState, this.getHeaderDisabledButtons(), invisibleButtons);
    this._topTaskbarProcessor.process(this.getTopTaskBarId(), this.taskbarManager, this._dataState, undefined, invisibleButtons);
    this.dataExporterProviderStore();
  }
  getHeaderTaskbarId() {
    var _a, _b;
    const hasSelectedRecord = this._dataState && !!((_a = this._dataState.selectionInfo) === null || _a === void 0 ? void 0 : _a.length);
    const taskbarIdPrefixLookup = {
      primary: this.isDetail ? 'snkGridHeaderTaskbar.detail' : 'snkGridHeaderTaskbar',
      secondary: this.isDetail ? 'snkGridHeaderTaskbar.detail' : 'snkGridHeaderTaskbar',
      singleTaskbar: this.isDetail ? 'snkGridHeaderTaskbar.singleTaskbar.detail' : 'snkGridHeaderTaskbar.singleTaskbar',
    };
    const taskbarIdPrefix = taskbarIdPrefixLookup[this.presentationMode];
    let headerTaskbarId = hasSelectedRecord ? `${taskbarIdPrefix}.selected` : `${taskbarIdPrefix}.unselected`;
    if (((_b = this._dataState) === null || _b === void 0 ? void 0 : _b.isDirty) && this.presentationMode === PresentationMode.SINGLE_TASKBAR) {
      headerTaskbarId = 'snkGridHeaderTaskbar.singleTaskbar.finish_edition';
    }
    return headerTaskbarId;
  }
  getTopTaskBarId() {
    var _a;
    const suffixLookup = {
      primary: '',
      secondary: '.secondary',
      singleTaskbar: '.singleTaskbar',
    };
    const sufix = suffixLookup[this.presentationMode];
    if ((_a = this._dataState) === null || _a === void 0 ? void 0 : _a.isDirty) {
      return `snkGridTopTaskbar.finish_edition${sufix}`;
    }
    return `snkGridTopTaskbar.regular${sufix}`;
  }
  getPrimaryButton() {
    const primaryButtonLookup = {
      primary: 'INSERT',
      secondary: '',
      singleTaskbar: 'INSERT',
    };
    return primaryButtonLookup[this.presentationMode];
  }
  getColumnSearch(item) {
    if (this._columnSearch != undefined) {
      return this._columnSearch;
    }
    this._columnSearch = buildFieldSearch(item, ({ argument }) => new Promise(accept => {
      this._grid.filterColumns(argument).then((columns) => {
        accept(columns
          .filter(column => !column.hidden)
          .map(column => ({ label: column.label, value: column.name })));
      });
    }), (option) => {
      if (option != undefined) {
        this._grid.locateColumn(option.value);
      }
    });
    return this._columnSearch;
  }
  getActionsList() {
    const hardList = [];
    if (this.enableGridInsert) {
      hardList.push(this._continuousInsertUtils.actionContinuousInsert(this._enableContinuousInsert, () => {
        this._enableContinuousInsert = !this._enableContinuousInsert;
        this._continuousInsertUtils.handleSaveConfig(this._enableContinuousInsert);
      }));
    }
    if (this.isGridInsertActive())
      return hardList;
    if (this.taskbarManager != undefined && this.taskbarManager.getMoreOptions != undefined) {
      const taskbarID = this.getTopTaskBarId();
      return hardList.concat(this.taskbarManager.getMoreOptions(taskbarID, this.configName, this._dataState, this.actionsList));
    }
    return hardList.concat(this.actionsList);
  }
  getActionsSettingsList() {
    const hardList = [{
        value: StringUtils.generateUUID(),
        label: this.messagesBuilder.getMessage('snkGrid.findColumn', {}),
        disableCloseOnSelect: true,
        eagerInitialize: true,
        itemBuilder: (_, item) => this.getColumnSearch(item),
      }];
    return hardList;
  }
  handleFilterConfigUpdated(filterConfig) {
    if (!filterConfig.length) {
      this._showSnkFilterBar = false;
      return;
    }
    if (filterConfig.length === 1 && filterConfig[0].id === 'PERSONALIZED_FILTER_GROUP') {
      this._showSnkFilterBar = true;
      this._filterMode = filterConfig[0].groupedItems.length > 0 ? 'regular' : 'button';
      return;
    }
    this._showSnkFilterBar = true;
  }
  getGridHeaderButtons() {
    if (this.isGridInsertActive())
      return TaskbarElement.MORE_OPTIONS;
    return this._headerTaskbarProcessor.buttons;
  }
  isGridInsertActive() {
    return this.enableGridInsert && this._dataUnit.hasNewRecord();
  }
  render() {
    var _a, _b;
    if (!this._dataUnit) {
      return undefined;
    }
    return (h("div", { class: "snk-grid__container ez-flex ez-flex--column ez-flex-item--auto ez-box--no-outline", tabindex: "0" }, !this.hideHeader &&
      h("div", { class: "snk-grid__header" }, this._showSnkFilterBar &&
        h(Fragment, null, 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, filterCustomConfig: this.filterCustomConfig, filterCustomConfigInterceptor: this.filterCustomConfigInterceptor, mode: this._filterMode, hideFilterButton: true }), h("ez-tooltip", { message: (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage("snkCrud.customButtons.filter") }, h("ez-button", { mode: "icon", iconName: "filter", onClick: () => this._snkFilterBar.showFilterModal(), size: "small" }))), h("snk-taskbar", { "data-element-id": "grid_top", key: "topTaskbar", configName: this.configName, dataUnit: this._dataUnit, messagesBuilder: this.messagesBuilder, buttons: this._topTaskbarProcessor.buttons, disabledButtons: this._topTaskbarProcessor.disabledButtons, customButtons: this._topTaskbarProcessor.customButtons, primaryButton: this.getPrimaryButton(), resourceID: this.resourceID, customContainerId: this.taskbarCustomContainerId, customSlotId: this.topTaskbarCustomSlotId, overflowStrategy: 'none', actionsSettingsList: this.getActionsSettingsList() }, h("slot", { name: this.topTaskbarCustomSlotId }))), h("ez-grid", { ref: ref => this._grid = ref, class: (this.presentationMode === PresentationMode.SECONDARY ? 'snk-grid-container__without-shadow ' : '') + 'snk-grid__table', "data-element-id": "embedded", dataUnit: this._dataUnit, key: 'grid-' + this._snkDataUnit.entityName, config: this._gridConfig, onConfigChange: (evt) => {
        this.gridConfigChangeHandler(evt);
      }, onEzColumnFilterChanged: async () => await this.dataExporterProviderStore(), onEzDoubleClick: (evt) => this.gridDoubleClick.emit(evt.detail), statusResolver: this.statusResolver, multipleSelection: this.multipleSelection, columnfilterDataSource: this.columnFilterDataSource, selectionToastConfig: this.selectionToastConfig, useEnterLikeTab: this.useEnterLikeTab, recordsValidator: this.recordsValidator, canEdit: this.canEdit, autoFocus: this.autoFocus, enableGridInsert: this.enableGridInsert, enableContinuousInsert: this._enableContinuousInsert, enableLockManagerTaskbarClick: this.enableLockManagerTaskbarClick, enableLockManagerLoadingComp: this.enableLockManagerLoadingComp, outlineMode: this.outlineMode, useSearchColumn: this.useSearchColumn, suppressHorizontalScroll: this.suppressHorizontalScroll, paginationCounterMode: this.paginationCounterMode, suppressCheckboxColumn: this.suppressCheckboxColumn, suppressFilterColumn: this.suppressFilterColumn, compact: this.compact, hidePagination: this.hidePagination }, !this.hideGridTaskbar &&
      h("snk-taskbar", { id: 'teste', dataUnit: this._dataUnit, configName: this.configName, messagesBuilder: this.messagesBuilder, "data-element-id": "grid_left", buttons: this.getGridHeaderButtons(), presentationMode: this.presentationMode, disabledButtons: this._headerTaskbarProcessor.disabledButtons, customButtons: this._headerTaskbarProcessor.customButtons, slot: "leftButtons", actionsList: this.getActionsList(), primaryButton: this.getPrimaryButton(), resourceID: this.resourceID, customContainerId: this.taskbarCustomContainerId, customSlotId: this.gridHeaderCustomSlotId, additionalSlotId: this.gridHeaderDynamicSearchSlotId, actionsSettingsList: this.getActionsSettingsList() }, h("slot", { name: this.gridHeaderCustomSlotId }), h("slot", { name: this.gridHeaderDynamicSearchSlotId }))), h("div", { class: "ez-col ez-col--sd-12 snk-grid-container__footer" }, h("slot", { name: "SnkGridFooter" })), h("ez-popup", { size: "medium", heightMode: "auto", useHeader: false, opened: this._popUpGridConfig, onEzClosePopup: () => this.closeGridConfig() }, h("snk-grid-config", { ref: ref => this._snkGridConfig = ref, config: this._gridConfig, "data-element-id": this._element.getAttribute(ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME), selectedIndex: 0, configName: this.configName, onConfigChange: (evt) => this.modalConfigChangeHandler(evt), onConfigCancel: () => this.closeGridConfig(), resourceID: this.resourceID, metadata: (_b = this._dataUnit) === null || _b === void 0 ? void 0 : _b.metadata }))));
  }
  get _element() { return this; }
  static get watchers() { return {
    "gridLegacyConfigName": ["handleGridLegacyConfigName"]
  }; }
  static get style() { return snkGridCss; }
}, [6, "snk-grid", {
    "columnFilterDataSource": [1040],
    "enableLockManagerLoadingComp": [4, "enable-lock-manager-loading-comp"],
    "enableLockManagerTaskbarClick": [4, "enable-lock-manager-taskbar-click"],
    "configName": [1, "config-name"],
    "filterBarTitle": [1, "filter-bar-title"],
    "resourceID": [1, "resource-i-d"],
    "selectionToastConfig": [16],
    "actionsList": [16],
    "isDetail": [4, "is-detail"],
    "taskbarManager": [16],
    "statusResolver": [16],
    "multipleSelection": [4, "multiple-selection"],
    "presentationMode": [1, "presentation-mode"],
    "messagesBuilder": [1040],
    "useEnterLikeTab": [4, "use-enter-like-tab"],
    "recordsValidator": [16],
    "canEdit": [4, "can-edit"],
    "taskbarCustomContainerId": [1, "taskbar-custom-container-id"],
    "gridHeaderCustomSlotId": [1, "grid-header-custom-slot-id"],
    "gridHeaderDynamicSearchSlotId": [1, "grid-header-dynamic-search-slot-id"],
    "topTaskbarCustomSlotId": [1, "top-taskbar-custom-slot-id"],
    "disablePersonalizedFilter": [4, "disable-personalized-filter"],
    "gridLegacyConfigName": [1, "grid-legacy-config-name"],
    "filterBarLegacyConfigName": [1, "filter-bar-legacy-config-name"],
    "autoLoad": [4, "auto-load"],
    "autoFocus": [4, "auto-focus"],
    "enableGridInsert": [4, "enable-grid-insert"],
    "outlineMode": [4, "outline-mode"],
    "suppressHorizontalScroll": [4, "suppress-horizontal-scroll"],
    "strategyExporter": [1025, "strategy-exporter"],
    "useSearchColumn": [4, "use-search-column"],
    "multipleEditionEnabled": [4, "multiple-edition-enabled"],
    "paginationCounterMode": [1, "pagination-counter-mode"],
    "suppressCheckboxColumn": [4, "suppress-checkbox-column"],
    "suppressFilterColumn": [1028, "suppress-filter-column"],
    "compact": [4],
    "filterCustomConfig": [16],
    "filterCustomConfigInterceptor": [16],
    "hidePagination": [516, "hide-pagination"],
    "hideHeader": [516, "hide-header"],
    "hideGridTaskbar": [516, "hide-grid-taskbar"],
    "_dataUnit": [32],
    "_dataState": [32],
    "_gridConfig": [32],
    "_popUpGridConfig": [32],
    "_showSnkFilterBar": [32],
    "_enableContinuousInsert": [32],
    "_filterMode": [32],
    "refreshColumnFilterDataSource": [64],
    "reloadConfig": [64],
    "showConfig": [64],
    "hideConfig": [64],
    "setConfig": [64],
    "reloadFilterBar": [64],
    "getFilterBar": [64],
    "addCustomEditor": [64],
    "addGridCustomRender": [64],
    "addCustomValueFormatter": [64],
    "removeCustomValueFormatter": [64],
    "setFocus": [64],
    "handlePageChange": [64],
    "locateColumn": [64],
    "filterColumns": [64]
  }, [[2, "click", "handleClick"]]]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-grid", "snk-actions-button", "snk-data-exporter", "snk-default-filter", "snk-exporter-email-sender", "snk-expression-group", "snk-expression-item", "snk-filter-advanced-mode", "snk-filter-assistent-mode", "snk-filter-bar", "snk-filter-detail", "snk-filter-field-search", "snk-filter-item", "snk-filter-modal", "snk-filter-modal-item", "snk-filter-param-config", "snk-grid-config", "snk-personalized-filter", "snk-select-box", "snk-simple-bar", "snk-taskbar", "snk-taskbar-skeleton", "taskbar-actions-button", "taskbar-split-button"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-grid":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkGrid);
      }
      break;
    case "snk-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$n();
      }
      break;
    case "snk-data-exporter":
      if (!customElements.get(tagName)) {
        defineCustomElement$m();
      }
      break;
    case "snk-default-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$l();
      }
      break;
    case "snk-exporter-email-sender":
      if (!customElements.get(tagName)) {
        defineCustomElement$k();
      }
      break;
    case "snk-expression-group":
      if (!customElements.get(tagName)) {
        defineCustomElement$j();
      }
      break;
    case "snk-expression-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$i();
      }
      break;
    case "snk-filter-advanced-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$h();
      }
      break;
    case "snk-filter-assistent-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$g();
      }
      break;
    case "snk-filter-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$f();
      }
      break;
    case "snk-filter-detail":
      if (!customElements.get(tagName)) {
        defineCustomElement$e();
      }
      break;
    case "snk-filter-field-search":
      if (!customElements.get(tagName)) {
        defineCustomElement$d();
      }
      break;
    case "snk-filter-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$c();
      }
      break;
    case "snk-filter-modal":
      if (!customElements.get(tagName)) {
        defineCustomElement$b();
      }
      break;
    case "snk-filter-modal-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "snk-filter-param-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "snk-grid-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "snk-personalized-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "snk-select-box":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "snk-simple-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "snk-taskbar":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "snk-taskbar-skeleton":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "taskbar-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
    case "taskbar-split-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$1();
      }
      break;
  } });
}

export { SnkGrid as S, defineCustomElement as d };
