import { r as registerInstance, e as createEvent, h, i as forceUpdate, f as Host, g as getElement } from './index-04f73a26.js';
import { a as FilterGroupCondition, F as FilterOperand, b as FilterConfigType, P as PersonalizedFilterUtils, c as FilterEntities, d as FilterUserConfigTypes } from './PersonalizedFilterUtils-45b5803c.js';
import { ApplicationUtils, CheckMode } from '@sankhyalabs/ezui/dist/collection/utils';
import { ApplicationContext, StringUtils, ElementIDUtils, UserInterface, JSUtils, DataType } from '@sankhyalabs/core';
import { fieldBuilder } from '@sankhyalabs/ezui/dist/collection/components/ez-form-view/fieldbuilder/FieldBuilder';
import { s as store } from './index-ea250be6.js';
import { convertType } from '@sankhyalabs/core/dist/dataunit/metadata/DataType';
import { ModalAction } from '@sankhyalabs/ezui/dist/collection/components/ez-modal-container';
import './filter-item-type.enum-d45e026f.js';

const snkExpressionGroupCss = ".sc-snk-expression-group-h{display:block;--snk-expression-group--container-condition--width:184px;--snk-expression-group--container-condition--height:38px;--snk-expression-group--container-condition--border-radius:var(--border--radius-medium, 12px);--snk-expression-group--container-option--width:85px;--snk-expression-group__container-condition--background-and:#66B6A0;--snk-expression-group__container-condition--background-or:#EBC65E;--snk-expression-group__container-expression--padding-left:26px;--snk-expression-group__background-color-dashed:var(--background--body, #fafcff);--ez-text-input__margin-bottom:0px}.snk-expression-group__container-condition.sc-snk-expression-group{width:var(--snk-expression-group--container-condition--width);height:var(--snk-expression-group--container-condition--height);border-radius:var(--snk-expression-group--container-condition--border-radius);z-index:var(--more-visible--2x, 3);padding:var(--space--nano, 2px)}.snk-expression-group__container-option.sc-snk-expression-group{width:var(--snk-expression-group--container-option--width)}.snk-expression-group__container-condition[data-condition=\"AND\"].sc-snk-expression-group{background-color:var(--snk-expression-group__container-condition--background-and)}.snk-expression-group__container-condition[data-condition=\"OR\"].sc-snk-expression-group{background-color:var(--snk-expression-group__container-condition--background-or)}.snk-expression-group__container-expression.sc-snk-expression-group{padding-left:var(--snk-expression-group__container-expression--padding-left)}.dashes.sc-snk-expression-group{z-index:var(--visible, 1);background:var(--snk-expression-group__background-color-dashed);border-left:2px dashed var(--text-secondary, #A2ABB9);position:absolute;width:15px;height:58px;margin-left:-15px;margin-top:-36.5px}.horizontal-dashes.sc-snk-expression-group{z-index:var(--more-visible, 2);border-bottom:2px dashed var(--text-secondary, #A2ABB9);position:absolute;width:15px;height:54px;margin-left:-15px;margin-top:-33.5px}.hidden.sc-snk-expression-group{display:none}";

const SnkExpressionGroup = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezFilterGroupChange = createEvent(this, "ezFilterGroupChange", 7);
    this.ezFilterGroupRemove = createEvent(this, "ezFilterGroupRemove", 7);
    this.ezExpressionGroupLayoutChanged = createEvent(this, "ezExpressionLayoutChanged", 7);
    this.FIRST_LEVEL = "0";
    this.LIMIT_GROUP_LEVEL = 4;
    this.application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    this._conditionOperator = FilterGroupCondition.AND;
    this._group = undefined;
    this._selfTop = 0;
    this.canAddExpression = true;
    this._showDashes = true;
    this.parentTop = 0;
    this.group = undefined;
    this.messagesBuilder = undefined;
    this.filterId = undefined;
    this.entityURI = undefined;
    this.isDefaultFilter = false;
  }
  /**
   * Listener para capturar adição e remoção de grupos e items de expressão.
   */
  todoCompletedHandler(_) {
    this.updateDashes();
  }
  /*
   * Retorna o grupo da expressão.
   */
  async getExpressionGroup() {
    return this._group;
  }
  watchGroup(newValue) {
    this._group = newValue;
    this._conditionOperator = this.getOperand();
  }
  componentWillLoad() {
    this._group = this.group;
    this._conditionOperator = this.getOperand();
    if (!this.getDataGroupLevel()) {
      this._element.setAttribute('data-group-level', this.FIRST_LEVEL);
    }
    this.canAddExpression = this.group.items.every(this.isFilledItem);
  }
  componentDidRender() {
    this.setSelfTop();
  }
  changeHandler() {
    this.ezExpressionGroupLayoutChanged.emit();
  }
  /**
   * Função que define o valor atualizado da propriedade top do elemento em tela para calcular o tamanho do tracejado.
   */
  setSelfTop() {
    this._selfTop = this._element.getBoundingClientRect().top;
  }
  /**
   * Função que calcula o tamanho que deve ter o tracejado.
   */
  getDashedHeight() {
    return this._selfTop - this.parentTop;
  }
  getOperand() {
    return !this._group.operand ? FilterGroupCondition.AND : this._group.operand;
  }
  getMessage(key, params) {
    return this.application.messagesBuilder.getMessage(key, params);
  }
  updateDashes() {
    this._showDashes = false;
    this.setSelfTop();
    this._showDashes = true;
  }
  renderExpressionItems() {
    var _a;
    return (_a = this._group.items) === null || _a === void 0 ? void 0 : _a.map((item) => (h("snk-expression-item", { key: item.id, class: "ez-padding-top--small snk-expression-group__item", expression: item, canRemove: this._group.items.length > 1, onEzFilterItemChange: () => this.handleFilterItemChange(), onEzFilterItemRemove: (evt) => this.handleFilterItemRemove(evt, item.id), messagesBuilder: this.messagesBuilder, entityURI: this.entityURI, isDefaultFilter: this.isDefaultFilter })));
  }
  renderGroups() {
    var _a;
    const currentLevel = parseInt(this.getDataGroupLevel() || '0');
    const newLevel = currentLevel + 1;
    return (_a = this._group.childrenGroups) === null || _a === void 0 ? void 0 : _a.map((group) => (h("snk-expression-group", { key: group.id, group: group, messagesBuilder: this.messagesBuilder, parentTop: this._selfTop, "data-group-level": newLevel, onEzFilterGroupRemove: (evt) => this.handleFilterGroupRemove(evt, group.id), entityURI: this.entityURI })));
  }
  handleFilterGroupRemove(evt, groupId) {
    this.onStopPropagation(evt);
    this._group.childrenGroups = this._group.childrenGroups.filter(group => group.id !== groupId);
    forceUpdate(this);
    this.ezFilterGroupChange.emit(this._group);
    this.changeHandler();
  }
  handleFilterItemRemove(evt, itemId) {
    this.onStopPropagation(evt);
    this._group.items = this._group.items.filter(item => item.id !== itemId);
    forceUpdate(this);
    this.ezFilterGroupChange.emit(this._group);
    this.changeHandler();
    this.canAddExpression = true;
  }
  isFilledItem(item) {
    if (!item.fieldName || !item.operand)
      return false;
    if (item.operand === 'NULL' || item.operand === 'NOT_NULL') {
      return true;
    }
    else {
      return item.paramVariable || (item.userInterface === 'SWITCH') ? true : !!item.value;
    }
  }
  handleFilterItemChange() {
    this.ezFilterGroupChange.emit(this._group);
    this.canAddExpression = this.group.items.every(this.isFilledItem);
  }
  handleAddExpression() {
    const newItem = {
      id: StringUtils.generateUUID(),
      entityName: "",
      fieldName: "",
      description: "",
      label: this.getMessage("snkPersonalizedFilter.info.labelDefaultValue"),
      type: undefined,
      expression: undefined,
      operand: undefined,
      paramVariable: false,
      value: undefined,
      systemConfig: null,
      userConfig: null
    };
    this._group.items.push(newItem);
    forceUpdate(this);
    this.ezFilterGroupChange.emit(this.group);
    this.changeHandler();
    this.canAddExpression = false;
  }
  handleAddGroup() {
    var _a;
    const newGroup = {
      id: StringUtils.generateUUID(),
      items: [
        {
          id: StringUtils.generateUUID(),
          entityName: "",
          fieldName: "",
          description: "",
          label: this.getMessage("snkPersonalizedFilter.info.labelDefaultValue"),
          type: undefined,
          expression: undefined,
          operand: undefined,
          paramVariable: false,
          value: undefined,
          systemConfig: null,
          userConfig: null
        }
      ],
      childrenGroups: [],
      operand: FilterGroupCondition.AND
    };
    this._group.childrenGroups = (_a = this._group.childrenGroups) !== null && _a !== void 0 ? _a : [];
    this._group.childrenGroups.push(newGroup);
    forceUpdate(this);
    if (!this.group.operand) {
      this.group.operand = FilterGroupCondition.AND;
    }
    this.ezFilterGroupChange.emit(this.group);
    this.changeHandler();
  }
  buildGroupStyle() {
    return {
      height: `${this.getDashedHeight()}px`,
      marginTop: `${-(this.getDashedHeight()) + 20}px`,
    };
  }
  handleConditionOperatorChange(newOperator) {
    this._conditionOperator = newOperator;
    this._group.operand = FilterGroupCondition[newOperator];
    this.ezFilterGroupChange.emit(this._group);
  }
  confirmRemoveGroup(evt) {
    this.onStopPropagation(evt);
    ApplicationUtils.confirm(this.getMessage("snkPersonalizedFilter.confirmGroup.title"), this.getMessage("snkPersonalizedFilter.confirmGroup.description"))
      .then((canRemove) => {
      if (canRemove) {
        this.ezFilterGroupRemove.emit(this._group);
      }
    });
  }
  getTooltipMessageForOperator() {
    const groupLevel = this.getDataGroupLevel();
    if (groupLevel === this.FIRST_LEVEL && this._group.items.length === 1) {
      return this.getMessage("snkPersonalizedFilter.operador.firstLevel");
    }
    if (this._conditionOperator === FilterGroupCondition.AND) {
      return this.getMessage("snkPersonalizedFilter.operador.and");
    }
    else if (this._conditionOperator === FilterGroupCondition.OR) {
      return this.getMessage("snkPersonalizedFilter.operador.or");
    }
  }
  getDataGroupLevel() {
    return this._element.getAttribute('data-group-level');
  }
  canAddGroup() {
    const dataGroupLevel = Number(this.getDataGroupLevel() || this.FIRST_LEVEL);
    return dataGroupLevel < this.LIMIT_GROUP_LEVEL;
  }
  isFirstLevel() {
    return Boolean(this.getDataGroupLevel() === this.FIRST_LEVEL);
  }
  onStopPropagation(evt) {
    evt.preventDefault();
    evt.stopPropagation();
  }
  getMessageAddTooltip() {
    if (this.isFirstLevel()) {
      const allValidItems = this.group.items.every(item => {
        if (!item.fieldName || !item.operand)
          return false;
        return item.paramVariable || !!item.value;
      });
      return allValidItems ? this.getMessage("snkPersonalizedFilter.info.labelAddNewExpression") : this.getMessage("snkPersonalizedFilter.info.labelDisabledAddExpressionButton");
    }
    else {
      return this.canAddExpression ? this.getMessage("snkPersonalizedFilter.info.labelAddNewExpression") : this.getMessage("snkPersonalizedFilter.info.labelDisabledAddExpressionButton");
    }
  }
  canChangeGroupCondition() {
    const membersCount = this._group.items.length + this._group.childrenGroups.length;
    return membersCount > 1;
  }
  render() {
    const canAddGroup = this.canAddGroup();
    return (h(Host, null, h("div", { class: !this.isFirstLevel() && this._showDashes ? 'dashes' : 'hidden', style: this.buildGroupStyle() }), h("div", { class: !this.isFirstLevel() && this._showDashes ? 'horizontal-dashes' : 'hidden' }), h("div", { class: 'ez-flex ez-flex--align-items-center' }, h("div", { class: 'snk-expression-group__container-condition ez-flex ez-flex-item--align-center ez-flex--align-items-center', "data-condition": this._conditionOperator, title: this.getTooltipMessageForOperator() }, h("label", { class: "ez-label ez-padding-right--medium ez-padding-left--medium ez-title--primary" }, this.getMessage("snkPersonalizedFilter.info.condition")), h("div", null, h("ez-combo-box", Object.assign({ class: "snk-expression-group__container-option", canShowError: false, mode: "slim", suppressEmptyOption: true, enabled: this.canChangeGroupCondition(), value: this._conditionOperator, onEzChange: (evt) => this.handleConditionOperatorChange(evt.detail.value) }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `comboBoxConditions_level_${this.getDataGroupLevel()}` }), h("option", { value: FilterGroupCondition.AND }, this.getMessage("snkPersonalizedFilter.info.conditionAnd")), h("option", { value: FilterGroupCondition.OR }, this.getMessage("snkPersonalizedFilter.info.conditionOr"))))), h("ez-button", { class: "ez-padding-right--medium ez-padding-left--medium", mode: "icon", iconName: "plus", size: "small", enabled: this.canAddExpression, title: this.getMessageAddTooltip(), onClick: () => this.handleAddExpression() }), h("ez-button", { label: this.getMessage("snkPersonalizedFilter.info.addGroup"), size: "small", enabled: canAddGroup, title: !canAddGroup ? this.getMessage('snkPersonalizedFilter.info.labelDisabledAddGroupButton', { LIMIT_GROUP_LEVEL: this.LIMIT_GROUP_LEVEL + 1 }) : '', onClick: () => this.handleAddGroup() }, h("ez-icon", { class: "ez-padding-right--small", slot: "leftIcon", iconName: "plus" })), !this.isFirstLevel() && h("ez-button", { title: this.getMessage("snkPersonalizedFilter.info.labelDeleteExpression"), class: "ez-padding-left--medium", mode: "icon", iconName: "delete", size: "small", onClick: (evt) => this.confirmRemoveGroup(evt) })), h("div", { class: "ez-padding-top--small snk-expression-group__container-expression" }, h("div", { class: "ez-padding-top--small" }, this.renderExpressionItems())), h("div", { class: "ez-padding-top--small snk-expression-group__container-expression" }, h("div", { class: "ez-padding-top--small" }, this.renderGroups()))));
  }
  get _element() { return getElement(this); }
  static get watchers() { return {
    "group": ["watchGroup"]
  }; }
};
SnkExpressionGroup.style = snkExpressionGroupCss;

var SelectedItemType;
(function (SelectedItemType) {
  SelectedItemType["LINK"] = "LINK";
  SelectedItemType["FIELD"] = "FIELD";
})(SelectedItemType || (SelectedItemType = {}));

const defaultsOperand = [
  { label: "snkPersonalizedFilter.operands.equal", value: "EQUAL" },
  { label: "snkPersonalizedFilter.operands.different", value: "DIFFERENT" },
  { label: "snkPersonalizedFilter.operands.like", value: "LIKE" },
  { label: "snkPersonalizedFilter.operands.in", value: "IN" },
  { label: "snkPersonalizedFilter.operands.startWith", value: "START_WITH" },
  { label: "snkPersonalizedFilter.operands.finishedWith", value: "FINISHED_WITH" },
  { label: "snkPersonalizedFilter.operands.null", value: "NULL" },
  { label: "snkPersonalizedFilter.operands.notNull", value: "NOT_NULL" },
];
const FilterOperandDefault = defaultsOperand.concat([
  { label: "snkPersonalizedFilter.operands.larger", value: "LARGER" },
  { label: "snkPersonalizedFilter.operands.largerEqual", value: "LARGER_EQUAL" },
  { label: "snkPersonalizedFilter.operands.smaller", value: "SMALLER" },
  { label: "snkPersonalizedFilter.operands.smallerEqual", value: "SMALLER_EQUAL" }
]);
const FilterOperandTypeTextSearch = defaultsOperand;
const FIELD_TYPE_SEARCH_AND_TEXT = [
  UserInterface.SEARCH,
  UserInterface.SHORTTEXT,
  UserInterface.PASSWORD,
  UserInterface.MASKEDTEXT,
  UserInterface.LONGTEXT,
  UserInterface.HTML
];

const snkExpressionItemCss = ".sc-snk-expression-item-h{display:flex;width:100%;--snk-expression-item--background-color:var(--background--xlight, #fff);--snk-expression-item__itens--padding:var(--space--small, 6px);--snk-expression-item__width--input-operator:220px;--snk-expression-item__width--input-value:240px;--snk-expression-item__width--input-value-variable:176px;--snk-expression-item--border-radius:var(--border--radius-medium, 12px);--snk-expression-item--border-color:var(--color--strokes, #DCE0E8);--snk-expression-item--border-style:var(--border--small, 1px solid);--snk-expression-item__background-color-dashed:var(--background--body, #fafcff)}.box.sc-snk-expression-item{width:100%;height:56px;background:var(--snk-expression-item--background-color);border:var(--snk-expression-item--border-color) var(--snk-expression-item--border-style);border-radius:var(--snk-expression-item--border-radius)}.box__container.sc-snk-expression-item{display:flex;align-items:center;justify-content:space-between;white-space:nowrap;margin:var(--space--small, 6px)}.box__container--input-filter.sc-snk-expression-item{width:100%}.box__container--input-operator.sc-snk-expression-item{display:flex;width:var(--snk-expression-item__width--input-operator);min-width:var(--snk-expression-item__width--input-operator)}.box__container--input-value.sc-snk-expression-item{display:flex;width:var(--snk-expression-item__width--input-value);min-width:var(--snk-expression-item__width--input-value)}.box__container--input-value-variable.sc-snk-expression-item{display:flex;width:var(--snk-expression-item__width--input-value-variable);min-width:var(--snk-expression-item__width--input-value-variable)}.box__container--button-delete.sc-snk-expression-item{display:flex}.box__container.sc-snk-expression-item>div.sc-snk-expression-item{padding-left:var(--snk-expression-item__itens--padding);padding-right:var(--snk-expression-item__itens--padding)}.box__container--button-delete--icon.sc-snk-expression-item{width:42px;min-width:42px}.box__container--input-value-variable--icon.sc-snk-expression-item{cursor:pointer}.dashes.sc-snk-expression-item{z-index:var(--more-visible, 2);background:var(--snk-expression-item__background-color-dashed);border-bottom:2px dashed var(--text-secondary, #A2ABB9);border-left:2px dashed var(--text-secondary, #A2ABB9);position:absolute;width:15px;height:62px;margin-left:-15px;margin-top:-33.5px}";

const SnkExpressionItem = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezFilterItemChange = createEvent(this, "ezFilterItemChange", 7);
    this.ezFilterItemRemove = createEvent(this, "ezFilterItemRemove", 7);
    this.application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    this.filterOperandDefault = FilterOperandDefault;
    this.filterOperandTypeTextSearch = FilterOperandTypeTextSearch;
    this.DEFAULT_FIELD_NAME = 'NOT_DEFINED';
    this._showValueVariable = false;
    this._fieldSelected = undefined;
    this._optionNotNull = false;
    this.expression = undefined;
    this.canRemove = true;
    this.messagesBuilder = undefined;
    this.isDefaultFilter = false;
    this.entityURI = undefined;
  }
  expressionChanged(newValue, oldValue) {
    if (newValue !== oldValue) {
      this.ezFilterItemChange.emit(newValue);
      this.updateFieldSelected();
    }
  }
  componentWillLoad() {
    this._dataSourceFetcher = store.get(`filterFieldsDataSource.${this.entityURI}`);
    store.onChange(`filterFieldsDataSource.${this.entityURI}`, () => {
      this._dataSourceFetcher = store.get(`filterFieldsDataSource.${this.entityURI}`);
    });
    if (this.expression) {
      this.updateFieldSelected();
      this._optionNotNull = this.expression.operand === 'NULL' || this.expression.operand === 'NOT_NULL';
    }
  }
  componentDidRender() {
    var _a;
    this._showValueVariable = (_a = this._elValueVariable) === null || _a === void 0 ? void 0 : _a.value;
  }
  updateFieldSelected() {
    const field = {
      dataType: this.expression.type,
      description: this.expression.description,
      name: this.expression.fieldName,
      label: this.expression.fieldLabel,
      entityName: this.expression.entityName,
      onlyDate: false,
      path: this.expression.description,
      properties: this.expressionPropsToFieldProps(this.expression.props),
      type: SelectedItemType.FIELD,
      uri: "",
      userInterface: this.expression.userInterface
    };
    this._fieldSelected = field;
  }
  buildExpression(entityName, fieldName, entityPath) {
    if (entityPath.length > 0) {
      entityPath.shift();
    }
    return entityPath.length > 0 ? `${entityPath.join("->")}->${fieldName}` : `${entityName}.${fieldName}`;
  }
  setValueExpression(key, value) {
    if (key === "fieldName") {
      this.expression.description = value.path;
      this.expression.expression = this.buildExpression(value.entityName, value.name, value.entityPath);
      this.expression.fieldName = value.name;
      this.expression.fieldLabel = value.label;
      this.expression.type = value.dataType;
      this.expression.userInterface = value.userInterface;
      this.expression.entityName = value.entityName;
      this.expression.value = undefined;
      this.expression.props = this.fieldPropsToExpressionProps(value.properties);
    }
    else {
      this.expression[key] = value;
    }
    this.expressionChanged(this.expression);
  }
  fieldPropsToExpressionProps(properties) {
    const parsedProps = [];
    if (!properties) {
      return parsedProps;
    }
    for (const key in properties) {
      let propValue = properties[key];
      if (typeof propValue == "object") {
        propValue = JSON.stringify(propValue);
      }
      parsedProps.push({ name: key, value: propValue });
    }
    return parsedProps;
  }
  expressionPropsToFieldProps(properties) {
    const parsedProps = {};
    if (!properties) {
      return parsedProps;
    }
    properties.forEach(prop => {
      try {
        parsedProps[prop.name] = JSON.parse(prop.value);
      }
      catch (_a) {
        parsedProps[prop.name] = prop.value;
      }
    });
    return parsedProps;
  }
  getMessage(key, params) {
    return this.application.messagesBuilder.getMessage(key, params);
  }
  handleSelectItem(filterField) {
    if (this.hasNoChanges(filterField)) {
      this._elFilterInput.value = filterField.path;
      return;
    }
    if (filterField.type === SelectedItemType.FIELD) {
      const field = filterField;
      this._fieldSelected = field;
      this.setValueExpression("fieldName", field);
    }
  }
  hasNoChanges(filterField) {
    return filterField.name === this.expression.fieldName && filterField.path === this.expression.description;
  }
  handleFocus() {
    if (this._elFilterFieldSearch)
      this._elFilterFieldSearch.show();
  }
  handleChangeFilterInput(evt) {
    this._elFilterFieldSearch.applyFilter(evt.detail);
  }
  handleChangeValueVariable(showValueVariable) {
    this._showValueVariable = showValueVariable;
    if (this._elFieldDynamic) {
      this._elFieldDynamic.value = undefined;
      this._elFieldDynamic.enabled = !showValueVariable;
    }
    this.expression["paramVariable"] = showValueVariable;
    this.expressionChanged(this.expression);
  }
  openSnkFilterParamConfig() {
    var _a;
    (_a = this._elFilterParamConfigRef) === null || _a === void 0 ? void 0 : _a.open(this.expression).then(this.onOpenPromiseReady.bind(this)).catch(error => {
      console.error(error);
    });
  }
  onOpenPromiseReady(changes) {
    this.expression = changes;
  }
  buildOptionsOperator() {
    var _a;
    if (FIELD_TYPE_SEARCH_AND_TEXT.includes((_a = this._fieldSelected) === null || _a === void 0 ? void 0 : _a.userInterface)) {
      return this.translateOperandOptions(this.filterOperandTypeTextSearch);
    }
    else {
      return this.translateOperandOptions(this.filterOperandDefault);
    }
  }
  translateOperandOptions(options) {
    return options.map(option => ({ label: this.getMessage(option.label), value: option.value }));
  }
  handleChangeOperator(optionSelected) {
    this.checkOptionIsNull(optionSelected);
    this.setValueExpression("operand", optionSelected);
  }
  checkOptionIsNull(optionSelected) {
    const filterOperandValue = FilterOperand[optionSelected];
    if ([FilterOperand.NULL, FilterOperand.NOT_NULL].includes(filterOperandValue)) {
      this._optionNotNull = true;
      if (this._elFieldDynamic) {
        this._elFieldDynamic.enabled = false;
        this._elFieldDynamic.value = undefined;
      }
    }
    else {
      this._optionNotNull = false;
      if (this._elFieldDynamic) {
        this._elFieldDynamic.enabled = this._showValueVariable ? false : true;
      }
    }
  }
  confirmRemove(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    ApplicationUtils.confirm(this.getMessage("snkPersonalizedFilter.confirmExpression.title"), this.getMessage("snkPersonalizedFilter.confirmExpression.description"))
      .then((canRemove) => {
      if (canRemove) {
        this.ezFilterItemRemove.emit(this.expression);
      }
    });
  }
  buildFieldByType() {
    var _a, _b, _c;
    if (!this._fieldSelected)
      return;
    const inputFieldData = (_a = fieldBuilder(this.configureFieldByType())) === null || _a === void 0 ? void 0 : _a.$children$.shift();
    if (this._optionNotNull && inputFieldData || ((_b = this._elValueVariable) === null || _b === void 0 ? void 0 : _b.value) && inputFieldData || this.expression.paramVariable || this._showValueVariable || !((_c = this._fieldSelected) === null || _c === void 0 ? void 0 : _c.dataType)) {
      inputFieldData.$attrs$.enabled = false;
    }
    if (this.expression.value != undefined) {
      inputFieldData.$attrs$.value = this.getExpressiontValue(this.expression);
    }
    inputFieldData.$attrs$.onEzChange = (event) => {
      this.setValueExpression("value", event.target.value);
    };
    if (this.expression.userInterface === 'SWITCH' && this.expression.value == undefined) {
      this.setValueExpression("value", false);
    }
    return h(inputFieldData.$tag$, Object.assign(Object.assign({}, inputFieldData.$attrs$), { ref: (el) => {
        this._elFieldDynamic = el;
      }, label: this.expression.fieldLabel || this._fieldSelected.label }));
  }
  getExpressiontValue(expression) {
    return convertType(expression.type, expression.value);
  }
  configureFieldByType() {
    var _a, _b;
    const field = {
      userInterface: this._fieldSelected.userInterface,
      name: this._fieldSelected.name,
      label: this._fieldSelected.label,
      canShowError: false
    };
    switch (field.userInterface) {
      case UserInterface.OPTIONSELECTOR:
        field.props = {
          options: (_b = (_a = this._fieldSelected) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b.options,
        };
        break;
      case UserInterface.LONGTEXT:
        field.rows = 1;
        break;
      case UserInterface.SEARCH:
        field.optionLoader = searchArgument => this.setCriteriaSearch(searchArgument, this.application);
        break;
    }
    return field;
  }
  setCriteriaSearch({ mode, argument }, application) {
    var _a, _b, _c;
    if (application == undefined)
      return;
    const searchOptions = {
      showInactives: false
    };
    const options = {
      entity: (_c = (_b = (_a = this._fieldSelected) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b.ENTITYNAME) !== null && _c !== void 0 ? _c : this._fieldSelected.entityName,
      searchOptions,
      entityDescription: this._fieldSelected.description
    };
    return application.executePreparedSearch(mode, argument, options);
  }
  render() {
    var _a;
    return (h(Host, null, h("div", { class: "dashes" }), h("div", { class: "box" }, h("div", { class: "box__container" }, h("div", { class: "box__container--input-filter" }, h("ez-filter-input", Object.assign({ ref: ref => this._elFilterInput = ref, value: (_a = this._fieldSelected) === null || _a === void 0 ? void 0 : _a.path, label: this.getMessage("snkPersonalizedFilter.info.labelSearchField"), canShowError: false, onEzChange: (evt) => this.handleChangeFilterInput(evt), onFocus: () => this.handleFocus() }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `expressionFilterInput_${this.expression.fieldName || this.DEFAULT_FIELD_NAME}` })), h("snk-filter-field-search", { ref: ref => this._elFilterFieldSearch = ref, searchable: false, onEzSelectFilterItem: (ev) => this.handleSelectItem(ev.detail), fieldsDataSource: this._dataSourceFetcher })), h("div", { class: "box__container--input-operator" }, h("ez-combo-box", Object.assign({ label: this.getMessage("snkPersonalizedFilter.info.labelOperator"), value: this.expression.operand, canShowError: false, options: this.buildOptionsOperator(), onEzChange: (evt) => { var _a; return this.handleChangeOperator((_a = evt.detail) === null || _a === void 0 ? void 0 : _a.value); }, suppressEmptyOption: true }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `comboBoxOperand_${this.expression.fieldName || this.DEFAULT_FIELD_NAME}` }))), h("div", { class: "box__container--input-value" }, !this._fieldSelected ? (h("ez-number-input", { label: this.getMessage('snkPersonalizedFilter.info.labelDefaultValue'), canShowError: false, enabled: !this._showValueVariable && !this._optionNotNull })) : (this.buildFieldByType())), h("div", { class: "box__container--input-value-variable" }, !this._optionNotNull &&
      h("ez-tooltip", { message: this.getMessage("snkPersonalizedFilter.info.checkVariableDisabled"), active: this.isDefaultFilter }, h("ez-check", { ref: ref => this._elValueVariable = ref, value: this.expression.paramVariable, label: this.getMessage("snkPersonalizedFilter.info.labelValueVarible"), mode: CheckMode.SWITCH, onEzChange: (evt) => this.handleChangeValueVariable(evt.detail), enabled: !this.isDefaultFilter })), (this._showValueVariable && !this._optionNotNull) &&
      h("ez-icon", Object.assign({ class: "box__container--input-value-variable--icon", size: "large", iconName: "settings-inverted" }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: 'iconConfig' }, { title: this.getMessage("snkPersonalizedFilter.info.titleTooltip"), onClick: () => this.openSnkFilterParamConfig() })), h("snk-filter-param-config", { ref: (el) => this._elFilterParamConfigRef = el, messagesBuilder: this.messagesBuilder })), h("div", { class: "box__container--button-delete" }, h("div", { class: "box__container--button-delete--icon" }, h("ez-button", { mode: "icon", iconName: "delete", enabled: this.canRemove, label: this.getMessage("snkPersonalizedFilter.info.labelDeleteItem"), onClick: (evt) => this.confirmRemove(evt) })))))));
  }
  static get watchers() { return {
    "expression": ["expressionChanged"]
  }; }
};
SnkExpressionItem.style = snkExpressionItemCss;

const ICON_MODES = {
  [UserInterface.SHORTTEXT]: 'text',
  [UserInterface.LONGTEXT]: 'text',
  [UserInterface.INTEGERNUMBER]: 'number',
  [UserInterface.DECIMALNUMBER]: 'number',
  [UserInterface.DATE]: 'calendar',
  [UserInterface.DATETIME]: 'calendar',
  [UserInterface.SWITCH]: 'boolean',
  [UserInterface.CHECKBOX]: 'check-circle-inverted',
  [UserInterface.OPTIONSELECTOR]: 'list',
  [UserInterface.SEARCH]: 'search',
  [UserInterface.HTML]: 'tag_code',
  [UserInterface.IMAGE]: 'png',
  [UserInterface.FILE]: 'edit-file',
  [UserInterface.TIME]: 'timer-outline',
  [UserInterface.ELAPSEDTIME]: 'timer',
  [UserInterface.MASKEDTEXT]: 'text',
  [UserInterface.PASSWORD]: 'email',
};
const ListItem = ({ userInterface, description }) => {
  return (h("ez-icon", { iconName: ICON_MODES[userInterface], class: "ez-padding-left--small", title: description }));
};

const snkFilterFieldSearchCss = ".sc-snk-filter-field-search-h{--snk-filter-field-search--container-width:468px;--snk-filter-field-search--container-height:322px}.snk-filter-field-search__container.sc-snk-filter-field-search{display:flex;flex-direction:column;padding:var(--space--medium);width:var(--snk-filter-field-search--container-width);height:var(--snk-filter-field-search--container-height)}.snk-filter-field-search__section.sc-snk-filter-field-search{display:grid;grid-template-columns:1fr 1fr;place-items:flex-start;overflow:hidden;gap:var(--space--small)}.snk-filter-field-search__input.sc-snk-filter-field-search{margin-bottom:var(--space--medium)}.snk-filter-field-search__list_container.sc-snk-filter-field-search{display:flex;flex-direction:column}.snk-filter-field-search__list.sc-snk-filter-field-search{overflow-y:auto}";

const SNK_CONTEXT_KEY = "__SNK__APPLICATION__";
const ENTITY_NAME_PATTERN = /\w+:\/\/(\w+)/;
const SnkFilterFieldSearch = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezSelectFilterItem = createEvent(this, "ezSelectFilterItem", 7);
    this._currentMetadata = null;
    this._filterText = "";
    this._isLoading = false;
    this.searchable = true;
    this.fieldsDataSource = undefined;
    this.breadcrumbItems = [];
    this.linkItems = [];
    this.fieldItems = [];
    this.searchEmpty = false;
    this.groupEmpty = false;
  }
  /**
   * /**
   * Realiza a abertura do componente abaixo do elemento HTML informado
   * e faz a primeira carga de dados.
   *
   * @param {HTMLElement} element - Elemento HTML onde o snk-filter-field-search irá se posicionar abaixo.
   * @param {IEzPopoverAnchorOptions} options - opções para regular o posicionamento do componente.
   */
  async show(element, options) {
    var _a;
    if (element) {
      (_a = this._ezPopover) === null || _a === void 0 ? void 0 : _a.showUnder(element, options);
    }
    else {
      this._ezPopover.show();
    }
    return this.loadData();
  }
  /**
   * Filtra a fonte de dados do componente.
   * @param {string} filterText - Texto para filtrar a fonte de dados.
   * @throws {Error} - Quando o componente estiver com a propriedade searchable como true.
  */
  async applyFilter(filterText) {
    if (this.searchable)
      throw new Error('This method is not available when searchable is true');
    this.handleFilterChange(filterText);
  }
  async loadData() {
    var _a, _b;
    this._isLoading = true;
    let metadata = await this.fieldsDataSource.fetchData(this._currentLink);
    this._currentLink = metadata.currentLink;
    const { fields, links } = metadata || {};
    if (!Array.isArray(fields) || !Array.isArray(links))
      throw new Error('Invalid metadata');
    this._currentMetadata = metadata;
    this.mapDataSourceToLinkItems();
    this.mapDataSourceToFieldItems();
    this._isLoading = false;
    (_a = this._ezFieldList) === null || _a === void 0 ? void 0 : _a.scrollToTop();
    (_b = this._ezLinkList) === null || _b === void 0 ? void 0 : _b.scrollToTop();
  }
  mapDataSourceToLinkItems() {
    var _a;
    const { links } = this._currentMetadata;
    const filterLinkLabelMessage = this.getMessage('snkFilterFieldSearch.linkLabel', { link: (_a = this._currentLink) === null || _a === void 0 ? void 0 : _a.description });
    const items = links.map(link => (Object.assign({ label: link.description }, link)));
    this.groupEmpty = Boolean(items.length === 0);
    this.linkItems = [{
        group: filterLinkLabelMessage,
        items,
      }];
    if (this.breadcrumbItems.length === 0) {
      this.breadcrumbItems = [Object.assign({ id: JSUtils.generateUUID(), label: this._currentLink.description }, this._currentLink)];
    }
  }
  mapDataSourceToFieldItems() {
    var _a;
    const fields = this._currentMetadata.fields;
    const filterFieldLabelMessage = this.getMessage('snkFilterFieldSearch.fieldLabel', { link: (_a = this._currentLink) === null || _a === void 0 ? void 0 : _a.description });
    const filteredFields = fields.filter(field => {
      if (!this._currentLink)
        return true;
      const searchableByDescription = field.description.toLowerCase().includes(this._filterText.toLowerCase());
      const searchableByName = field.name.toLowerCase().includes(this._filterText.toLowerCase());
      return searchableByDescription || searchableByName;
    });
    const items = filteredFields.map(field => (Object.assign({ label: field.description }, field)));
    this.searchEmpty = Boolean(this._filterText && items.length === 0);
    this.fieldItems = [{
        group: filterFieldLabelMessage,
        items
      }];
  }
  handleFilterChange(filterText) {
    if (this._isLoading)
      return;
    this._filterText = filterText;
    this.mapDataSourceToFieldItems();
  }
  handleSelectLink({ detail: item }) {
    if (this._isLoading)
      return;
    const breadcrumbByIndex = this.breadcrumbItems.findIndex(breadcrumbItem => breadcrumbItem.id === item.id);
    if (breadcrumbByIndex > -1) {
      this.breadcrumbItems = this.breadcrumbItems.slice(0, (breadcrumbByIndex + 1));
    }
    else {
      this.breadcrumbItems = [...this.breadcrumbItems, Object.assign({ id: JSUtils.generateUUID(), label: item.description }, item)];
    }
    const selectedItem = Object.assign(Object.assign({}, item), { type: SelectedItemType.LINK });
    this._currentLink = selectedItem;
    this.ezSelectFilterItem.emit(selectedItem);
    this.loadData();
  }
  getEntityFromBreadCrumbItem(item) {
    const result = ENTITY_NAME_PATTERN.exec(item.uri);
    if (!result) {
      return undefined;
    }
    return result[1];
  }
  handleSelectField({ detail: item }) {
    var _a;
    const breadcrumbPath = this.breadcrumbItems.map(breadcrumbItem => breadcrumbItem.label).join('>>');
    const selectedField = Object.assign(Object.assign({}, item), { type: SelectedItemType.FIELD, entityPath: this.breadcrumbItems.map(item => this.getEntityFromBreadCrumbItem(item)).filter(item => item != undefined), path: `${breadcrumbPath} >> ${item.description}` });
    this.ezSelectFilterItem.emit(selectedField);
    (_a = this._ezPopover) === null || _a === void 0 ? void 0 : _a.hide();
  }
  getElementID(sufix) {
    return {
      [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(sufix)
    };
  }
  /**
   * 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-filter-field-search.msg.ts"
  */
  getMessage(key, params) {
    var _a, _b, _c;
    if (!this._application)
      this._application = ApplicationContext.getContextValue(SNK_CONTEXT_KEY);
    return (_c = (_b = (_a = this._application) === null || _a === void 0 ? void 0 : _a.messagesBuilder) === null || _b === void 0 ? void 0 : _b.getMessage) === null || _c === void 0 ? void 0 : _c.call(_b, key, params);
  }
  ;
  componentWillLoad() {
    this._application = ApplicationContext.getContextValue(SNK_CONTEXT_KEY);
  }
  componentDidLoad() {
    ElementIDUtils.addIDInfoIfNotExists(this._ezPopover, 'popover');
  }
  disconnectedCallback() {
    var _a;
    (_a = this._ezPopover) === null || _a === void 0 ? void 0 : _a.hide();
  }
  render() {
    var _a;
    const searchLabelMessage = this.getMessage('snkFilterFieldSearch.searchLabel');
    return (h("ez-popover", Object.assign({ ref: (el) => this._ezPopover = el, role: "dialog", overlayType: "none", "aria-hidden": !((_a = this._ezPopover) === null || _a === void 0 ? void 0 : _a.opened) }, this.getElementID('EzPopover')), h("div", { class: "snk-filter-field-search__container" }, h("header", { class: "snk-filter-field-search__header" }, this.searchable && !!searchLabelMessage && (h("ez-filter-input", Object.assign({ class: "snk-filter-field-search__input", label: searchLabelMessage, asyncSearch: true, canShowError: false, onEzSearching: (event) => this.handleFilterChange.bind(this)(event.detail), "aria-label": searchLabelMessage, "aria-required": "false", "aria-invalid": "false" }, this.getElementID('EzFilterInput')))), this.breadcrumbItems.length > 0 && (h("ez-breadcrumb", Object.assign({ items: this.breadcrumbItems, onSelectedItem: this.handleSelectLink.bind(this), role: "navigation", "aria-current": "step" }, this.getElementID('EzBreadcrumb')))), h("hr", { class: "ez-divider-horizontal ez-margin-vertical--medium" })), h("section", { class: `snk-filter-field-search__section ${(this.groupEmpty && this.searchEmpty) && " ez-margin--auto"}` }, this.groupEmpty ?
      h("div", { class: "ez-margin--auto" }, h("span", { class: "ez-text ez-text--secondary ez-text--medium" }, this.getMessage('snkFilterFieldSearch.groupEmpty')))
      :
        h("ez-list", Object.assign({ ref: (el) => this._ezLinkList = el, class: "snk-filter-field-search__list", id: "filterLinkList", useGroups: true, dataSource: this.linkItems, onEzSelectItem: this.handleSelectLink.bind(this), hoverFeedback: true, ezSelectable: true, itemSlotBuilder: listItem => h("ez-badge", { label: listItem.fieldCount }), "aria-describedby": "filterLinkLabel" }, this.getElementID('EzListLinks'))), this.searchEmpty ?
      h("div", { class: "ez-margin--auto" }, h("span", { class: "ez-text ez-text--secondary ez-text--medium" }, this.getMessage('snkFilterFieldSearch.searchEmpty')))
      :
        h("ez-list", Object.assign({ ref: (el) => this._ezFieldList = el, class: "snk-filter-field-search__list", id: "filterFieldList", useGroups: true, dataSource: this.fieldItems, onEzSelectItem: this.handleSelectField.bind(this), hoverFeedback: true, ezSelectable: true, itemSlotBuilder: ListItem, "aria-describedby": "filterFieldLabel" }, this.getElementID('EzListFields')))))));
  }
};
SnkFilterFieldSearch.style = snkFilterFieldSearchCss;

const snkFilterParamConfigCss = ":host{--snk-filter-param-config__expression--color:var(--title--primary, #2b3a54);display:flex;position:relative}.snk-filter-param-config__expression{--text-area__input--disabled--color:var(--snk-filter-param-config__expression--color)}";

const SnkFilterParamConfig = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this._opened = false;
    this._configType = FilterConfigType.SYSTEM_CONFIG;
    this._expressionItem = undefined;
    this._informedInstance = false;
    this._canSave = false;
    this.messagesBuilder = undefined;
  }
  /**
   * Abre o modal de configuração de valor variável
   */
  open(expressionItem) {
    this._opened = true;
    this._expressionItem = expressionItem;
    this.loadValues();
    return new Promise(accept => {
      this._promiseResolver = accept;
    });
  }
  /**
   * Fecha o modal de configuração de valor variável
   */
  close() {
    this._opened = false;
    return new Promise(accept => {
      this._promiseResolver = accept;
    });
  }
  /**
   * 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-filter-param-config.msg.ts"
   */
  getMessage(key, params) {
    var _a;
    return (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage(key, params);
  }
  getConfigValue(configName, inputName, inputAlias = "") {
    var _a, _b, _c;
    return ((_b = (_a = this._expressionItem) === null || _a === void 0 ? void 0 : _a[configName]) === null || _b === void 0 ? void 0 : _b[inputName])
      || ((_c = this._expressionItem) === null || _c === void 0 ? void 0 : _c[inputAlias || inputName]);
  }
  loadValues() {
    var _a;
    const entityName = this.getConfigValue("systemConfig", "entity", "entityName");
    const fieldName = this.getConfigValue("systemConfig", "fieldName");
    const description = this.getConfigValue("userConfig", "description");
    const type = this.getConfigValue("userConfig", "type");
    if (((_a = this._expressionItem) === null || _a === void 0 ? void 0 : _a.userConfig) != undefined) {
      this._configType = FilterConfigType.USER_CONFIG;
    }
    else {
      this._configType = FilterConfigType.SYSTEM_CONFIG;
    }
    if (!StringUtils.isEmpty(entityName) && !StringUtils.isEmpty(fieldName)) {
      this._instanceElement.value = { value: entityName, label: "" };
      this._fieldElement.value = { value: fieldName, label: "" };
    }
    if (!StringUtils.isEmpty(description) && !StringUtils.isEmpty(type)) {
      this._descriptionElement.value = description;
      this._typeElement.value = type;
    }
    this.buildFilterExpression();
  }
  changeDefinitionUsed(option) {
    this._configType = option !== null && option !== void 0 ? option : FilterConfigType.SYSTEM_CONFIG;
    if (this._configType === FilterConfigType.SYSTEM_CONFIG) {
      const entityName = this.getConfigValue("systemConfig", "entity", "entityName");
      const fieldName = this.getConfigValue("systemConfig", "fieldName");
      this._instanceElement.value = this._instanceElement.value || { value: entityName, label: "" };
      this._fieldElement.value = this._fieldElement.value || { value: fieldName, label: "" };
    }
    else if (this._configType === FilterConfigType.USER_CONFIG) {
      const description = this.getConfigValue("userConfig", "description");
      const type = this.getConfigValue("userConfig", "type");
      this._descriptionElement.value = this._descriptionElement.value || description;
      this._typeElement.value = this._typeElement.value || type;
    }
    this.buildFilterExpression();
  }
  getTypeValue() {
    var _a;
    const value = (_a = this._typeElement) === null || _a === void 0 ? void 0 : _a.value;
    return ((value === null || value === void 0 ? void 0 : value.value) || value);
  }
  getExpressionValues() {
    var _a, _b, _c, _d, _e;
    let systemConfig;
    let userConfig;
    if (this._configType === FilterConfigType.SYSTEM_CONFIG) {
      const entity = (_b = (_a = this._instanceElement) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.value;
      const fieldName = (_d = (_c = this._fieldElement) === null || _c === void 0 ? void 0 : _c.value) === null || _d === void 0 ? void 0 : _d.value;
      systemConfig = { entity, fieldName };
    }
    else if (this._configType === FilterConfigType.USER_CONFIG) {
      const description = (_e = this._descriptionElement) === null || _e === void 0 ? void 0 : _e.value;
      const type = this.getTypeValue();
      userConfig = { description, type };
    }
    return Object.assign(Object.assign(Object.assign({}, this._expressionItem), { systemConfig }), { userConfig });
  }
  isEnabled(value) {
    return this._configType === value;
  }
  isInformedInstance() {
    var _a, _b;
    return !StringUtils.isEmpty((_b = (_a = this._instanceElement) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.value);
  }
  save() {
    var _a;
    this._expressionItem = Object.assign(Object.assign({}, this.getExpressionValues()), { expression: (_a = this._expressionElement) === null || _a === void 0 ? void 0 : _a.value });
    this._promiseResolver(this._expressionItem);
    this._opened = false;
  }
  buildFilterExpression() {
    var _a;
    this._informedInstance = this.isInformedInstance();
    const expression = PersonalizedFilterUtils.buildFilterExpression(this.getExpressionValues());
    this._expressionElement.value = expression || ((_a = this._expressionItem) === null || _a === void 0 ? void 0 : _a.expression);
    this._canSave = this.getCanSave();
  }
  handleChangeInstance() {
    this._informedInstance = this.isInformedInstance();
    if (this._fieldElement != undefined && !StringUtils.isEmpty(this._fieldElement.value)) {
      this._fieldElement.value = null;
    }
    this.buildFilterExpression();
  }
  getInstanceCriteria() {
    var _a, _b;
    const value = (_b = (_a = this._instanceElement) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.value;
    return {
      expression: "this.NOMETAB = (SELECT NOMETAB FROM TDDINS WHERE NOMEINSTANCIA = ?)",
      params: [
        {
          name: "NOMEINSTANCIA",
          dataType: DataType.TEXT,
          value
        }
      ]
    };
  }
  onSearch({ mode, argument }, entity) {
    if (this._application == undefined || !this._opened) {
      return;
    }
    const isField = entity === FilterEntities.FIELD;
    const criteria = isField ? this.getInstanceCriteria() : undefined;
    const messageKey = `snkFilterParamConfig.label${isField ? "Field" : "Instance"}`;
    const entityDescription = this.getMessage(messageKey);
    const searchOptions = {
      descriptionFieldName: isField ? "DESCRCAMPO" : "DESCRINSTANCIA",
      codeFieldName: isField ? "NOMECAMPO" : "NOMEINSTANCIA",
      showInactives: false
    };
    const options = {
      entity,
      entityDescription,
      criteria,
      searchOptions
    };
    return new Promise((resolve) => {
      this._application.executePreparedSearch(mode, argument, options).then(res => resolve(res));
    });
  }
  getElementID(sufix) {
    return {
      [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(sufix)
    };
  }
  getCanSave() {
    var _a;
    if (this._configType === FilterConfigType.USER_CONFIG) {
      const description = (_a = this._descriptionElement) === null || _a === void 0 ? void 0 : _a.value;
      const type = this.getTypeValue();
      return !StringUtils.isEmpty(description) && !StringUtils.isEmpty(type);
    }
    return true;
  }
  componentWillLoad() {
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
  }
  render() {
    ElementIDUtils.addIDInfoIfNotExists(this._element, 'snkFilterParamConfig');
    return (h("ez-popup", Object.assign({ useHeader: false, size: "small", heightMode: "auto", opened: this._opened }, this.getElementID("popup")), h("ez-modal-container", Object.assign({ onEzModalAction: (evt) => {
        if (evt.detail === ModalAction.CLOSE)
          this.close();
      }, modalTitle: this.getMessage("snkFilterParamConfig.modalTitle") }, this.getElementID("modalContainer")), h("div", { class: "ez-flex" }, h("div", { class: "ez-col ez-col--sd-6 ez-flex--column" }, h("ez-radio-button", Object.assign({ value: this._configType, onEzChange: (evt) => this.changeDefinitionUsed(evt.detail) }, this.getElementID("systemConfigOption")), h("ez-radio-button-option", { label: this.getMessage("snkFilterParamConfig.labelSystemConfig"), value: FilterConfigType.SYSTEM_CONFIG })), h("ez-search", Object.assign({ ref: (ref) => this._instanceElement = ref, label: this.getMessage("snkFilterParamConfig.labelInstance"), enabled: this.isEnabled(FilterConfigType.SYSTEM_CONFIG), suppressEmptyOption: true, showOptionValue: false, showSelectedValue: false, onEzChange: () => this.handleChangeInstance(), optionLoader: (searchArgument) => this.onSearch(searchArgument, FilterEntities.INSTANCE) }, this.getElementID("configFindEntity"))), h("ez-search", Object.assign({ ref: (ref) => this._fieldElement = ref, label: this.getMessage("snkFilterParamConfig.labelField"), enabled: this.isEnabled(FilterConfigType.SYSTEM_CONFIG) && this._informedInstance, suppressEmptyOption: true, showOptionValue: false, showSelectedValue: false, onEzChange: () => this.buildFilterExpression(), optionLoader: (searchArgument) => this.onSearch(searchArgument, FilterEntities.FIELD) }, this.getElementID("configFindField")))), h("div", { class: "ez-flex ez-padding--medium" }, h("hr", { class: "ez-divider-vertical" })), h("div", { class: "ez-col ez-col--sd-6 ez-flex--column" }, h("ez-radio-button", Object.assign({ value: this._configType, onEzChange: (evt) => this.changeDefinitionUsed(evt.detail) }, this.getElementID("userConfigOption")), h("ez-radio-button-option", { label: this.getMessage("snkFilterParamConfig.labelUserConfig"), value: FilterConfigType.USER_CONFIG })), h("ez-text-input", Object.assign({ ref: (ref) => this._descriptionElement = ref, label: this.getMessage("snkFilterParamConfig.labelDescription"), enabled: this.isEnabled(FilterConfigType.USER_CONFIG), onEzChange: () => this.buildFilterExpression() }, this.getElementID("configParamLabel"))), h("ez-combo-box", Object.assign({ ref: (ref) => this._typeElement = ref, label: this.getMessage("snkFilterParamConfig.labelType"), enabled: this.isEnabled(FilterConfigType.USER_CONFIG), suppressEmptyOption: true, onEzChange: () => this.buildFilterExpression() }, this.getElementID("configParamType")), Object.keys(FilterUserConfigTypes).map((configType) => {
      return (h("option", { value: FilterUserConfigTypes[configType] }, this.getMessage(`snkFilterParamConfig.labelTypeValues.${configType.toLowerCase()}`)));
    })))), h("ez-text-area", Object.assign({ ref: (ref) => this._expressionElement = ref, class: "snk-filter-param-config__expression", label: this.getMessage("snkFilterParamConfig.labelExpression"), enabled: false }, this.getElementID("presentationExpression"))), h("div", { class: "ez-col ez-col--sd-12 ez-flex--justify-end ez-margin-vertical--small" }, h("ez-button", Object.assign({ class: "ez-padding-right--medium", label: this.getMessage("snkFilterParamConfig.labelCancel"), onClick: () => this.close() }, this.getElementID("cancelEditParam"))), h("ez-button", Object.assign({ class: "ez-button--primary", label: this.getMessage("snkFilterParamConfig.labelSave"), onClick: () => this.save(), enabled: this._canSave }, this.getElementID("saveEditParam")))))));
  }
  get _element() { return getElement(this); }
};
SnkFilterParamConfig.style = snkFilterParamConfigCss;

export { SnkExpressionGroup as snk_expression_group, SnkExpressionItem as snk_expression_item, SnkFilterFieldSearch as snk_filter_field_search, SnkFilterParamConfig as snk_filter_param_config };
