var __rest = (this && this.__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;
};
import { Action as DUAction, KeyboardManager, StringUtils } from '@sankhyalabs/core';
import { Host, forceUpdate, h } from '@stencil/core';
import { SnkFormConfigManager } from '../../../snk-dynaform-form-config/SnkFormConfigManager';
import { FormMetadata, buildFormMetadata } from "@sankhyalabs/ezui/dist/collection/utils/form";
import { PresentationMode } from '../../../../lib';
import { TaskbarElement } from '../../../snk-taskbar/elements/taskbar-elements';
import { VIEW_MODE } from '../../../../lib/utils/constants';
import { SnkDynaformGuidesViewer } from '../snk-dynaform-guides-view/snk-dynaform-guides-view';
import { SnkMessageBuilder } from '../../../../lib/message/SnkMessageBuilder';
import { buildFieldSearch, SHORTCUT_SEARCH_FIELD } from '@sankhyalabs/ezui/dist/collection/utils';
import SimpleTaskbarProcessor from '../../../snk-taskbar/processor/simple-taskbar-processor';
import { DEFAULT_TASKBAR_BUTTONS, getTopTaskBarId } from '../../../snk-crud/utils/taskbarUtils';
export class SnkDynaformDetailView {
  constructor() {
    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, { UITabName: _removed } = _b, 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 === DUAction.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())));
  }
  static get is() { return "snk-dynaform-detail-view"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["snk-dynaform-detail-view.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["snk-dynaform-detail-view.css"]
    };
  }
  static get properties() {
    return {
      "formConfigManager": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "SnkFormConfigManager",
          "resolved": "SnkFormConfigManager",
          "references": {
            "SnkFormConfigManager": {
              "location": "import",
              "path": "../../../snk-dynaform-form-config/SnkFormConfigManager"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Gerenciador de configura\u00E7\u00E3o do formul\u00E1rio."
        }
      },
      "dataUnitName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Determina todo o caminho desde o pai at\u00E9 chegar neste n\u00EDvel"
        },
        "attribute": "data-unit-name",
        "reflect": false
      },
      "resourceID": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Identificador de recursos como configura\u00E7\u00F5es e acesso."
        },
        "attribute": "resource-i-d",
        "reflect": false
      },
      "entityName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Nome da entidade detail."
        },
        "attribute": "entity-name",
        "reflect": false
      },
      "label": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Descri\u00E7\u00E3o amig\u00E1vel do cadastro detalhe."
        },
        "attribute": "label",
        "reflect": false
      },
      "dataUnit": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "DataUnit",
          "resolved": "DataUnit",
          "references": {
            "DataUnit": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Inst\u00E2ncia do DataUnit detail."
        }
      },
      "selectedForm": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Representa o formul\u00E1rio selecionado na inicializa\u00E7\u00E3o.\nAp\u00F3s o primeiro render, o estado interno _selectedSheet assume o controle."
        },
        "attribute": "selected-form",
        "reflect": false
      },
      "dataState": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "DataState",
          "resolved": "DataState",
          "references": {
            "DataState": {
              "location": "import",
              "path": "../../../snk-data-unit/snk-data-unit"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Representa o estado do dataUnit detail."
        }
      },
      "messagesBuilder": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "SnkMessageBuilder",
          "resolved": "SnkMessageBuilder",
          "references": {
            "SnkMessageBuilder": {
              "location": "import",
              "path": "../../../../lib/message/SnkMessageBuilder"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": ""
        }
      },
      "canEdit": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se a edi\u00E7\u00E3o est\u00E1 habilitada na grid."
        },
        "attribute": "can-edit",
        "reflect": false,
        "defaultValue": "true"
      },
      "taskbarCustomContainerId": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Define o identificador do container de elementos customizados da Taskbar."
        },
        "attribute": "taskbar-custom-container-id",
        "reflect": false
      },
      "customEditors": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "PropsCustomEditor",
          "resolved": "PropsCustomEditor",
          "references": {
            "PropsCustomEditor": {
              "location": "import",
              "path": "../../interfaces/PropsCustomEditor"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Registra um editor customizado para campos da grade e formul\u00E1rio."
        }
      },
      "customRenders": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "PropsCustomRender",
          "resolved": "PropsCustomRender",
          "references": {
            "PropsCustomRender": {
              "location": "import",
              "path": "../../interfaces/PropsCustomRender"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Render customizados da grade."
        }
      },
      "presentationMode": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "PresentationMode",
          "resolved": "PresentationMode.PRIMARY | PresentationMode.SECONDARY | PresentationMode.SINGLE_TASKBAR",
          "references": {
            "PresentationMode": {
              "location": "import",
              "path": "../../../../lib"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Altera o modo de apresenta\u00E7\u00E3o dos bot\u00F5es do snk-taskbar."
        },
        "attribute": "presentation-mode",
        "reflect": false,
        "defaultValue": "PresentationMode.SECONDARY"
      }
    };
  }
  static get states() {
    return {
      "_currentView": {},
      "attachmentRegisterKey": {},
      "_fieldToGetFocus": {},
      "_hasToCreateFieldSearch": {},
      "_selectedSheet": {},
      "_selectedUITab": {},
      "_internalErrorTabs": {},
      "_selectedRecordPKDisplay": {}
    };
  }
  static get methods() {
    return {
      "changeViewMode": {
        "complexType": {
          "signature": "(mode: VIEW_MODE) => Promise<void>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "mode - Novo modo que o componente deve ser apresentado."
                }],
              "text": "- Novo modo que o componente deve ser apresentado."
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "VIEW_MODE": {
              "location": "import",
              "path": "../../../../lib/utils/constants"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Muda o modo de visualiza\u00E7\u00E3o do componente entre VIEW_MODE.GRID e VIEW_MODE.FORM",
          "tags": [{
              "name": "param",
              "text": "mode - Novo modo que o componente deve ser apresentado."
            }]
        }
      },
      "configGrid": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Abre o configurador de grid.",
          "tags": []
        }
      },
      "showUp": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      },
      "addCustomEditor": {
        "complexType": {
          "signature": "(fieldName: string, customEditor: ICustomEditor) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "ICustomEditor": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/utils"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Registra um editor customizado para campos da grade e formul\u00E1rio.",
          "tags": []
        }
      },
      "addGridCustomRender": {
        "complexType": {
          "signature": "(fieldName: string, customRender: ICustomRender) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "ICustomRender": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/utils"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Registra um render customizado para colunas da grid.",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_element"; }
  static get watchers() {
    return [{
        "propName": "dataUnit",
        "methodName": "observeDataUnit"
      }, {
        "propName": "dataState",
        "methodName": "observerDataState"
      }, {
        "propName": "customEditors",
        "methodName": "observerPropsCustomEditor"
      }, {
        "propName": "customRenders",
        "methodName": "observeCustomRenders"
      }];
  }
  static get listeners() {
    return [{
        "name": "snkContentCardChanged",
        "method": "onContentCardChanged",
        "target": undefined,
        "capture": false,
        "passive": false
      }];
  }
}
SnkDynaformDetailView.MAIN_TAB = "__main";
