import { proxyCustomElement, HTMLElement, createEvent, h, Fragment, forceUpdate, Host } from '@stencil/core/internal/client';
import { ObjectUtils, StringUtils, Action, KeyboardManager, ElementIDUtils } from '@sankhyalabs/core';
import { C as ConfigStorage } from './ConfigStorage.js';
import { F as FormConfigFetcher } from './form-config-fetcher.js';
import { T as TAB_NAMES, V as VIEW_MODE } from './constants.js';
import { buildFormMetadata, FormMetadata } from '@sankhyalabs/ezui/dist/collection/utils/form';
import './DataFetcher.js';
import { P as PresentationMode } from './ISave.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 { T as TaskbarElement, d as defineCustomElement$6 } from './snk-taskbar2.js';
import { buildFieldSearch, SHORTCUT_SEARCH_FIELD } from '@sankhyalabs/ezui/dist/collection/utils';
import { d as defineCustomElement$H } from './snk-actions-button2.js';
import { d as defineCustomElement$G } from './snk-attach2.js';
import { d as defineCustomElement$F } from './snk-configurator2.js';
import { d as defineCustomElement$E } from './snk-data-exporter2.js';
import { d as defineCustomElement$D } from './snk-data-unit2.js';
import { d as defineCustomElement$C } from './snk-default-filter2.js';
import { d as defineCustomElement$B } from './snk-dynaform-config-header2.js';
import { d as defineCustomElement$A } from './snk-dynaform-configs-button2.js';
import { S as SnkMessageBuilder } from './SnkMessageBuilder.js';
import { S as SimpleTaskbarProcessor, D as DEFAULT_TASKBAR_BUTTONS, g as getTopTaskBarId } from './taskbarUtils.js';
import { d as defineCustomElement$u } from './snk-dynaform-form-view2.js';
import { d as defineCustomElement$s } from './snk-exporter-email-sender2.js';
import { d as defineCustomElement$r } from './snk-expression-group2.js';
import { d as defineCustomElement$q } from './snk-expression-item2.js';
import { d as defineCustomElement$p } from './snk-filter-advanced-mode2.js';
import { d as defineCustomElement$o } from './snk-filter-assistent-mode2.js';
import { d as defineCustomElement$n } from './snk-filter-bar2.js';
import { d as defineCustomElement$m } from './snk-filter-detail2.js';
import { d as defineCustomElement$l } from './snk-filter-field-search2.js';
import { d as defineCustomElement$k } from './snk-filter-item2.js';
import { d as defineCustomElement$j } from './snk-filter-modal2.js';
import { d as defineCustomElement$i } from './snk-filter-modal-item2.js';
import { d as defineCustomElement$h } from './snk-filter-param-config2.js';
import { d as defineCustomElement$g } from './snk-grid2.js';
import { d as defineCustomElement$f } from './snk-grid-config2.js';
import { d as defineCustomElement$e } from './snk-image-input2.js';
import { d as defineCustomElement$d } from './snk-layout-form-config2.js';
import { d as defineCustomElement$c } from './snk-numbering-config2.js';
import { d as defineCustomElement$b } from './snk-personalized-filter2.js';
import { d as defineCustomElement$a } from './snk-select-box2.js';
import { d as defineCustomElement$9 } from './snk-simple-bar2.js';
import { d as defineCustomElement$8 } from './snk-simple-crud2.js';
import { d as defineCustomElement$7 } from './snk-simple-form-config2.js';
import { d as defineCustomElement$5 } from './snk-taskbar-skeleton2.js';
import { d as defineCustomElement$4 } from './snk-view-representation2.js';
import { d as defineCustomElement$3 } from './taskbar-actions-button2.js';
import { d as defineCustomElement$2 } from './taskbar-split-button2.js';
import { d as defineCustomElement$z } from './snk-dynaform-field-config2.js';
import { d as defineCustomElement$y } from './snk-dynaform-field-item2.js';
import { d as defineCustomElement$x } from './snk-dynaform-fields-layout2.js';
import { d as defineCustomElement$w } from './snk-dynaform-fields-selector2.js';
import { d as defineCustomElement$v } from './snk-dynaform-form-config2.js';
import { d as defineCustomElement$t } from './snk-dynaform-guides-configurator2.js';

class SnkFormConfigManager {
  constructor(configName, resourceID, onConfigChange, dataUnit) {
    this._resourceID = resourceID;
    this._configName = configName;
    this._onConfigChange = onConfigChange;
    this._dataUnit = dataUnit;
  }
  addFormLegacyConfig(legacyConfigName) {
    if (this._configName) {
      ConfigStorage.addFormLegacyConfig(this._configName, legacyConfigName);
    }
  }
  async loadConfig() {
    return new Promise(resolve => {
      ConfigStorage.loadFormConfig(this._configName, this._resourceID)
        .then((config) => {
        config = this.buildFormMetadataUITabs(config);
        this.setConfig(config);
        resolve(config);
      })
        .catch((error) => {
        console.warn(error);
      });
    });
  }
  getEmptyConfig() {
    return this.buildFormMetadataUITabs({ fields: [], emptyConfig: true }, true);
  }
  saveConfig(config) {
    const configToSave = ObjectUtils.copy(config);
    return new Promise(accept => {
      ConfigStorage.saveFormConfig(config, this._configName, this._resourceID)
        .then((response) => {
        this.setConfig(Object.assign(Object.assign({}, configToSave), response));
        accept(Object.assign(Object.assign({}, configToSave), response));
      });
    });
  }
  saveCardState(cardId, cardConfig, propertyChanged) {
    return new Promise(resolve => {
      var _a;
      const cardsState = ((_a = this._config) === null || _a === void 0 ? void 0 : _a.cardsState) || new Map;
      const currentConfig = cardsState.get(cardId);
      cardsState.set(cardId, propertyChanged === "fixed" ?
        this.updateFixSequence(Object.assign(Object.assign({}, currentConfig), { fixed: cardConfig.fixed }), cardsState)
        : Object.assign(Object.assign({}, currentConfig), { [propertyChanged]: cardConfig[propertyChanged] }));
      ConfigStorage.saveCardState(cardsState, this._configName, this._resourceID)
        .then(savedCardConfig => {
        this._config = Object.assign(Object.assign({}, this._config), { cardsState });
        resolve(savedCardConfig);
      });
    });
  }
  updateFixSequence(updatingCardConfig, cardsState) {
    let maxSequence = -1;
    Array.from(cardsState.values()).forEach(cardConfig => {
      if (!cardConfig.fixed) {
        delete updatingCardConfig.fixSequence;
      }
      if (cardConfig.fixSequence != undefined) {
        maxSequence = Math.max(maxSequence, cardConfig.fixSequence);
      }
    });
    if (updatingCardConfig.fixed) {
      updatingCardConfig.fixSequence = maxSequence + 1;
    }
    else {
      delete updatingCardConfig.fixSequence;
    }
    return updatingCardConfig;
  }
  hasConfig(config) {
    var _a;
    const currentConfig = config !== null && config !== void 0 ? config : this._config;
    if (currentConfig && ((_a = currentConfig.fields) === null || _a === void 0 ? void 0 : _a.length)) {
      return true;
    }
    return false;
  }
  getFieldsList(descriptionFilter, forceEmptyConfig = false) {
    var _a, _b;
    const fields = (_a = this._config) === null || _a === void 0 ? void 0 : _a.fields;
    const hasConfig = this.hasConfig();
    if (hasConfig && !forceEmptyConfig) {
      return fields.map(({ label, name, readOnly, visible, required, tab, group }) => {
        var _a;
        if (label == undefined) {
          const currentField = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.getField(name);
          if (!currentField)
            return;
          return Object.assign(Object.assign({}, currentField), { name: name !== null && name !== void 0 ? name : currentField.name, readOnly: readOnly !== null && readOnly !== void 0 ? readOnly : currentField.readOnly, visible: visible !== null && visible !== void 0 ? visible : currentField.visible, required: required !== null && required !== void 0 ? required : currentField.required, tab: tab, group: group });
        }
        return { name, label, readOnly, visible, required, tab, group };
      })
        .filter(field => this.isFieldVisible(field, descriptionFilter));
    }
    if (!this._dataUnit || !((_b = this._dataUnit.metadata) === null || _b === void 0 ? void 0 : _b.fields)) {
      return [];
    }
    const filteredFields = this._dataUnit.metadata.fields
      .filter(field => this.isFieldVisible(field, descriptionFilter))
      .map(({ label, name, readOnly, visible, required, properties }) => ({ label, name, readOnly, visible, required, tab: properties === null || properties === void 0 ? void 0 : properties.UITabName }));
    return filteredFields;
  }
  isFieldVisible(field, descriptionFilter) {
    if (field === undefined || field.visible === false) {
      return false;
    }
    if (descriptionFilter == undefined) {
      return true;
    }
    const normalizedText = StringUtils.replaceAccentuatedCharsLower((field.label || field.name).toLocaleLowerCase());
    const normalizedFilter = StringUtils.replaceAccentuatedCharsLower(descriptionFilter.toLocaleLowerCase());
    return normalizedText.includes(normalizedFilter);
  }
  getFormConfig(dataUnit, ignoreReadOnlyFormFields, forceEmptyConfig = false) {
    let fields = this.getFieldsList(undefined, forceEmptyConfig);
    if (ignoreReadOnlyFormFields) {
      fields = fields.filter(field => {
        if (dataUnit) {
          const def = dataUnit.getField(field.name);
          if (def && def.readOnly) {
            return false;
          }
        }
        return !field.readOnly;
      });
    }
    return Object.assign(Object.assign({}, this._config), { fields });
  }
  setConfig(config) {
    this.isLoaded = true;
    const { cardsState, summary, defaultVars } = this._config || {};
    this._config = Object.assign({}, config);
    if (cardsState) {
      this._config.cardsState = cardsState;
    }
    if (summary) {
      this._config.summary = summary;
    }
    if (defaultVars) {
      this._config.defaultVars = defaultVars;
    }
    if (this._onConfigChange) {
      this._onConfigChange(Object.assign({}, this._config));
    }
  }
  getConfig(dataUnit, ignoreReadOnlyFormFields) {
    return this.getFormConfig(dataUnit, ignoreReadOnlyFormFields);
  }
  getFormConfigFetcher() {
    if (this._formConfigFetcher == undefined) {
      this._formConfigFetcher = new FormConfigFetcher();
    }
    return this._formConfigFetcher;
  }
  async fetchUserAvailableConfigs() {
    if (this._configName != undefined) {
      //FIXME: Precisamos preparar o backend para retornar as configurações disponíveis para details;
      return Promise.resolve(undefined);
    }
    return this.getFormConfigFetcher().fetchUserAvailableConfigs(this._configName, this._resourceID);
  }
  async fetchLegacyConfig() {
    return this.getFormConfigFetcher().fetchLegacyConfig(this._configName, this._resourceID);
  }
  async fetchDefaultConfig() {
    return this.getFormConfigFetcher().fetchDefaultConfig(this._configName, this._resourceID);
  }
  parseObjectList(object) {
    if (!object) {
      return [];
    }
    return Array.isArray(object) ? object : [object];
  }
  buildFormMetadataUITabs(config, forceEmptyConfig = false) {
    var _a, _b, _c;
    const hasConfig = this.hasConfig(config);
    if (!forceEmptyConfig && (!this._dataUnit || hasConfig)) {
      return config;
    }
    config = this.getFormConfig(this._dataUnit, false, true);
    config.tabs = this.parseObjectList(config.tabs);
    config.emptyConfig = false;
    config.defaultConfiguration = true;
    const fields = (_b = (_a = this._dataUnit.metadata) === null || _a === void 0 ? void 0 : _a.fields) !== null && _b !== void 0 ? _b : [];
    for (const currentField of fields) {
      const field = config.fields.find(field => field.name === currentField.name);
      const uiTabName = (_c = currentField.properties) === null || _c === void 0 ? void 0 : _c.UITabName;
      if (!uiTabName || uiTabName === TAB_NAMES.main) {
        continue;
      }
      const haveTab = config.tabs.some((tab) => tab.label === uiTabName);
      if (!haveTab) {
        config.tabs.push({
          label: uiTabName,
          name: uiTabName,
          order: 0,
          visible: true,
        });
      }
      if (field) {
        field.tab = uiTabName;
      }
    }
    return config;
  }
}

const snkDynaformGuidesViewCss = ".sc-snk-dynaform-guides-view-h{--snk-guides-viewer--space-large:var(--space--large, 24px);--snk-guides-viewer--space-small:var(--space--2xs, 8px);--snk-guides-viewer__header--min-height:68px;--snk-guides-viewer__header--z-index:var(--more-visible, 2);--snk-guides-viewer__header--background-color:var(--background--body, #fafcff);display:block;height:100%;min-width:0;overflow-x:hidden}snk-dynaform-form-view.sc-snk-dynaform-guides-view{width:100%}.snk-guides-viewer.sc-snk-dynaform-guides-view{position:relative;display:flex;flex-direction:column;height:100%;overflow:hidden;padding:0px}.snk-guides-viewer__detail-container.sc-snk-dynaform-guides-view{display:flex;row-gap:24px;flex-direction:column;flex:1.2;min-height:0;overflow:hidden;margin-bottom:var(--space--12, 12px)}.snk-guides-viewer__container.sc-snk-dynaform-guides-view>snk-dynaform-form-view.sc-snk-dynaform-guides-view{flex:1;min-height:0;overflow-y:auto}.snk-guides-viewer__detail-container.sc-snk-dynaform-guides-view>snk-dynaform-form-view.sc-snk-dynaform-guides-view,.snk-guides-viewer__detail-container.sc-snk-dynaform-guides-view>snk-dynaform-detail-view.sc-snk-dynaform-guides-view{flex:1;min-height:0;overflow-y:auto}.snk-guides-viewer__header.sc-snk-dynaform-guides-view{position:sticky;align-items:center;top:0;z-index:var(--snk-guides-viewer__header--z-index);background-color:var(--snk-guides-viewer__header--background-color);padding:var(--snk-guides-viewer--space-small)}.snk-guides-viewer__header-breadcrumb.sc-snk-dynaform-guides-view{width:25%;display:flex}.snk-guides-viewer__header-taskbar.sc-snk-dynaform-guides-view{width:75%}.snk-guides-viewer__container.sc-snk-dynaform-guides-view{display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;overflow:hidden}.snk-guides-viewer__tabselector.sc-snk-dynaform-guides-view{width:100%;min-width:0;box-sizing:border-box;padding:0 var(--space--12, 12px);flex-shrink:0}";

const SnkDynaformGuidesViewer = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.snkMasterFormConfigChange = createEvent(this, "snkMasterFormConfigChange", 7);
    this.formConfigVisibilityChanged = createEvent(this, "formConfigVisibilityChanged", 7);
    this.exit = createEvent(this, "exit", 7);
    this.actionClick = createEvent(this, "actionClick", 7);
    this.formItemsReady = createEvent(this, "formItemsReady", 7);
    this.dataUnit = undefined;
    this.dataState = undefined;
    this.configName = undefined;
    this.entityPath = undefined;
    this.actionsList = undefined;
    this.recordsValidator = undefined;
    this.masterFormConfig = undefined;
    this.selectedGuide = undefined;
    this.taskbarManager = undefined;
    this.messagesBuilder = undefined;
    this.canEdit = true;
    this.presentationMode = undefined;
    this.resourceID = undefined;
    this.detailTaskbarCustomContainerId = undefined;
    this.formLegacyConfigName = undefined;
    this.enableGridInsert = false;
    this.ignoreReadOnlyFormFields = undefined;
    this.getCustomTitle = undefined;
    this.customGuidesConfig = [];
    this._guides = [];
    this._formEditorConfigManager = undefined;
    this._formEditorDataUnit = undefined;
    this._fieldToGetFocus = undefined;
    this._customEditors = {};
    this._customRenders = {};
    this._fieldsProps = {};
    this._mainForm = undefined;
    this._mainFormName = undefined;
    this._errorTabs = new Set();
    this._hasToCreateFieldSearch = true;
  }
  observeDataUnit() {
    this.loadGuides(true);
  }
  async observeFormConfigManager(value) {
    var _a, _b;
    const showFormConfig = !!value;
    await ((_a = this._viewStack) === null || _a === void 0 ? void 0 : _a.show(showFormConfig ?
      GUIDES_VIEWER_VIEW_MODE.CONFIG :
      GUIDES_VIEWER_VIEW_MODE.GUIDES));
    (_b = this.formConfigVisibilityChanged) === null || _b === void 0 ? void 0 : _b.emit(showFormConfig);
  }
  observeDataState(newValue, oldValue) {
    var _a, _b, _c, _d, _e, _f;
    const newRecordsIds = (_b = (_a = newValue === null || newValue === void 0 ? void 0 : newValue.selectionInfo) === null || _a === void 0 ? void 0 : _a.recordIds) !== null && _b !== void 0 ? _b : (_c = newValue === null || newValue === void 0 ? void 0 : newValue.selectedRecord) === null || _c === void 0 ? void 0 : _c['__record__id__'];
    const oldRecordsIds = (_e = (_d = oldValue === null || oldValue === void 0 ? void 0 : oldValue.selectionInfo) === null || _d === void 0 ? void 0 : _d.recordIds) !== null && _e !== void 0 ? _e : (_f = oldValue === null || oldValue === void 0 ? void 0 : oldValue.selectedRecord) === null || _f === void 0 ? void 0 : _f['__record__id__'];
    if (!ObjectUtils.equals(newRecordsIds, oldRecordsIds)) {
      this.loadGuides((oldValue === null || oldValue === void 0 ? void 0 : oldValue.insertionMode) != (newValue === null || newValue === void 0 ? void 0 : newValue.insertionMode));
    }
  }
  observeMasterFormConfig() {
    var _a;
    this.loadGuides(this.noGuideSelected());
    (_a = this.snkMasterFormConfigChange) === null || _a === void 0 ? void 0 : _a.emit(this.masterFormConfig);
  }
  /**
  * Abre o configurador do formulário
  * @param detail - Define se a configuração que está sendo carregada é
  * referente a um form detail.
  */
  async showFormConfig(detail = false) {
    var _a, _b;
    const masterConfig = !detail || this._currentDetail == undefined;
    this._formEditorConfigManager = masterConfig ? this._configManager : (_a = this._currentDetail) === null || _a === void 0 ? void 0 : _a.formConfigManager;
    this._formEditorDataUnit = masterConfig ? this.dataUnit : (_b = this._currentDetail) === null || _b === void 0 ? void 0 : _b.dataUnit;
  }
  /**
   * Registra um editor customizado para campos da grade e formulário
   */
  async addCustomEditor(fieldName, customEditor) {
    this._customEditors = Object.assign(Object.assign({}, this._customEditors), { [fieldName]: customEditor });
  }
  /**
   * Registra um render customizado para colunas da grid.
   */
  async addGridCustomRender(fieldName, customRender) {
    this._customRenders = Object.assign(Object.assign({}, this._customRenders), { [fieldName]: customRender });
  }
  ;
  /**
   * Altera/adiciona uma propriedade nos metadados do campo.
   */
  async setFieldProp(fieldName, propName, value) {
    const newFieldsProps = {
      [fieldName]: Object.assign(Object.assign({}, this._fieldsProps[fieldName]), { [propName]: value })
    };
    this._fieldsProps = Object.assign(Object.assign({}, this._fieldsProps), newFieldsProps);
  }
  /**
   * Atribui o foco para o componente.
   */
  async setFocus() {
    var _a;
    (_a = this._container) === null || _a === void 0 ? void 0 : _a.focus({ preventScroll: true });
  }
  /**
   * Recarrega os guias baseada nos metadados atuais.
   */
  async reloadGuides() {
    this.loadGuides(false);
  }
  exitViewer() {
    var _a, _b;
    if (!this.enableGridInsert && ((_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.isDirty())) {
      this.dataUnit.cancelEdition({ after: () => { var _a; return (_a = this.exit) === null || _a === void 0 ? void 0 : _a.emit(); } });
    }
    else {
      (_b = this.exit) === null || _b === void 0 ? void 0 : _b.emit();
    }
  }
  onActionClick(evt) {
    var _a;
    if (evt.detail === TaskbarElement.CONFIGURATOR) {
      if (evt.target.dataset.taskbarOwner != "master") {
        (_a = this._snkConfigurator) === null || _a === void 0 ? void 0 : _a.open();
        evt.stopImmediatePropagation();
        evt.stopPropagation();
      }
    }
  }
  onContentCardChanged(evt) {
    if (!this._configManager || !this.dataUnit) {
      return;
    }
    SnkDynaformGuidesViewer.updateContentCard(evt.detail.formName, evt.detail.cardConfig, evt.detail.propertyChanged, this._configManager)
      .then(() => { var _a; return this.masterFormConfig = (_a = this._configManager) === null || _a === void 0 ? void 0 : _a.getConfig(this.dataUnit); });
  }
  /**
   * Conforme mecanismo de mensagens, é possível customizar as mensagens dos blocos de construção
   * através de um pequeno modulo na estrutura da aplicação:
   * - Criar um arquivo no seguinte caminho: /messages/appmessages.msg.js.
   * Para conhecer os detalhes do módulo, vide o arquivo neste projeto "/src/lib/message/resources/snk-crud.msg.ts"
   */
  getMessage(key) {
    var _a, _b, _c, _d, _e, _f;
    if ((_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.isMultipleEdition) {
      const selectedRecords = (_c = (_b = this.dataUnit.getSelectionInfo()) === null || _b === void 0 ? void 0 : _b.records) !== null && _c !== void 0 ? _c : [];
      return (_d = this.messagesBuilder) === null || _d === void 0 ? void 0 : _d.getMessage("snkCrud.multipleEdition.editing", { COUNT: selectedRecords.length });
    }
    return (_e = this.messagesBuilder) === null || _e === void 0 ? void 0 : _e.getMessage(key, (_f = this.dataUnit) === null || _f === void 0 ? void 0 : _f.getSelectedRecord());
  }
  loadGuides(changeSelection) {
    var _a;
    if (!this.dataUnit || !this._configManager) {
      return;
    }
    if (!this._configManager.isLoaded) {
      return;
    }
    this._masterFormMetadata = buildFormMetadata(this.masterFormConfig, this.dataUnit, true, this.customGuidesConfig);
    const allSheets = (_a = this._masterFormMetadata) === null || _a === void 0 ? void 0 : _a.getAllSheets();
    if (!allSheets) {
      return;
    }
    const currentRecord = this.dataUnit.getSelectedRecord();
    const disableDetails = this.hasToDisableDetails(currentRecord);
    const guides = [];
    let mainFormName;
    const listSheetsValues = Array.from(allSheets.values());
    listSheetsValues.forEach((sheet) => {
      if (mainFormName == undefined && !this.isDetail(sheet === null || sheet === void 0 ? void 0 : sheet.name) && !sheet.isCustom) {
        mainFormName = sheet === null || sheet === void 0 ? void 0 : sheet.name;
        return;
      }
      const item = { id: sheet === null || sheet === void 0 ? void 0 : sheet.name, label: sheet === null || sheet === void 0 ? void 0 : sheet.label };
      if (this.isDetail(sheet === null || sheet === void 0 ? void 0 : sheet.name) && disableDetails) {
        item.tooltip = this.getMessage("snkCrud.detail.tooltip.needSingleSelection");
        item.disabled = true;
      }
      if (sheet.isCustom && sheet.ctxProps) {
        Object.entries(sheet.ctxProps).forEach(([key, value]) => {
          if (value !== undefined) {
            item[key] = value;
          }
        });
      }
      if (!item.props) {
        item.props = {};
      }
      item.props.isAdditional = sheet.name.includes("AD_");
      item.props.isCustom = !!sheet.isCustom;
      guides.push(item);
    });
    this._mainFormName = mainFormName;
    this._guides = guides;
    if (changeSelection) {
      this.selectedGuide = this._guides && this._guides.length > 0 ? this._guides[0] : undefined;
    }
  }
  hasToDisableDetails(currentRecord) {
    return !currentRecord
      || !this.dataUnit
      || this.dataUnit.isNewRecord(currentRecord.__record__id__)
      || this.dataUnit.isMultipleEdition;
  }
  isDetail(formId) {
    return FormMetadata.getDetailName(formId) != undefined;
  }
  buildTabItems() {
    return this._guides.map((guide, index) => ({
      tabKey: guide.id,
      label: guide.label,
      index,
      disabled: guide.disabled,
      rightIcon: this._errorTabs.has(guide.id) ? 'alert-circle-inverted' : undefined,
      leftIcon: this.getTabLeftIcon(guide),
    }));
  }
  getTabLeftIcon(guide) {
    var _a, _b;
    if (guide.icon) {
      return guide.icon;
    }
    if ((_a = guide.props) === null || _a === void 0 ? void 0 : _a.isCustom) {
      return 'puzzle-piece';
    }
    if ((_b = guide.props) === null || _b === void 0 ? void 0 : _b.isAdditional) {
      return 'puzzle-piece';
    }
    return undefined;
  }
  isCustomGuide(guideId) {
    var _a;
    if (!guideId) {
      return false;
    }
    return !!((_a = this.customGuidesConfig) === null || _a === void 0 ? void 0 : _a.some(g => g.id === guideId));
  }
  onTabChange(tab) {
    const targetGuide = this._guides.find(g => g.id === tab.tabKey);
    if (!targetGuide || targetGuide.disabled) {
      return;
    }
    this.selectedGuide = targetGuide;
  }
  static updateContentCard(formName, cardConfig, propertyChanged, configManager) {
    return configManager.saveCardState(formName, cardConfig, propertyChanged);
  }
  static buildMainForm(params) {
    if (params.formMetadata == undefined || params.mainFormName == undefined) {
      return undefined;
    }
    const mainSheet = params.formMetadata.getSheet(params.mainFormName);
    if (mainSheet == undefined) {
      return undefined;
    }
    return (h("snk-dynaform-form-view", { ref: (ref) => { var _a; return (_a = params.onMainFormRef) === null || _a === void 0 ? void 0 : _a.call(params, ref); }, label: mainSheet.label, name: params.mainFormName, fields: mainSheet.fields, formMetadata: params.formMetadata, dataUnit: params.dataUnit, recordsValidator: params.recordsValidator, fieldToFocus: params.fieldToFocus, key: params.mainFormName, onSnkRequestClearFieldToFocus: _ => { var _a; return (_a = params.onRequestClearFieldToFocus) === null || _a === void 0 ? void 0 : _a.call(params); }, customEditors: params.propsCustomEditor, fieldsProps: params.fieldsProps, entityPath: params.entityPath, fieldSearch: params.fieldSearch }));
  }
  static buildFixedForms(params) {
    var _a;
    const cardsState = (_a = params.formConfig) === null || _a === void 0 ? void 0 : _a.cardsState;
    if (cardsState == undefined || params.formMetadata == undefined) {
      return undefined;
    }
    const fixedEntries = Array.from(cardsState.entries())
      .filter(([formName, cardConfig]) => (cardConfig === null || cardConfig === void 0 ? void 0 : cardConfig.fixed) && formName != params.selectedForm && formName != params.mainFormName)
      .sort(([, cardConfigA], [, cardConfigB]) => {
      const indexA = (cardConfigA === null || cardConfigA === void 0 ? void 0 : cardConfigA.fixSequence) || 0;
      const indexB = (cardConfigB === null || cardConfigB === void 0 ? void 0 : cardConfigB.fixSequence) || 0;
      return indexA - indexB;
    });
    if (fixedEntries.length === 0) {
      return undefined;
    }
    return (h(Fragment, null, fixedEntries.map(([formName]) => {
      const sheet = params.formMetadata.getSheet(formName);
      if (sheet == undefined) {
        return undefined;
      }
      return h("snk-dynaform-form-view", { label: sheet.label, name: formName, fields: sheet.fields, formMetadata: params.formMetadata, dataUnit: params.dataUnit, recordsValidator: params.recordsValidator, fieldToFocus: params.fieldToFocus, key: formName, onSnkRequestClearFieldToFocus: _ => { var _a; return (_a = params.onRequestClearFieldToFocus) === null || _a === void 0 ? void 0 : _a.call(params); }, customEditors: params.propsCustomEditor, fieldsProps: params.fieldsProps, entityPath: params.entityPath });
    })));
  }
  getContent() {
    var _a;
    if (!this.selectedGuide) {
      return undefined;
    }
    const guideId = this.selectedGuide.id;
    if (this.isCustomGuide(guideId)) {
      return h("slot", { name: guideId });
    }
    const childEntityName = FormMetadata.getDetailName(guideId);
    if (childEntityName) {
      return (h("snk-dynaform-detail-view", { ref: (ref) => {
          if (ref)
            this._currentDetail = ref;
        }, dataUnitName: `${this.entityPath}/${childEntityName}`, entityName: childEntityName, label: this.selectedGuide.label, key: `detail_${guideId}`, canEdit: this.canEdit, resourceID: this.resourceID, taskbarCustomContainerId: this.detailTaskbarCustomContainerId, customEditors: this._customEditors, customRenders: this._customRenders, presentationMode: this.presentationMode, messagesBuilder: this.messagesBuilder }));
    }
    if (guideId === this._mainFormName) {
      return undefined;
    }
    const sheet = (_a = this._masterFormMetadata) === null || _a === void 0 ? void 0 : _a.getSheet(guideId);
    if (!sheet) {
      return undefined;
    }
    return (h("snk-dynaform-form-view", { name: guideId, label: sheet.label, fields: sheet.fields, dataUnit: this.dataUnit, formMetadata: this._masterFormMetadata, recordsValidator: this.recordsValidator, fieldToFocus: this._fieldToGetFocus, key: guideId, onSnkRequestClearFieldToFocus: _ => this.clearFieldToFocusHandler(), customEditors: this._customEditors, fieldsProps: this._fieldsProps, fieldSearch: this._fieldSearch, entityPath: this.entityPath }));
  }
  clearFieldToFocusHandler() {
    this._fieldToGetFocus = undefined;
  }
  getConfigViewMode() {
    return VIEW_MODE.GRID;
  }
  changeConfigViewMode(mode) {
    var _a, _b;
    if (this._currentDetail) {
      (_b = (_a = this._currentDetail).changeViewMode) === null || _b === void 0 ? void 0 : _b.call(_a, mode);
    }
  }
  openConfig(mode) {
    var _a, _b, _c, _d;
    (_b = (_a = this._snkConfigurator) === null || _a === void 0 ? void 0 : _a.close) === null || _b === void 0 ? void 0 : _b.call(_a);
    if (this._currentDetail) {
      if (mode === VIEW_MODE.FORM) {
        this.showFormConfig(true);
      }
      else {
        (_d = (_c = this._currentDetail).configGrid) === null || _d === void 0 ? void 0 : _d.call(_c);
      }
    }
  }
  noGuideSelected() {
    var _a;
    return this.selectedGuide === undefined || '__main' === ((_a = this.selectedGuide) === null || _a === void 0 ? void 0 : _a.id);
  }
  addFormLegacyConfigName() {
    var _a;
    if (this.formLegacyConfigName) {
      (_a = this._configManager) === null || _a === void 0 ? void 0 : _a.addFormLegacyConfig(this.formLegacyConfigName);
    }
  }
  setMasterFormConfig(config) {
    this.masterFormConfig = config;
  }
  componentWillLoad() {
    var _a;
    if (this.resourceID == undefined) {
      throw new Error((_a = this.getMessage("snkCrud.errors.resourceIDNotProvided")) !== null && _a !== void 0 ? _a : "");
    }
    this._configManager = new SnkFormConfigManager(this.configName, this.resourceID, this.setMasterFormConfig.bind(this), this.dataUnit);
    this.addFormLegacyConfigName();
    this._configManager.loadConfig();
  }
  async dataUnitActionHandler(action) {
    var _a, _b;
    switch (action.type) {
      case Action.EDITION_CANCELED:
      case Action.DATA_SAVED:
        if ((_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.isMultipleEdition) {
          this.exitViewer();
          if (this.dataUnit) {
            this.dataUnit.isMultipleEdition = false;
          }
        }
        break;
      case Action.FIELD_INVALIDATED:
        const guideName = this.getGuideName((_b = action.payload) === null || _b === void 0 ? void 0 : _b.fieldName);
        if (guideName) {
          this._errorTabs = new Set([...this._errorTabs, guideName]);
        }
        break;
      case Action.METADATA_LOADED:
      case Action.MULTIPLE_EDITION_CHANGED:
        this.loadGuides(this.noGuideSelected());
        break;
    }
  }
  getGuideName(fieldName) {
    var _a, _b;
    const sheets = (_a = this._masterFormMetadata) === null || _a === void 0 ? void 0 : _a.getAllSheets();
    if (!sheets) {
      return "";
    }
    for (const sheet of sheets) {
      const formFields = (_b = sheet[1]) === null || _b === void 0 ? void 0 : _b.fields;
      if (!formFields)
        continue;
      for (const field of formFields) {
        if (field.name === fieldName) {
          return sheet[0];
        }
      }
    }
    return "";
  }
  getTitle() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this.getCustomTitle) === null || _a === void 0 ? void 0 : _a.call(this)) !== null && _b !== void 0 ? _b : this.getMessage("snkCrud.title")) !== null && _c !== void 0 ? _c : "";
  }
  getTitleTooltip() {
    var _a;
    if (!((_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.isMultipleEdition))
      return undefined;
    return this.buildRecordIdsArray();
  }
  buildRecordIdsArray() {
    var _a, _b, _c;
    const selectedRecords = (_c = (_b = (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getSelectionInfo()) === null || _b === void 0 ? void 0 : _b.records) !== null && _c !== void 0 ? _c : [];
    if (selectedRecords.length === 0) {
      return "[]";
    }
    const labels = selectedRecords.map(record => { var _a; return (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage("snkCrud.title", record); });
    return `[${labels.join(", ")}]`;
  }
  getFieldsSearch() {
    var _a;
    if (this._fieldSearch == undefined || this._hasToCreateFieldSearch) {
      this._hasToCreateFieldSearch = false;
      const item = {
        label: (_a = this.getMessage("snkSimpleCrud.findFields")) !== null && _a !== void 0 ? _a : "Busca de campos",
        value: "findFields",
      };
      this._fieldSearch = buildFieldSearch(item, ({ argument }) => this.fieldsOptionLoader(argument), (option) => this.onSelectField(option));
    }
    return this._fieldSearch;
  }
  fieldsOptionLoader(argument) {
    var _a, _b;
    return Promise.resolve((_b = (_a = this._configManager) === null || _a === void 0 ? void 0 : _a.getFieldsList(argument).map(field => ({ value: field.name, label: field.label }))) !== null && _b !== void 0 ? _b : []);
  }
  onSelectField(option) {
    var _a, _b, _c;
    if (option == undefined) {
      return;
    }
    this._fieldToGetFocus = option.value;
    const fieldGuideName = this.getGuideName(option.value);
    if (!fieldGuideName) {
      return;
    }
    if (fieldGuideName === this._mainFormName) {
      (_b = (_a = this._mainForm) === null || _a === void 0 ? void 0 : _a.showUp) === null || _b === void 0 ? void 0 : _b.call(_a);
      return;
    }
    if (fieldGuideName !== ((_c = this.selectedGuide) === null || _c === void 0 ? void 0 : _c.id)) {
      const targetGuide = this._guides.find(g => g.id === fieldGuideName);
      if (targetGuide && !targetGuide.disabled) {
        this.selectedGuide = targetGuide;
      }
    }
  }
  componentDidLoad() {
    var _a;
    (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.subscribe(this.dataUnitActionHandler.bind(this));
    this.initKeyboardManager();
    this.getFieldsSearch();
  }
  disconnectedCallback() {
    var _a;
    (_a = this._keyboardManager) === null || _a === void 0 ? void 0 : _a.unbindAllShortcutKeys();
  }
  async initKeyboardManager() {
    this._keyboardManager = new KeyboardManager({ propagate: false, element: this._element });
    if (this._keyboardManager) {
      this._keyboardManager.bind(SHORTCUT_SEARCH_FIELD, async () => {
        var _a, _b;
        if (!this._mainForm)
          return;
        await ((_b = (_a = this._mainForm).showSearchField) === null || _b === void 0 ? void 0 : _b.call(_a));
      }, { description: this.getMessage("snkSimpleCrud.findFields"), element: this._element });
    }
  }
  render() {
    var _a, _b, _c;
    if (this._formEditorConfigManager != undefined) {
      return (h("snk-dynaform-form-config", { ref: (ref) => {
          if (ref)
            this._container = ref;
        }, tabindex: -1, dataUnit: this._formEditorDataUnit, messagesBuilder: this.messagesBuilder, configManager: this._formEditorConfigManager, onConfigClose: () => this._formEditorConfigManager = undefined }));
    }
    if (!this.dataUnit || !((_a = this._configManager) === null || _a === void 0 ? void 0 : _a.isLoaded)) {
      return undefined;
    }
    const showTabs = this._guides && this._guides.length > 0;
    const fixedFormsParams = {
      formConfig: this.masterFormConfig,
      formMetadata: this._masterFormMetadata,
      selectedForm: (_b = this.selectedGuide) === null || _b === void 0 ? void 0 : _b.id,
      mainFormName: this._mainFormName,
      dataUnit: this.dataUnit,
      recordsValidator: this.recordsValidator,
      fieldToFocus: this._fieldToGetFocus,
      onRequestClearFieldToFocus: this.clearFieldToFocusHandler.bind(this),
      propsCustomEditor: this._customEditors,
      fieldsProps: this._fieldsProps,
      entityPath: this.entityPath,
      fieldSearch: this._fieldSearch,
      onMainFormRef: (ref) => { this._mainForm = ref; }
    };
    return (h("section", { class: "snk-guides-viewer", ref: (ref) => {
        if (ref)
          this._container = ref;
      }, tabindex: -1 }, this.getTitle() && (h("div", { class: "ez-row snk-guides-viewer__header" }, h("div", { class: "snk-guides-viewer__header-breadcrumb ez-flex--align-items-center ez-flex-item--align-center", key: "header" }, h("div", { class: "ez-flex ez-flex--column ez-flex-item--auto" }, h("h1", { class: "ez-title ez-title--primary ez-title--xlarge", title: this.getTitleTooltip() }, this.getTitle()))))), h("div", { class: "snk-guides-viewer__container" }, SnkDynaformGuidesViewer.buildMainForm(fixedFormsParams), showTabs &&
      h("ez-tabselector", Object.assign({ class: "snk-guides-viewer__tabselector", tabs: this.buildTabItems(), selectedTab: (_c = this.selectedGuide) === null || _c === void 0 ? void 0 : _c.id, onEzChange: (evt) => this.onTabChange(evt.detail) }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `${ElementIDUtils.getInternalIDInfo("tabselector")}` })), h("div", { class: "snk-guides-viewer__detail-container" }, SnkDynaformGuidesViewer.buildFixedForms(fixedFormsParams), this.getContent())), h("snk-configurator", { ref: (ref) => {
        if (ref)
          this._snkConfigurator = ref;
      }, viewMode: this.getConfigViewMode(), onConfigSelected: (evt) => this.changeConfigViewMode(evt.detail), messagesBuilder: this.messagesBuilder, onOpenConfig: (evt) => this.openConfig(evt.detail), resourceID: this.resourceID })));
  }
  get _element() { return this; }
  static get watchers() { return {
    "dataUnit": ["observeDataUnit"],
    "_formEditorConfigManager": ["observeFormConfigManager"],
    "dataState": ["observeDataState"],
    "masterFormConfig": ["observeMasterFormConfig"]
  }; }
  static get style() { return snkDynaformGuidesViewCss; }
}, [6, "snk-dynaform-guides-view", {
    "dataUnit": [16],
    "dataState": [16],
    "configName": [1, "config-name"],
    "entityPath": [1, "entity-path"],
    "actionsList": [16],
    "recordsValidator": [16],
    "masterFormConfig": [1040],
    "selectedGuide": [1040],
    "taskbarManager": [16],
    "messagesBuilder": [1040],
    "canEdit": [4, "can-edit"],
    "presentationMode": [1, "presentation-mode"],
    "resourceID": [1, "resource-i-d"],
    "detailTaskbarCustomContainerId": [1, "detail-taskbar-custom-container-id"],
    "formLegacyConfigName": [1, "form-legacy-config-name"],
    "enableGridInsert": [4, "enable-grid-insert"],
    "ignoreReadOnlyFormFields": [4, "ignore-read-only-form-fields"],
    "getCustomTitle": [16],
    "customGuidesConfig": [16],
    "_guides": [32],
    "_formEditorConfigManager": [32],
    "_formEditorDataUnit": [32],
    "_fieldToGetFocus": [32],
    "_customEditors": [32],
    "_customRenders": [32],
    "_fieldsProps": [32],
    "_mainForm": [32],
    "_mainFormName": [32],
    "_errorTabs": [32],
    "_hasToCreateFieldSearch": [32],
    "showFormConfig": [64],
    "addCustomEditor": [64],
    "addGridCustomRender": [64],
    "setFieldProp": [64],
    "setFocus": [64],
    "reloadGuides": [64]
  }, [[2, "actionClick", "onActionClick"], [0, "snkContentCardChanged", "onContentCardChanged"]]]);
var GUIDES_VIEWER_VIEW_MODE;
(function (GUIDES_VIEWER_VIEW_MODE) {
  GUIDES_VIEWER_VIEW_MODE[GUIDES_VIEWER_VIEW_MODE["GUIDES"] = 0] = "GUIDES";
  GUIDES_VIEWER_VIEW_MODE[GUIDES_VIEWER_VIEW_MODE["CONFIG"] = 1] = "CONFIG";
})(GUIDES_VIEWER_VIEW_MODE || (GUIDES_VIEWER_VIEW_MODE = {}));
function defineCustomElement$1() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-dynaform-guides-view", "snk-actions-button", "snk-attach", "snk-configurator", "snk-data-exporter", "snk-data-unit", "snk-default-filter", "snk-dynaform-config-header", "snk-dynaform-configs-button", "snk-dynaform-detail-view", "snk-dynaform-field-config", "snk-dynaform-field-item", "snk-dynaform-fields-layout", "snk-dynaform-fields-selector", "snk-dynaform-form-config", "snk-dynaform-form-view", "snk-dynaform-guides-configurator", "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", "snk-grid-config", "snk-image-input", "snk-layout-form-config", "snk-numbering-config", "snk-personalized-filter", "snk-select-box", "snk-simple-bar", "snk-simple-crud", "snk-simple-form-config", "snk-taskbar", "snk-taskbar-skeleton", "snk-view-representation", "taskbar-actions-button", "taskbar-split-button"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-dynaform-guides-view":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkDynaformGuidesViewer);
      }
      break;
    case "snk-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$H();
      }
      break;
    case "snk-attach":
      if (!customElements.get(tagName)) {
        defineCustomElement$G();
      }
      break;
    case "snk-configurator":
      if (!customElements.get(tagName)) {
        defineCustomElement$F();
      }
      break;
    case "snk-data-exporter":
      if (!customElements.get(tagName)) {
        defineCustomElement$E();
      }
      break;
    case "snk-data-unit":
      if (!customElements.get(tagName)) {
        defineCustomElement$D();
      }
      break;
    case "snk-default-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$C();
      }
      break;
    case "snk-dynaform-config-header":
      if (!customElements.get(tagName)) {
        defineCustomElement$B();
      }
      break;
    case "snk-dynaform-configs-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$A();
      }
      break;
    case "snk-dynaform-detail-view":
      if (!customElements.get(tagName)) {
        defineCustomElement();
      }
      break;
    case "snk-dynaform-field-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$z();
      }
      break;
    case "snk-dynaform-field-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$y();
      }
      break;
    case "snk-dynaform-fields-layout":
      if (!customElements.get(tagName)) {
        defineCustomElement$x();
      }
      break;
    case "snk-dynaform-fields-selector":
      if (!customElements.get(tagName)) {
        defineCustomElement$w();
      }
      break;
    case "snk-dynaform-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$v();
      }
      break;
    case "snk-dynaform-form-view":
      if (!customElements.get(tagName)) {
        defineCustomElement$u();
      }
      break;
    case "snk-dynaform-guides-configurator":
      if (!customElements.get(tagName)) {
        defineCustomElement$t();
      }
      break;
    case "snk-exporter-email-sender":
      if (!customElements.get(tagName)) {
        defineCustomElement$s();
      }
      break;
    case "snk-expression-group":
      if (!customElements.get(tagName)) {
        defineCustomElement$r();
      }
      break;
    case "snk-expression-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$q();
      }
      break;
    case "snk-filter-advanced-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$p();
      }
      break;
    case "snk-filter-assistent-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$o();
      }
      break;
    case "snk-filter-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$n();
      }
      break;
    case "snk-filter-detail":
      if (!customElements.get(tagName)) {
        defineCustomElement$m();
      }
      break;
    case "snk-filter-field-search":
      if (!customElements.get(tagName)) {
        defineCustomElement$l();
      }
      break;
    case "snk-filter-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$k();
      }
      break;
    case "snk-filter-modal":
      if (!customElements.get(tagName)) {
        defineCustomElement$j();
      }
      break;
    case "snk-filter-modal-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$i();
      }
      break;
    case "snk-filter-param-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$h();
      }
      break;
    case "snk-grid":
      if (!customElements.get(tagName)) {
        defineCustomElement$g();
      }
      break;
    case "snk-grid-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$f();
      }
      break;
    case "snk-image-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$e();
      }
      break;
    case "snk-layout-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$d();
      }
      break;
    case "snk-numbering-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$c();
      }
      break;
    case "snk-personalized-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$b();
      }
      break;
    case "snk-select-box":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "snk-simple-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "snk-simple-crud":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "snk-simple-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "snk-taskbar":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "snk-taskbar-skeleton":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "snk-view-representation":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "taskbar-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "taskbar-split-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
  } });
}

const snkDynaformDetailViewCss = ".sc-snk-dynaform-detail-view-h{display:flex;row-gap:24px;flex-direction:column;width:100%;height:100%;overflow:hidden}.level-path.sc-snk-dynaform-detail-view{color:var(--color--title-primary, #2B3A54);font-weight:var(--text-weight--medium, 400);padding-right:3px}.grid-container.sc-snk-dynaform-detail-view{min-height:100px;height:100%;width:100%;display:flex;flex-wrap:wrap;text-decoration:none;border-radius:var(--border--radius-medium);background-color:var(--color--gray-70, #FFFFFF);border:1px solid var(--color--petroleum-100, #C8CCD3)}.detail-header.sc-snk-dynaform-detail-view{padding-bottom:0}snk-data-unit.sc-snk-dynaform-detail-view{flex:1;gap:var(--space--12, 12px);display:flex;flex-direction:column}snk-grid.sc-snk-dynaform-detail-view{height:100%;--snk-grid-margin:0px;--snk-grid-box-shadow:none}.form-and-detail-container.sc-snk-dynaform-detail-view{display:flex;flex-direction:column;height:100%;width:100%;overflow:auto;padding:var(--space--12, 12px)}.ez-tabselector-internal.sc-snk-dynaform-detail-view{margin:var(--space--8, 8px) 0}.selected-record-header.sc-snk-dynaform-detail-view{display:flex;align-items:center;flex-wrap:wrap;gap:var(--space--8, 8px) var(--space--12, 12px);padding:var(--space--12, 12px) var(--space--16, 16px);margin-bottom:var(--space--12, 12px);background:var(--color--gray-80, #F9F9F9);border-radius:var(--border--radius-12, 12px);font-family:var(--font--pattern);border:1px solid var(--color--petroleum-100, #C8CCD3);border-left:4px solid var(--color--ocean-green-500, #00B07E)}.selected-record-header--message.sc-snk-dynaform-detail-view{border-left-color:var(--color--primary, #007EFF)}.selected-record-header__message.sc-snk-dynaform-detail-view{font-size:var(--font-size--default, 14px);font-weight:var(--font-weight--medium, 500);color:var(--color--title-primary, #2B3A54)}.selected-record-header__chip.sc-snk-dynaform-detail-view{display:inline-flex;flex-direction:row;align-items:center;gap:var(--space--4, 4px);min-width:0}.selected-record-header__label.sc-snk-dynaform-detail-view{font-size:var(--font-size--xs, 11px);font-weight:var(--font-weight--medium, 500);text-transform:uppercase;letter-spacing:0.04em;color:var(--color--text-secondary, #6E7A8A)}.selected-record-header__value.sc-snk-dynaform-detail-view{font-size:var(--font-size--md, 15px);font-weight:var(--font-weight--semibold, 600);color:var(--color--ocean-green-1000, #00281D);line-height:1.2;word-break:break-word}.selected-record-header__separator.sc-snk-dynaform-detail-view{display:inline-block;align-self:stretch;width:1px;background:var(--color--petroleum-100, #C8CCD3);margin:0 var(--space--4, 4px)}";

var __rest = (undefined && undefined.__rest) || function (s, e) {
  var t = {};
  for (var p in s)
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
const SnkDynaformDetailView = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this._taskbarProcessor = new SimpleTaskbarProcessor(DEFAULT_TASKBAR_BUTTONS);
    this._currentView = 0;
    this.attachmentRegisterKey = undefined;
    this._fieldToGetFocus = undefined;
    this._hasToCreateFieldSearch = true;
    this._selectedSheet = undefined;
    this._selectedUITab = undefined;
    this._internalErrorTabs = new Set();
    this._selectedRecordPKDisplay = undefined;
    this.formConfigManager = undefined;
    this.dataUnitName = undefined;
    this.resourceID = undefined;
    this.entityName = undefined;
    this.label = undefined;
    this.dataUnit = undefined;
    this.selectedForm = undefined;
    this.dataState = undefined;
    this.messagesBuilder = undefined;
    this.canEdit = true;
    this.taskbarCustomContainerId = undefined;
    this.customEditors = undefined;
    this.customRenders = undefined;
    this.presentationMode = PresentationMode.SECONDARY;
  }
  observeDataUnit(newDataUnit, oldDataUnit) {
    newDataUnit === null || newDataUnit === void 0 ? void 0 : newDataUnit.subscribe(this.dataUnitActionHandler.bind(this));
    oldDataUnit === null || oldDataUnit === void 0 ? void 0 : oldDataUnit.unsubscribe(this.dataUnitActionHandler);
  }
  observerDataState(newValue, oldValue) {
    const openInsertion = !(oldValue === null || oldValue === void 0 ? void 0 : oldValue.insertionMode) && (newValue === null || newValue === void 0 ? void 0 : newValue.insertionMode);
    const closeInsertion = (oldValue === null || oldValue === void 0 ? void 0 : oldValue.insertionMode) && !(newValue === null || newValue === void 0 ? void 0 : newValue.insertionMode);
    if (openInsertion || closeInsertion) {
      this.loadMetadata();
    }
    if (this._formMetadata == undefined) {
      return;
    }
    if (!this.selectedSheetIsDetail()) {
      if (openInsertion) {
        setTimeout(() => {
          this.changeViewMode(VIEW_MODE.FORM);
        }, 0);
      }
      if (closeInsertion) {
        this.changeViewMode(VIEW_MODE.GRID);
      }
    }
  }
  /**
  * Muda o modo de visualização do componente entre VIEW_MODE.GRID e VIEW_MODE.FORM
  * @param mode - Novo modo que o componente deve ser apresentado.
  */
  async changeViewMode(mode) {
    if (!this._viewStack) {
      return;
    }
    this._viewStack.show(mode);
    this._currentView = mode;
  }
  /**
   * Abre o configurador de grid.
   */
  async configGrid() {
    if (this._snkGrid) {
      this._snkGrid.showConfig();
    }
  }
  async showUp() {
    if (this._snkFormView) {
      this._snkFormView.showUp();
    }
    if (this._snkGrid) {
      this._snkGrid.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  }
  /**
   * Registra um editor customizado para campos da grade e formulário.
   */
  async addCustomEditor(fieldName, customEditor) {
    var _a, _b;
    const detailContext = this.normalizeDataUnitName();
    (_a = this._snkGrid) === null || _a === void 0 ? void 0 : _a.addCustomEditor(fieldName, customEditor, detailContext);
    (_b = this._snkFormView) === null || _b === void 0 ? void 0 : _b.addCustomEditor(fieldName, customEditor, detailContext);
  }
  async observerPropsCustomEditor(newValue) {
    for (const fieldName in newValue) {
      await this.addCustomEditor(fieldName, newValue[fieldName]);
    }
  }
  /**
   * Registra um render customizado para colunas da grid.
   */
  async addGridCustomRender(fieldName, customRender) {
    var _a;
    const detailContext = this.normalizeDataUnitName();
    await ((_a = this._snkGrid) === null || _a === void 0 ? void 0 : _a.addGridCustomRender(fieldName, customRender, detailContext));
  }
  onContentCardChanged(evt) {
    SnkDynaformGuidesViewer.updateContentCard(evt.detail.formName, evt.detail.cardConfig, evt.detail.propertyChanged, this.formConfigManager).then(() => forceUpdate(this));
    evt.stopPropagation();
  }
  async observeCustomRenders(newValue) {
    for (const field in newValue) {
      const customRender = newValue[field];
      await this.addGridCustomRender(field, customRender);
    }
  }
  loadMetadata() {
    if (!this.dataUnit || !this.formConfigManager) {
      return;
    }
    if (!this.formConfigManager.isLoaded) {
      return;
    }
    const formConfig = this.formConfigManager.getConfig(this.dataUnit);
    this._formMetadata = buildFormMetadata(formConfig == undefined || formConfig.fields.length === 0 ? undefined : formConfig, this.dataUnit, true);
    this.initSelectedSheet();
  }
  initSelectedSheet() {
    if (!this._formMetadata) {
      return;
    }
    const sheets = this._formMetadata.getAllSheets();
    if (!sheets || sheets.size === 0) {
      this._selectedSheet = undefined;
      return;
    }
    const mainSheet = sheets.get(SnkDynaformDetailView.MAIN_TAB);
    const firstUITab = mainSheet === null || mainSheet === void 0 ? void 0 : mainSheet.fields.map((f) => { var _a; return (_a = f.props) === null || _a === void 0 ? void 0 : _a.UITabName; }).find((name) => !!name);
    if (!this._selectedUITab && !firstUITab) {
      this._selectedUITab = SnkDynaformDetailView.MAIN_TAB;
    }
    if (!this._selectedUITab && firstUITab) {
      this._selectedUITab = firstUITab;
    }
    this._selectedSheet = mainSheet;
  }
  dataUnitReadyHandler(evt) {
    this.dataUnit = evt.detail;
    this.loadMetadata();
  }
  getFormFields() {
    var _a, _b, _c;
    const mainSheet = (_b = (_a = this._formMetadata) === null || _a === void 0 ? void 0 : _a.getAllSheets()) === null || _b === void 0 ? void 0 : _b.get(SnkDynaformDetailView.MAIN_TAB);
    const allMainFields = (_c = mainSheet === null || mainSheet === void 0 ? void 0 : mainSheet.fields) !== null && _c !== void 0 ? _c : [];
    return allMainFields.filter((field) => { var _a; return ((_a = field.props) === null || _a === void 0 ? void 0 : _a.UITabName) === SnkDynaformDetailView.MAIN_TAB; });
  }
  removeUiTabName(fields) {
    return fields.map((field) => {
      var _a;
      if (!((_a = field.props) === null || _a === void 0 ? void 0 : _a.UITabName))
        return field;
      const _b = field.props, restProps = __rest(_b, ["UITabName"]);
      return Object.assign(Object.assign({}, field), { props: restProps });
    });
  }
  getUITabFields() {
    var _a, _b, _c;
    if (!this._selectedUITab)
      return [];
    const mainSheet = (_b = (_a = this._formMetadata) === null || _a === void 0 ? void 0 : _a.getAllSheets()) === null || _b === void 0 ? void 0 : _b.get(SnkDynaformDetailView.MAIN_TAB);
    const allMainFields = (_c = mainSheet === null || mainSheet === void 0 ? void 0 : mainSheet.fields) !== null && _c !== void 0 ? _c : [];
    if (this._selectedUITab === SnkDynaformDetailView.MAIN_TAB) {
      return this.removeUiTabName(allMainFields.filter((field) => { var _a; return !((_a = field.props) === null || _a === void 0 ? void 0 : _a.UITabName); }));
    }
    return this.removeUiTabName(allMainFields.filter((field) => { var _a; return ((_a = field.props) === null || _a === void 0 ? void 0 : _a.UITabName) === this._selectedUITab; }));
  }
  hasMultipleSheets() {
    return true;
  }
  selectedSheetIsDetail() {
    return !!this._selectedSheet && FormMetadata.getDetailName(this._selectedSheet.name) != undefined;
  }
  isSheetDisabled(sheet) {
    var _a;
    if (FormMetadata.getDetailName(sheet.name) == undefined) {
      return false;
    }
    const currentRecord = (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getSelectedRecord();
    if (!currentRecord || !this.dataUnit) {
      return true;
    }
    return this.dataUnit.isNewRecord(currentRecord.__record__id__) || this.dataUnit.isMultipleEdition;
  }
  buildInternalTabItems() {
    var _a, _b, _c;
    if (!this._formMetadata) {
      return [];
    }
    const sheets = Array.from(this._formMetadata.getAllSheets().values());
    const mainTab = sheets.find((tab) => tab.name === SnkDynaformDetailView.MAIN_TAB);
    const distinctUITabs = [
      ...new Set(((_a = mainTab === null || mainTab === void 0 ? void 0 : mainTab.fields) !== null && _a !== void 0 ? _a : [])
        .map((field) => { var _a; return (_a = field.props) === null || _a === void 0 ? void 0 : _a.UITabName; })
        .filter((name) => !!name)),
    ];
    if (!distinctUITabs.length) {
      distinctUITabs.push(SnkDynaformDetailView.MAIN_TAB);
    }
    const mainLabel = (_c = (_b = this._formMetadata.getAllSheets().get(SnkDynaformDetailView.MAIN_TAB)) === null || _b === void 0 ? void 0 : _b.label) !== null && _c !== void 0 ? _c : SnkDynaformDetailView.MAIN_TAB;
    const uiTabItems = distinctUITabs.map((tabName, index) => ({
      label: tabName === SnkDynaformDetailView.MAIN_TAB ? mainLabel : tabName,
      tabKey: tabName,
      index,
    }));
    const detailSheets = sheets.filter((sheet) => sheet.name !== SnkDynaformDetailView.MAIN_TAB);
    const sheetItems = detailSheets.map((sheet, index) => ({
      tabKey: sheet.name,
      label: sheet.label,
      index: index + distinctUITabs.length,
      disabled: this.isSheetDisabled(sheet),
      rightIcon: this._internalErrorTabs.has(sheet.name) ? 'alert-circle-inverted' : undefined,
    }));
    return [...uiTabItems, ...sheetItems];
  }
  onInternalTabChange(tab) {
    var _a;
    const allSheets = (_a = this._formMetadata) === null || _a === void 0 ? void 0 : _a.getAllSheets();
    const matchedSheet = allSheets === null || allSheets === void 0 ? void 0 : allSheets.get(tab.tabKey);
    if (matchedSheet && tab.tabKey !== SnkDynaformDetailView.MAIN_TAB) {
      if (this.isSheetDisabled(matchedSheet)) {
        return;
      }
      this._selectedSheet = matchedSheet;
      this._selectedUITab = undefined;
      return;
    }
    this._selectedUITab = tab.tabKey;
    const mainSheet = allSheets === null || allSheets === void 0 ? void 0 : allSheets.get(SnkDynaformDetailView.MAIN_TAB);
    if (mainSheet) {
      this._selectedSheet = mainSheet;
    }
  }
  executeActionHandler(evt) {
    var _a;
    if (evt.detail === TaskbarElement.GRID_MODE) {
      this.changeViewMode(VIEW_MODE.GRID);
      evt.stopPropagation();
    }
    if (evt.detail === TaskbarElement.UPDATE_MULTIPLE && this.dataUnit) {
      this.dataUnit.isMultipleEdition = true;
      this.changeViewMode(VIEW_MODE.FORM);
      evt.stopPropagation();
    }
    if (evt.detail === TaskbarElement.FORM_MODE || evt.detail === TaskbarElement.UPDATE || evt.detail === TaskbarElement.INSERT) {
      this.changeViewMode(VIEW_MODE.FORM);
      evt.stopPropagation();
    }
    if (evt.detail === TaskbarElement.ATTACH) {
      (_a = this._snkAttach) === null || _a === void 0 ? void 0 : _a.open();
      evt.stopPropagation();
    }
  }
  async getAttachmentRegisterKey() {
    if (!this._snkDataUnit) {
      return;
    }
    const recordCriteria = await this._snkDataUnit.getSelectedRecordsIDsInfo();
    const joinedPrimaryKeys = recordCriteria.map(({ value }) => value).join('_');
    return joinedPrimaryKeys;
  }
  async handleDataStateChange({ detail: dataState }) {
    var _a;
    this.dataState = dataState;
    if (dataState.selectedRecord !== undefined && this._snkDataUnit) {
      this.attachmentRegisterKey = (_a = await this.getAttachmentRegisterKey()) !== null && _a !== void 0 ? _a : undefined;
    }
    this._selectedRecordPKDisplay = this.buildSelectedRecordPKDisplay();
  }
  buildSelectedRecordPKDisplay() {
    var _a, _b, _c, _d, _e, _f, _g;
    if (!this.dataUnit) {
      return undefined;
    }
    if ((_a = this.dataState) === null || _a === void 0 ? void 0 : _a.insertionMode) {
      const message = (_b = this.messagesBuilder) === null || _b === void 0 ? void 0 : _b.getMessage("snkCrud.newRecord");
      return message ? { message } : undefined;
    }
    const selectedRecord = this.dataUnit.getSelectedRecord();
    if (!selectedRecord) {
      return undefined;
    }
    const items = [];
    const fields = (_d = (_c = this.dataUnit.metadata) === null || _c === void 0 ? void 0 : _c.fields) !== null && _d !== void 0 ? _d : [];
    for (const field of fields) {
      if (((_e = field.properties) === null || _e === void 0 ? void 0 : _e.isPrimaryKey) !== "true") {
        continue;
      }
      const rawValue = selectedRecord[field.name];
      const value = (_f = rawValue === null || rawValue === void 0 ? void 0 : rawValue.value) !== null && _f !== void 0 ? _f : rawValue;
      if (value === undefined || value === null || value === "") {
        continue;
      }
      items.push({ label: (_g = field.label) !== null && _g !== void 0 ? _g : field.name, value: String(value) });
    }
    return items.length ? { items } : undefined;
  }
  renderSelectedRecordHeader() {
    var _a;
    if (!this.label && !this._selectedRecordPKDisplay) {
      return undefined;
    }
    const display = this._selectedRecordPKDisplay;
    if (!display) {
      return undefined;
    }
    if (display.message) {
      return (h("div", { class: "selected-record-header selected-record-header--message" }, h("span", { class: "selected-record-header__message" }, display.message)));
    }
    if (!((_a = display.items) === null || _a === void 0 ? void 0 : _a.length)) {
      return undefined;
    }
    return (h("div", { class: "selected-record-header", role: "group" }, display.items.map((item, index) => [
      index > 0 && h("span", { class: "selected-record-header__separator", "aria-hidden": "true" }),
      h("div", { class: "selected-record-header__chip" }, h("span", { class: "selected-record-header__label" }, item.label, ":"), h("span", { class: "selected-record-header__value" }, item.value))
    ])));
  }
  componentWillLoad() {
    var _a;
    this._configName = `dynaform.${this.entityName}`;
    this.formConfigManager = new SnkFormConfigManager(this._configName, (_a = this.resourceID) !== null && _a !== void 0 ? _a : '', () => this.loadMetadata(), this.dataUnit);
    this.formConfigManager.loadConfig();
    if (this.messagesBuilder == undefined) {
      this.messagesBuilder = new SnkMessageBuilder(this.entityName);
    }
  }
  componentWillRender() {
    this.initializeTaskbarProcessor();
  }
  initializeTaskbarProcessor() {
    if (!this.dataState) {
      return;
    }
    const detailTaskbarManager = this.buildDetailTaskbarManager();
    const topTaskbarId = getTopTaskBarId(this.dataState, this.presentationMode);
    this._taskbarProcessor.process(topTaskbarId, detailTaskbarManager, this.dataState, [], []);
  }
  buildDetailTaskbarManager() {
    const EDITION_MODE_BUTTONS = [
      TaskbarElement.CANCEL,
      TaskbarElement.SAVE,
    ];
    const currentView = this._currentView;
    return {
      getButtons: (taskbarID, dataState, defaultButtons) => {
        var _a, _b, _c;
        if (!taskbarID) {
          return [];
        }
        const isInEditionMode = (dataState === null || dataState === void 0 ? void 0 : dataState.insertionMode) || (dataState === null || dataState === void 0 ? void 0 : dataState.isDirty);
        if (isInEditionMode) {
          return EDITION_MODE_BUTTONS;
        }
        let buttons = [...defaultButtons];
        if (currentView === VIEW_MODE.FORM) {
          const indexFormMode = buttons.indexOf(TaskbarElement.FORM_MODE);
          if (indexFormMode > -1) {
            buttons = [
              ...buttons.slice(0, indexFormMode),
              TaskbarElement.GRID_MODE,
              ...buttons.slice(indexFormMode + 1),
            ];
          }
        }
        if (((_c = (_b = (_a = dataState === null || dataState === void 0 ? void 0 : dataState.selectionInfo) === null || _a === void 0 ? void 0 : _a.records) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0) > 1) {
          const indexUpdate = buttons.indexOf(TaskbarElement.UPDATE);
          if (indexUpdate > -1) {
            buttons = [
              ...buttons.slice(0, indexUpdate),
              TaskbarElement.UPDATE_MULTIPLE,
              ...buttons.slice(indexUpdate + 1),
            ];
          }
        }
        return buttons;
      },
      isEnabled: (_, dataState, buttonName, originalValue) => {
        if (!dataState) {
          return originalValue;
        }
        const hasSelectedRecord = dataState.selectedRecord !== undefined;
        const buttonsRequiringSelection = [
          TaskbarElement.UPDATE,
          TaskbarElement.REMOVE,
          TaskbarElement.ATTACH,
          TaskbarElement.CLONE,
        ];
        if (!hasSelectedRecord && buttonsRequiringSelection.includes(buttonName)) {
          return false;
        }
        if (buttonName === TaskbarElement.PREVIOUS && !dataState.hasPrevious) {
          return false;
        }
        if (buttonName === TaskbarElement.NEXT && !dataState.hasNext) {
          return false;
        }
        if (buttonName === TaskbarElement.INSERT && dataState.insertionMode) {
          return false;
        }
        return originalValue;
      },
    };
  }
  async componentDidLoad() {
    if (this.customEditors) {
      await this.observerPropsCustomEditor(this.customEditors);
    }
    if (this.customRenders) {
      await this.observeCustomRenders(this.customRenders);
    }
    this.initKeyboardManager();
  }
  disconnectedCallback() {
    var _a;
    (_a = this._keyboardManager) === null || _a === void 0 ? void 0 : _a.unbindAllShortcutKeys();
  }
  async dataUnitActionHandler(action) {
    var _a;
    if (action.type === Action.FIELD_INVALIDATED) {
      const sheetName = this.findSheetOfField((_a = action.payload) === null || _a === void 0 ? void 0 : _a.fieldName);
      if (sheetName) {
        this._internalErrorTabs = new Set([...this._internalErrorTabs, sheetName]);
      }
    }
  }
  findSheetOfField(fieldName) {
    var _a;
    if (!fieldName || !this._formMetadata) {
      return undefined;
    }
    const sheets = this._formMetadata.getAllSheets();
    for (const [sheetName, sheet] of sheets) {
      if ((_a = sheet.fields) === null || _a === void 0 ? void 0 : _a.some((f) => f.name === fieldName)) {
        return sheetName;
      }
    }
    return undefined;
  }
  normalizeDataUnitName() {
    var _a, _b;
    return (_b = (_a = this.dataUnitName) === null || _a === void 0 ? void 0 : _a.replace(/\//g, '>')) !== null && _b !== void 0 ? _b : '';
  }
  getSettingsListForm() {
    var _a, _b;
    const hardList = [{
        value: StringUtils.generateUUID(),
        label: (_b = (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage("snkCrud.findColumn", undefined)) !== null && _b !== void 0 ? _b : "",
        disableCloseOnSelect: true,
        eagerInitialize: true,
        itemBuilder: (_, item) => this.getFieldsSearch(item)
      }];
    return hardList;
  }
  getFieldsSearch(item) {
    var _a;
    if (this._fieldSearch === undefined || this._hasToCreateFieldSearch) {
      this._hasToCreateFieldSearch = false;
      this._fieldSearch = buildFieldSearch(item, ({ argument }) => this.fieldsOptionLoader(argument), (option) => this.onSelectField(option));
    }
    return (_a = this._fieldSearch) !== null && _a !== void 0 ? _a : document.createElement('div');
  }
  fieldsOptionLoader(argument) {
    const searchTerm = argument === null || argument === void 0 ? void 0 : argument.toLowerCase();
    const allFields = this.getFormFields().map(field => { var _a; return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getField(field.name); });
    const filteredFields = allFields.filter(field => {
      var _a, _b;
      if (!field) {
        return;
      }
      return ((_a = field.name) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(searchTerm)) ||
        ((_b = field.label) === null || _b === void 0 ? void 0 : _b.toLowerCase().includes(searchTerm));
    });
    const options = filteredFields.map((field) => {
      if (!field) {
        return;
      }
      return ({ value: field.name, label: field.label });
    });
    return Promise.resolve(options);
  }
  onSelectField(option) {
    if (option == undefined) {
      return;
    }
    this._fieldToGetFocus = option.value;
  }
  clearFieldToFocusHandler() {
    this._fieldToGetFocus = undefined;
  }
  getColumnSearch(item) {
    var _a;
    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 (_a = this._columnSearch) !== null && _a !== void 0 ? _a : document.createElement('div');
  }
  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'); },
    };
  }
  async initKeyboardManager() {
    var _a;
    this._keyboardManager = new KeyboardManager({ propagate: false, element: this._element });
    this._keyboardManager.bind(SHORTCUT_SEARCH_FIELD, async () => {
      var _a;
      await ((_a = this._snkFormView) === null || _a === void 0 ? void 0 : _a.showSearchField());
    }, { description: (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage("snkSimpleCrud.findFields"), element: this._element });
  }
  renderTabSelector() {
    var _a;
    if (!this.hasMultipleSheets()) {
      return undefined;
    }
    const selectedKey = (_a = this._selectedUITab) !== null && _a !== void 0 ? _a : (this._selectedSheet && this._selectedSheet.name !== SnkDynaformDetailView.MAIN_TAB
      ? this._selectedSheet.name
      : undefined);
    return (h("ez-tabselector", { class: "ez-tabselector-internal", tabs: this.buildInternalTabItems(), selectedTab: selectedKey, onEzChange: (evt) => this.onInternalTabChange(evt.detail) }));
  }
  renderUITabForm() {
    if (!this._selectedUITab) {
      return undefined;
    }
    const fields = this.getUITabFields();
    if (fields.length === 0) {
      return undefined;
    }
    return (h("snk-dynaform-form-view", { key: `uitab_${this._selectedUITab}`, name: `${SnkDynaformDetailView.MAIN_TAB}__${this._selectedUITab}`, formMetadata: this._formMetadata, dataUnit: this.dataUnit, fields: fields, fieldToFocus: this._fieldToGetFocus, label: this._selectedUITab, onSnkRequestClearFieldToFocus: this.clearFieldToFocusHandler.bind(this), fieldSearch: this._fieldSearch }));
  }
  renderSubDetail() {
    if (!this._selectedSheet || this._selectedSheet.name === SnkDynaformDetailView.MAIN_TAB) {
      return undefined;
    }
    const childEntityName = FormMetadata.getDetailName(this._selectedSheet.name);
    if (!childEntityName) {
      return undefined;
    }
    return (h("snk-dynaform-detail-view", { key: `sub_${this.dataUnitName}_${this._selectedSheet.name}`, dataUnitName: `${this.dataUnitName}/${childEntityName}`, entityName: childEntityName, label: this._selectedSheet.label, resourceID: this.resourceID, canEdit: this.canEdit, messagesBuilder: this.messagesBuilder, customEditors: this.customEditors, customRenders: this.customRenders, presentationMode: this.presentationMode, taskbarCustomContainerId: this.taskbarCustomContainerId }));
  }
  renderViewStack() {
    var _a, _b;
    return (h("ez-view-stack", { ref: (ref) => this._viewStack = ref }, h("stack-item", { class: "ez-size-width--full ez-size-height--full" }, h("snk-grid", { class: "ez-size-width--full ez-size-height--full", ref: (ref) => {
        if (ref)
          this._snkGrid = ref;
      }, configName: this._configName, messagesBuilder: this.messagesBuilder, onGridDoubleClick: () => this.changeViewMode(VIEW_MODE.FORM), onActionClick: (evt) => this.executeActionHandler(evt), presentationMode: this.presentationMode, canEdit: this.canEdit, isDetail: true, taskbarCustomContainerId: this.taskbarCustomContainerId, gridHeaderCustomSlotId: "DETAIL_GRID_HEADER_CUSTOM_ELEMENTS", topTaskbarCustomSlotId: "DETAIL_GRID_TASKBAR_CUSTOM_ELEMENTS", outlineMode: true, enableGridInsert: true, autoLoad: true, multipleEditionEnabled: true, multipleSelection: true, hideHeader: true, hideGridTaskbar: true })), h("stack-item", { class: "ez-size-width--full ez-size-height--full grid-container" }, h("div", { class: "form-and-detail-container" }, h("snk-dynaform-form-view", { ref: (ref) => {
        if (ref)
          this._snkFormView = ref;
      }, name: SnkDynaformDetailView.MAIN_TAB, formMetadata: this._formMetadata, dataUnit: this.dataUnit, fields: this.getFormFields(), fieldToFocus: this._fieldToGetFocus, label: this.label, onSnkRequestClearFieldToFocus: this.clearFieldToFocusHandler.bind(this), fieldSearch: this._fieldSearch }, this.renderSelectedRecordHeader()), this.renderTabSelector(), this.renderUITabForm(), this.renderSubDetail())), h("snk-attach", { ref: (ref) => this._snkAttach = ref, registerKey: (_a = this.attachmentRegisterKey) !== null && _a !== void 0 ? _a : '', messagesBuilder: this.messagesBuilder, entityName: (_b = this.entityName) !== null && _b !== void 0 ? _b : '' })));
  }
  render() {
    return (h(Host, null, h("snk-data-unit", { ref: (el) => {
        if (el)
          this._snkDataUnit = el;
      }, dataUnitName: `${this.dataUnitName}`, onDataUnitReady: evt => this.dataUnitReadyHandler(evt), entityName: this.entityName, onDataStateChange: this.handleDataStateChange.bind(this), ignoreSaveMessage: this._currentView === VIEW_MODE.GRID, messagesBuilder: this.messagesBuilder, configName: this._configName }, h("snk-taskbar", { key: "detailViewTaskbar", class: "form-taskbar", "data-element-id": "detail_top", configName: this._configName, messagesBuilder: this.messagesBuilder, buttons: this._taskbarProcessor.buttons, disabledButtons: this._taskbarProcessor.disabledButtons, customButtons: this._taskbarProcessor.customButtons, primaryButton: "INSERT", overflowStrategy: "hiddenItems", alignRigth: true, sizeButtons: 'small', presentationMode: this.presentationMode, onActionClick: evt => this.executeActionHandler(evt), dataUnit: this.dataUnit, resourceID: this.resourceID, customContainerId: this.taskbarCustomContainerId, customSlotId: "DETAIL_TASKBAR_CUSTOM_ELEMENTS", actionsSettingsList: this.getSettingsListForm(), customActionsList: this.buildTaskbarCustomActionsList() }, h("slot", { name: "DETAIL_TASKBAR_CUSTOM_ELEMENTS" })), this.renderViewStack())));
  }
  get _element() { return this; }
  static get watchers() { return {
    "dataUnit": ["observeDataUnit"],
    "dataState": ["observerDataState"],
    "customEditors": ["observerPropsCustomEditor"],
    "customRenders": ["observeCustomRenders"]
  }; }
  static get style() { return snkDynaformDetailViewCss; }
}, [6, "snk-dynaform-detail-view", {
    "formConfigManager": [1040],
    "dataUnitName": [1, "data-unit-name"],
    "resourceID": [1, "resource-i-d"],
    "entityName": [1, "entity-name"],
    "label": [1],
    "dataUnit": [1040],
    "selectedForm": [1025, "selected-form"],
    "dataState": [1040],
    "messagesBuilder": [1040],
    "canEdit": [4, "can-edit"],
    "taskbarCustomContainerId": [1, "taskbar-custom-container-id"],
    "customEditors": [16],
    "customRenders": [16],
    "presentationMode": [1, "presentation-mode"],
    "_currentView": [32],
    "attachmentRegisterKey": [32],
    "_fieldToGetFocus": [32],
    "_hasToCreateFieldSearch": [32],
    "_selectedSheet": [32],
    "_selectedUITab": [32],
    "_internalErrorTabs": [32],
    "_selectedRecordPKDisplay": [32],
    "changeViewMode": [64],
    "configGrid": [64],
    "showUp": [64],
    "addCustomEditor": [64],
    "addGridCustomRender": [64]
  }, [[0, "snkContentCardChanged", "onContentCardChanged"]]]);
SnkDynaformDetailView.MAIN_TAB = "__main";
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-dynaform-detail-view", "snk-actions-button", "snk-attach", "snk-configurator", "snk-data-exporter", "snk-data-unit", "snk-default-filter", "snk-dynaform-detail-view", "snk-dynaform-form-view", "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", "snk-grid-config", "snk-image-input", "snk-layout-form-config", "snk-numbering-config", "snk-personalized-filter", "snk-select-box", "snk-simple-bar", "snk-simple-crud", "snk-simple-form-config", "snk-taskbar", "snk-taskbar-skeleton", "snk-view-representation", "taskbar-actions-button", "taskbar-split-button"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-dynaform-detail-view":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkDynaformDetailView);
      }
      break;
    case "snk-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$H();
      }
      break;
    case "snk-attach":
      if (!customElements.get(tagName)) {
        defineCustomElement$G();
      }
      break;
    case "snk-configurator":
      if (!customElements.get(tagName)) {
        defineCustomElement$F();
      }
      break;
    case "snk-data-exporter":
      if (!customElements.get(tagName)) {
        defineCustomElement$E();
      }
      break;
    case "snk-data-unit":
      if (!customElements.get(tagName)) {
        defineCustomElement$D();
      }
      break;
    case "snk-default-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$C();
      }
      break;
    case "snk-dynaform-detail-view":
      if (!customElements.get(tagName)) {
        defineCustomElement();
      }
      break;
    case "snk-dynaform-form-view":
      if (!customElements.get(tagName)) {
        defineCustomElement$u();
      }
      break;
    case "snk-exporter-email-sender":
      if (!customElements.get(tagName)) {
        defineCustomElement$s();
      }
      break;
    case "snk-expression-group":
      if (!customElements.get(tagName)) {
        defineCustomElement$r();
      }
      break;
    case "snk-expression-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$q();
      }
      break;
    case "snk-filter-advanced-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$p();
      }
      break;
    case "snk-filter-assistent-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$o();
      }
      break;
    case "snk-filter-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$n();
      }
      break;
    case "snk-filter-detail":
      if (!customElements.get(tagName)) {
        defineCustomElement$m();
      }
      break;
    case "snk-filter-field-search":
      if (!customElements.get(tagName)) {
        defineCustomElement$l();
      }
      break;
    case "snk-filter-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$k();
      }
      break;
    case "snk-filter-modal":
      if (!customElements.get(tagName)) {
        defineCustomElement$j();
      }
      break;
    case "snk-filter-modal-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$i();
      }
      break;
    case "snk-filter-param-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$h();
      }
      break;
    case "snk-grid":
      if (!customElements.get(tagName)) {
        defineCustomElement$g();
      }
      break;
    case "snk-grid-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$f();
      }
      break;
    case "snk-image-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$e();
      }
      break;
    case "snk-layout-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$d();
      }
      break;
    case "snk-numbering-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$c();
      }
      break;
    case "snk-personalized-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$b();
      }
      break;
    case "snk-select-box":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "snk-simple-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "snk-simple-crud":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "snk-simple-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "snk-taskbar":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "snk-taskbar-skeleton":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "snk-view-representation":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "taskbar-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "taskbar-split-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
  } });
}

export { SnkDynaformDetailView as S, defineCustomElement as a, SnkDynaformGuidesViewer as b, defineCustomElement$1 as d };
