import { proxyCustomElement, HTMLElement, createEvent, h, Host } from '@stencil/core/internal/client';
import { DataType, StringUtils, ObjectUtils, ElementIDUtils, ErrorException, ApplicationContext, LockManager, LockManagerOperation } from '@sankhyalabs/core';
import { EzScrollDirection } from '@sankhyalabs/ezui/dist/collection/components/ez-scroller/EzScrollDirection';
import { C as ConfigStorage } from './ConfigStorage.js';
import { a as FilterOperand, P as PersonalizedFilterUtils } from './PersonalizedFilterUtils.js';
import { toString } from '@sankhyalabs/core/dist/dataunit/metadata/DataType';
import { F as FilterItemType } from './filter-item-type.enum.js';
import { F as FilterNumberVariation } from './filterNumberVariation.js';
import { d as defineCustomElement$d } from './snk-default-filter2.js';
import { d as defineCustomElement$c } from './snk-expression-group2.js';
import { d as defineCustomElement$b } from './snk-expression-item2.js';
import { d as defineCustomElement$a } from './snk-filter-advanced-mode2.js';
import { d as defineCustomElement$9 } from './snk-filter-assistent-mode2.js';
import { d as defineCustomElement$8 } from './snk-filter-detail2.js';
import { d as defineCustomElement$7 } from './snk-filter-field-search2.js';
import { d as defineCustomElement$6 } from './snk-filter-item2.js';
import { d as defineCustomElement$5 } from './snk-filter-modal2.js';
import { d as defineCustomElement$4 } from './snk-filter-modal-item2.js';
import { d as defineCustomElement$3 } from './snk-filter-param-config2.js';
import { d as defineCustomElement$2 } from './snk-personalized-filter2.js';
import { d as defineCustomElement$1 } from './snk-simple-bar2.js';

const buildFilter = (item) => {
  switch (item.type) {
    case FilterItemType.DEFAULT_FILTER:
      return buildDefault(item);
    case FilterItemType.BINARY_SELECT:
      return buildBinary(item);
    case FilterItemType.MULTI_SELECT:
      return buildMultSelect(item);
    case FilterItemType.MULTI_LIST:
      return buildMultiList(item);
    case FilterItemType.PERIOD:
      return buildPeriod(item);
    case FilterItemType.SEARCH:
      return buildSearch(item);
    case FilterItemType.TEXT:
      return buildText(item);
    case FilterItemType.NUMBER:
      return buildNumber(item);
    case FilterItemType.PERSONALIZED:
      return buildPersonalized(item);
    case FilterItemType.CHECK_BOX_LIST:
      return buildCheckboxList(item);
    default:
      return undefined;
  }
};
function buildDefault(item) {
  return { name: item.id, expression: item.props.expression, params: [] };
}
function buildBinary(item) {
  const { id, value, props } = item;
  const options = props.options;
  const selectedOption = options.find(opt => opt.name === value);
  return { name: id, expression: selectedOption.expression, params: [] };
}
function buildMultSelect(item) {
  const { id, value, props } = item;
  return { name: id, expression: props.expression, params: [{ name: id, dataType: DataType.TEXT, value }] };
}
function buildMultiList(item) {
  const { id, value, props } = item;
  const parsedValues = parseMultiListValues(value);
  if (parsedValues.length > 0) {
    return {
      name: id,
      expression: props.expression,
      params: [{
          name: id,
          dataType: DataType.TEXT,
          value: JSON.stringify(parsedValues)
        }]
    };
  }
}
function buildCheckboxList(item) {
  var _a;
  const { id, value, props } = item;
  const selectedOptionNames = Object.entries(value !== null && value !== void 0 ? value : {})
    .filter(([_, valueChecked]) => valueChecked === true)
    .map(([key, _]) => key);
  const selectedOptionsObject = (_a = props.options) === null || _a === void 0 ? void 0 : _a.filter(option => selectedOptionNames.includes(option.name));
  return { name: id, expression: buildCheckboxListExpression(selectedOptionsObject), params: [] };
}
function buildCheckboxListExpression(options) {
  let expression = "";
  options.forEach((option, index) => {
    var _a;
    expression += ` ${index > 0 ? ((_a = option.operand) !== null && _a !== void 0 ? _a : 'OR') : ''} ${option.expression}`;
  });
  return expression.trim();
}
function parseMultiListValues(multiListValue) {
  var _a, _b;
  const value = (_b = (_a = multiListValue === null || multiListValue === void 0 ? void 0 : multiListValue.elements) !== null && _a !== void 0 ? _a : multiListValue === null || multiListValue === void 0 ? void 0 : multiListValue.members) !== null && _b !== void 0 ? _b : multiListValue;
  return value.filter(item => item === null || item === void 0 ? void 0 : item.check).map(({ id }) => Number.isNaN(+id) ? String(id) : Number(id));
}
function buildPeriod(item) {
  const { id, value, props } = item;
  let { end, start } = value;
  if (typeof end === "string") {
    end = new Date(end);
  }
  if (typeof start === "string") {
    start = new Date(start);
  }
  const params = [];
  let expression;
  if (end && start) {
    expression = props.expression.fullfill;
    params.push({ name: `${id}.START`, dataType: DataType.DATE, value: toString(DataType.DATE, start) }, { name: `${id}.END`, dataType: DataType.DATE, value: toString(DataType.DATE, end) });
  }
  else {
    if (start) {
      expression = props.expression.onlystart;
      params.push({ name: id, dataType: DataType.DATE, value: toString(DataType.DATE, start) });
    }
    else {
      expression = props.expression.onlyend;
      params.push({ name: id, dataType: DataType.DATE, value: toString(DataType.DATE, end) });
    }
  }
  return { name: id, expression, params };
}
function buildSearch(item) {
  const { id, value, props } = item;
  const expression = props.expression;
  return { name: id, expression, params: [{ name: id, dataType: DataType.TEXT, value: toString(DataType.TEXT, value === null || value === void 0 ? void 0 : value.value) }] };
}
function buildText(item) {
  let { id, value, props } = item;
  const expression = props.expression;
  if (!StringUtils.isEmpty(props.likeAs)) {
    value = buildLikeValue(value, props.likeAs);
  }
  return { name: id, expression, params: [{ name: id, dataType: DataType.TEXT, value: toString(DataType.TEXT, value) }] };
}
function buildNumber(item) {
  const { id, value, props } = item;
  const variation = props.variation;
  if (variation === FilterNumberVariation.INTERVAL) {
    const { start, end } = value !== null && value !== void 0 ? value : { start: 0, end: 0 };
    if (!isNaN(start) && !isNaN(end)) {
      return {
        name: id,
        expression: props.intervalExpression.fullfill,
        params: [
          { name: `${id}.START`, dataType: DataType.NUMBER, value: toString(DataType.NUMBER, start) },
          { name: `${id}.END`, dataType: DataType.NUMBER, value: toString(DataType.NUMBER, end) }
        ]
      };
    }
    if (!isNaN(start)) {
      return {
        name: id,
        expression: props.intervalExpression.onlystart,
        params: [
          { name: id, dataType: DataType.NUMBER, value: toString(DataType.NUMBER, start) }
        ]
      };
    }
    if (!isNaN(end)) {
      return {
        name: id,
        expression: props.intervalExpression.onlyend,
        params: [
          { name: id, dataType: DataType.NUMBER, value: toString(DataType.NUMBER, end) }
        ]
      };
    }
  }
  const expression = props.expression;
  return { name: id, expression, params: [{ name: id, dataType: DataType.NUMBER, value: toString(DataType.NUMBER, value) }] };
}
function buildLikeValue(valueAsString, likeAs) {
  if (likeAs === "CONTANIS") {
    return `%${valueAsString}%`;
  }
  else if (likeAs === "STARTS_WITH") {
    return `${valueAsString}%`;
  }
  else if (likeAs === "ENDS_WITH") {
    return `%${valueAsString}`;
  }
  return valueAsString;
}
function buildPersonalized(item) {
  const { id, groupedItems = [] } = item;
  const activeFilters = groupedItems.filter(groupItem => !!groupItem.visible);
  const filters = activeFilters.map(item => {
    var _a;
    const expression = item.props.expression;
    const params = (((_a = item.props.personalizedFilter) === null || _a === void 0 ? void 0 : _a.parameters) || []).map((param, index) => {
      const valuesArray = Array.from(item.value || 0);
      const dataType = param.dataType;
      let paramValue = (index >= 0 && index < valuesArray.length ? valuesArray[index] : null);
      if (paramValue != undefined && typeof paramValue === "object" && "value" in paramValue) {
        paramValue = paramValue["value"];
      }
      if (paramValue == undefined && dataType === DataType.BOOLEAN) {
        paramValue = false;
      }
      return { name: param.name, dataType, value: typeof paramValue === "string" ? paramValue : toString(dataType, paramValue) };
    });
    return { expression, name: item.id, params };
  });
  const expression = filters.map(filter => `(${filter.expression})`).join(` ${FilterOperand.AND} `);
  const params = filters.flatMap(filter => filter.params);
  return { name: id, expression, params };
}

const snkFilterBarCss = ".sc-snk-filter-bar-h{display:grid;grid-template-columns:1fr minmax(100px, 100%) 1fr 1fr;--snk-personalized-filter--z-index:var(--elevation--20, 20);--snk-personalized-filter--background-color:var(--background--xlight, #fff)}.snk-filter-bar__title.sc-snk-filter-bar{max-width:260px;display:inline-block;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;font-size:16px;font-family:var(--font-pattern, Arial);font-weight:var(--text-weight--large, 600);color:var(--color--title-primary, #2B3A54);margin-top:12px}[data-mode=\"hidden\"].sc-snk-filter-bar-h{width:0px;height:0px}[data-mode=\"button\"].sc-snk-filter-bar-h{grid-template-columns:1fr;width:fit-content}.snk-filter__popover-container.sc-snk-filter-bar{display:flex;cursor:auto}.filter-bar__personalized-filter.sc-snk-filter-bar{display:flex;flex-direction:column;position:fixed;top:0;left:0;width:100%;height:100%;overflow:auto;z-index:var(--snk-personalized-filter--z-index);background-color:var(--snk-personalized-filter--background-color)}.snk-filter__popover.sc-snk-filter-bar{display:flex;flex-direction:column;position:absolute;width:fit-content;height:fit-content;min-width:265px;background-color:var(--background--xlight, #fff);border-radius:var(--border--radius-medium, 12px);box-shadow:var(--shadow, 0px 0px 16px 0px #000)}.snk-filter-item__editor-header.sc-snk-filter-bar{flex-grow:1;font-weight:var(--text-weight--medium, 400);color:var(--color--title-primary, #2B3A54)}.snk-filter__popover-rule.sc-snk-filter-bar{border-style:solid;border-color:var(--color--disable-secondary, #F2F5F8);border-radius:1px;border-width:1px;width:100%}.editor__ez-check.sc-snk-filter-bar{--ez-check__label--padding-left:0}.snk-filter-item__editor-header-button.sc-snk-filter-bar{cursor:pointer;background-color:transparent;border:none;padding:3px;outline-color:var(--color--primary)}.snk-filter-bar__divider.sc-snk-filter-bar{margin-bottom:var(--space--small);height:80%}.snk-filter-bar__filter-item-container.sc-snk-filter-bar{display:flex;align-items:start;margin:var(--space--2, 2px) 0}.snk-filter-bar__scroller.sc-snk-filter-bar .sc-snk-filter-bar:first-child{margin-left:var(--space-extra-small, 3px)}.snk-filter-bar__filter-list-items-container.sc-snk-filter-bar{overflow-y:auto;max-height:360px;margin-top:var(--space--small, 6px)}.snk-filter-bar__filter-list-item.sc-snk-filter-bar{cursor:pointer;border-radius:var(--border--radius-small, 6px);border:none;background-color:transparent}.snk-filter-bar__filter-list-item__label.sc-snk-filter-bar{color:var(--title--primary)}.snk-filter-bar__filter-list-item__label--secondary.sc-snk-filter-bar{color:var(--text--primary)}.snk-filter-bar__filter-list-item__icon.sc-snk-filter-bar{--ez-icon--color:var(--title--primary)}.snk-filter-bar__filter-list-item__icon--secondary.sc-snk-filter-bar{--ez-icon--color:var(--text--secondary)}.snk-filter-bar__filter-list-item.sc-snk-filter-bar:focus-visible{outline:none;background-color:var(--background--medium)}.snk-filter-bar__filter-list-item.sc-snk-filter-bar:hover{background-color:var(--background--medium)}.snk-filter-bar__filter-list-items-container--empty.sc-snk-filter-bar{width:100%;height:100px;display:flex;justify-content:center;align-self:center;align-items:center}.snk-filter-bar__filter-list-items-button--active.sc-snk-filter-bar{position:relative}.snk-filter-bar__filter-list-items-button--active.sc-snk-filter-bar::after{display:flex;position:absolute;content:\"\";width:8px;height:8px;top:7px;left:17px;background-color:var(--icon--alert--color, #008561);border-radius:50%}.snk-filter-bar__filter-modal-item.sc-snk-filter-bar{--modal-item-border-width:2px;display:flex;flex-direction:row;margin-left:var(--modal-item-border-width);border-radius:var(--border--radius-medium, 12px);background-color:var(--background--medium, #f0f3f7);border:none;width:100%}.snk-filter-bar__filter-modal-item.sc-snk-filter-bar:focus-visible{outline:var(--color--primary) solid var(--modal-item-border-width)}.snk-filter-bar__filter-modal-item__check.sc-snk-filter-bar{width:auto}.snk-filter-bar__filter-modal-item__label.sc-snk-filter-bar{font-weight:var(--text-weight--medium)}.snk-filter-bar__filter-modal-content.sc-snk-filter-bar{display:grid;grid-template-rows:auto auto 1fr auto;width:99%;height:100%}";

const SnkFilterBar = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.configUpdated = createEvent(this, "configUpdated", 7);
    this._updateSequence = [];
    this._loadingPending = false;
    this._configUpdated = false;
    this._firstLoad = true;
    this._pendingVariables = false;
    this._isDefaultFilter = false;
    this._customfiltersToBeUpdated = [];
    this._resolveLoading = undefined;
    this._calculateSortIndex = (item) => {
      if (!item.visible)
        return 0;
      if (item.hardFixed)
        return 1000000; //campos Hard Fixed não variam a ordem
      let index = item.fixed ? 100000 : 0;
      index += this.hasValidValue(item) ? 10000 : 0;
      index += this._updateSequence.lastIndexOf(item.id) + 1;
      return index;
    };
    this._filtersComparator = (a, b) => {
      return this._calculateSortIndex(b) - this._calculateSortIndex(a);
    };
    this.enableLockManagerLoadingComp = false;
    this.customFilterBarConfig = undefined;
    this.dataUnit = undefined;
    this.title = undefined;
    this.configName = undefined;
    this.resourceID = undefined;
    this.mode = "regular";
    this.filterConfig = undefined;
    this.messagesBuilder = undefined;
    this.disablePersonalizedFilter = undefined;
    this.filterBarLegacyConfigName = undefined;
    this.autoLoad = undefined;
    this.afterApplyConfig = undefined;
    this.filterCustomConfig = undefined;
    this.filterCustomConfigInterceptor = undefined;
    this.allowDefault = undefined;
    this.scrollerLocked = false;
    this.showPersonalizedFilter = false;
    this.personalizedFilterId = undefined;
    this.isFilterModalOpen = false;
  }
  hasValidValue(item) {
    var _a, _b;
    if (item.value === undefined || item.value === null) {
      return false;
    }
    if (item.type === FilterItemType.PERIOD) {
      return (!!((_a = item.value) === null || _a === void 0 ? void 0 : _a.start) || !!((_b = item.value) === null || _b === void 0 ? void 0 : _b.end));
    }
    if (item.groupedItems) {
      return true;
    }
    if (!Array.isArray(item.value)) {
      return true;
    }
    return item.value.some(filterItem => filterItem.check === true);
  }
  observeFilterConfig(newValue, oldValue) {
    if (ObjectUtils.equals(newValue, oldValue))
      return;
    this.handleFilterConfigsChanged(oldValue, newValue);
  }
  handleFilterConfigsChanged(oldValue, newValue) {
    if (oldValue != undefined && newValue == undefined) {
      this._loadingPending = true;
      this._configUpdated = true;
    }
    else {
      const oldItems = new Map(oldValue ? oldValue.map(item => [item.id, item]) : undefined);
      if (oldItems.size === 0 && newValue.length > 0) {
        this._loadingPending = true;
        this._configUpdated = false;
      }
      else {
        newValue.forEach(newItem => {
          const oldItem = oldItems.get(newItem.id);
          if (oldItem != undefined) {
            this._configUpdated = this._configUpdated || ObjectUtils.objectToString(oldItem) != ObjectUtils.objectToString(newItem);
            this._loadingPending = this._loadingPending || ObjectUtils.objectToString(oldItem.value) !== ObjectUtils.objectToString(newItem.value);
            if (!this._loadingPending) {
              const groupedChanged = ObjectUtils.objectToString(oldItem.groupedItems) != ObjectUtils.objectToString(newItem.groupedItems);
              this._configUpdated = this._configUpdated || groupedChanged;
              this._loadingPending = this._loadingPending || groupedChanged;
            }
          }
          else {
            this._configUpdated = true;
            this._loadingPending = this._loadingPending || newItem.value != undefined;
          }
        });
      }
    }
    if (this._loadingPending || this._configUpdated)
      this.configUpdated.emit(newValue);
    this.processAfterUpdateConfig();
  }
  /**
   * @description Faz o recarregamento da barra de filtros buscando o state no servidor.
   * @async
   * @return {Promise<void>} Retorna uma Promise que resolve quando o recarregamento for concluído.
   */
  async reload() {
    this.loadConfigFromStorage(true);
  }
  /**
   * @description Retorna um item de filtro pelo ID.
   * @async
   * @param {string} id - ID do item de filtro.
   * @returns {Promise<SnkFilterItemConfig | undefined>} O item de filtro correspondente ou undefined se não for encontrado.
   */
  async getFilterItem(id) {
    const item = this.filterConfig.find(item => item.id === id);
    return Promise.resolve(ObjectUtils.copy(item));
  }
  /**
  * @description Atualiza um item do filtro.
  * @async
  * @param {SnkFilterItemConfig} newFilterItem - Item com as informações atualizadas, caso o item não seja encontrado no array, ele não será modificado.
  * @return {Promise<void>} Retorna uma Promise que resolve quando a atualização for concluída.
  */
  async updateFilterItem(newFilterItem) {
    const itemIndex = this.filterConfig.findIndex(item => item.id === newFilterItem.id);
    if (itemIndex == -1) {
      console.warn("[SnkFilterBar.updateFilterItem] " + this.getMessage("snkFilterBar.filterItem.updateFilterItemNotFound"));
      return Promise.resolve();
    }
    this._loadingPending = true;
    this.updateFilter(newFilterItem);
    return Promise.resolve();
  }
  /**
  * @description Adiciona um item de filtro.
  * @async
  * @param {SnkFilterItemConfig} filterItem - Item a ser adicionado, caso o item já exista com o ID, ele não será adicionado novamente.
  * @return {Promise<void>} Retorna uma Promise que resolve quando o item for adicionado.
  */
  async addFilterItem(filterItem) {
    const itemIndex = this.filterConfig.findIndex(item => item.id === filterItem.id);
    if (itemIndex > -1) {
      console.warn("[SnkFilterBar.addFilterItem] " + this.getMessage("snkFilterBar.filterItem.addFilterItemExists"));
      return Promise.resolve();
    }
    this.filterConfig.push(filterItem);
    this._loadingPending = true;
    this.updateFilter(filterItem);
    return Promise.resolve();
  }
  /**
  * @description Remove um item de filtro.
  * @async
  * @param {string} filterID - ID do item a ser removido.
  * @returns {Promise<SnkFilterItemConfig|undefined>} Retorna o item de filtro removido, ou undefined caso não seja encontrado.
  */
  async removeFilterItem(filterID) {
    const itemIndex = this.filterConfig.findIndex(item => item.id === filterID);
    if (itemIndex == -1) {
      console.warn("[SnkFilterBar.removeFilterItem] " + this.getMessage("snkFilterBar.filterItem.removeFilterItemNotFound"));
      return Promise.resolve(undefined);
    }
    const itemToRemove = this.filterConfig[itemIndex];
    this.filterConfig = this.filterConfig.filter(item => item.id !== filterID);
    return Promise.resolve(itemToRemove);
  }
  componentDidLoad() {
    if (this._element) {
      const dataInfo = { dataUnit: this.dataUnit };
      ElementIDUtils.addIDInfo(this._element, null, dataInfo);
    }
  }
  processPendingFilter() {
    if (this._pendingVariables) {
      const popUp = this._element.querySelector("#filter-PERSONALIZED_FILTER_GROUP");
      if (popUp) {
        popUp.showUp(true).then(() => {
          this.processAfterUpdateConfig();
        });
      }
    }
    else {
      this.processAfterUpdateConfig();
    }
  }
  getPersonalizedFilterItem() {
    return this.filterConfig.find(item => item.type === FilterItemType.PERSONALIZED);
  }
  async processAfterUpdateConfig() {
    var _a;
    if (this._loadingPending) {
      if (await this._application.isLoadedByPk() && !this._configUpdated)
        return;
      const personalizedFilter = this.getPersonalizedFilterItem();
      this._pendingVariables = !PersonalizedFilterUtils.validateVariableValues(personalizedFilter);
      if (this._pendingVariables) {
        return;
      }
      this._loadingPending = false;
      this.doLoadData();
    }
    if (this._configUpdated) {
      this._configUpdated = false;
      ConfigStorage.saveFilterBarConfig(this.filterConfig, this.configName, this.resourceID);
      (_a = this.afterApplyConfig) === null || _a === void 0 ? void 0 : _a.call(this);
    }
  }
  async doLoadData(forceReload = false) {
    try {
      if (this._firstLoad && this.autoLoad === false) {
        return;
      }
      if (this._firstLoad && !forceReload && this.autoLoad === undefined) {
        let autoLoad = await this._application.getBooleanParam("global.carregar.registros.iniciar.tela");
        if (!autoLoad) {
          return;
        }
      }
      this.dataUnit.loadData(undefined, undefined, true);
    }
    finally {
      this._firstLoad = false;
    }
  }
  /**
   * Conforme mecanismo de mensagens, é possível customizar as mensagens dos blocos de construção
   * através de um pequeno módulo 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-bar.msg.ts"
   */
  getMessage(key, params, defaultValue) {
    var _a;
    if (this.messagesBuilder == undefined && this._application) {
      this.messagesBuilder = this._application.messagesBuilder;
    }
    return ((_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage(key, params)) || defaultValue;
  }
  async getFilters() {
    return this.getFilter(null);
  }
  getFilter(_dataUnit) {
    var _a;
    const filters = [];
    (_a = this.filterConfig) === null || _a === void 0 ? void 0 : _a.filter(item => this.isActiveFilter(item)).forEach(item => {
      const filter = buildFilter(item);
      if (filter) {
        filters.push(filter);
      }
    });
    return filters;
  }
  isActiveFilter(item) {
    /*
      - O filtro padrão também deve sempre ser condiderado ativo, pois, sempre deve
        ser aplicado.
    */
    if (item.type === FilterItemType.DEFAULT_FILTER) {
      return true;
    }
    return this.filterActiveFilter(item) && this.hasValidValue(item);
  }
  async registryFilterProvider() {
    this.dataUnit.addFilterProvider(this);
    if (this.filterConfig) {
      await this.doLoadData();
    }
  }
  itemFocused(selectedItem) {
    this._element.querySelectorAll("snk-filter-item,snk-filter-list").forEach(item => {
      if (item.id === selectedItem) {
        if (item.tagName.toLowerCase() === "snk-filter-item" && item.getClientRects()[0].x < 0) {
          item.scrollIntoView({ behavior: "auto", inline: 'nearest' });
        }
      }
      else {
        item["hideDetail"]();
      }
    });
  }
  filterActiveFilter(item) {
    return item.visible || item.removalBlocked;
  }
  filterPersonalizedItems(item) {
    return item.type === FilterItemType.PERSONALIZED;
  }
  getPersonalizedFilterVariableItems() {
    return this.filterConfig
      .filter(this.filterPersonalizedItems)
      .map(item => {
      const itemId = `filter-${item.id}`;
      return (h("snk-filter-item", { key: item.id, id: itemId, config: Object.assign({}, item), onFocusin: () => this.itemFocused(itemId), onVisibleChanged: (evt) => this.scrollerLocked = evt.detail, onFilterChange: (event) => this.updateFilter(event.detail), getMessage: (key, props) => this.getMessage(key, props), showChips: false }));
    });
  }
  getFilterItems() {
    const pinnedItems = [];
    const unpinnedItems = [];
    this.filterConfig.sort((a, b) => this._filtersComparator(a, b))
      .filter(this.filterActiveFilter)
      .forEach((item) => {
      item = ObjectUtils.copy(item);
      const itemId = `filter-${item.id}`;
      const filterItem = (h("snk-filter-item", { onVisibleChanged: (evt) => this.scrollerLocked = evt.detail, onFilterChange: (event) => this.updateFilter(event.detail), onFocusin: () => this.itemFocused(itemId), id: itemId, config: item, class: "ez-margin-horizontal--extra-small", getMessage: (key, props) => this.getMessage(key, props), key: item.id }));
      if (item.fixed || item.hardFixed || item.required) {
        pinnedItems.push(filterItem);
      }
      else {
        unpinnedItems.push(filterItem);
      }
      return filterItem;
    });
    const elements = [];
    elements.push(...pinnedItems.reverse());
    if (pinnedItems.length > 0 && unpinnedItems.length > 0) {
      elements.push(h("hr", { class: "ez-margin-horizontal--small ez-margin-vertical--auto ez-divider-vertical ez-divider--dark snk-filter-bar__divider" }));
    }
    elements.push(...unpinnedItems);
    return elements;
  }
  calculateUpdateSequence(item) {
    if (item) {
      this._updateSequence = this._updateSequence.filter(itemId => item.id !== itemId);
      this._updateSequence.push(item.id);
    }
  }
  normalizeItem(item) {
    const normalized = Object.assign({}, item);
    const isPersonalizedFilter = item.type === FilterItemType.PERSONALIZED;
    const hasNormalizedGroupedItems = (normalized.value === undefined && normalized.groupedItems);
    if (isPersonalizedFilter && hasNormalizedGroupedItems) {
      normalized.value = normalized.groupedItems.filter(groupItem => !!groupItem.visible).length;
    }
    const optionals = ["props", "value", "hardFixed", "fixed"];
    optionals.forEach(prop => {
      if (prop === "value" && isPersonalizedFilter) {
        return;
      }
      if (normalized[prop] == undefined) {
        delete normalized[prop];
      }
    });
    if (normalized.value === "" && !isPersonalizedFilter) {
      delete normalized.value;
    }
    return normalized;
  }
  updateFilter(newItem) {
    const normalizedNewItem = this.normalizeItem(newItem);
    let config = this.filterConfig.map(item => {
      if (item.id !== normalizedNewItem.id) {
        return item;
      }
      if (ObjectUtils.objectToString(item) == ObjectUtils.objectToString(normalizedNewItem)) {
        this.calculateUpdateSequence(normalizedNewItem);
      }
      return normalizedNewItem;
    }).sort((a, b) => this._filtersComparator(a, b));
    if (this.filterCustomConfigInterceptor) {
      config = this.filterCustomConfigInterceptor(config);
    }
    this.filterConfig = config;
  }
  loadPermitions() {
    this._application.isUserSup().then(value => this.allowDefault = value);
  }
  addFilterBarLegacyConfigName() {
    if (this.filterBarLegacyConfigName) {
      ConfigStorage.addFilterBarLegacyConfig(this.configName, this.filterBarLegacyConfigName);
    }
  }
  async loadConfigFromStorage(clearCache) {
    try {
      if (clearCache) {
        await ConfigStorage.deleteFilterBarConfigCache(this.configName, this.resourceID);
      }
      let config;
      if (this.customFilterBarConfig) {
        config = await this.customFilterBarConfig(this.configName, this.resourceID, { contextURI: this.dataUnit.name });
      }
      else {
        config = await ConfigStorage.loadFilterBarConfig(this.configName, this.resourceID, { contextURI: this.dataUnit.name });
      }
      if (this.filterCustomConfig) {
        config = [...this.filterCustomConfig, ...config];
      }
      if (this.filterCustomConfigInterceptor) {
        config = this.filterCustomConfigInterceptor(config);
      }
      this.filterConfig = config.map(item => this.normalizeItem(item));
      this.filterConfig.sort((a, b) => this._filtersComparator(a, b));
    }
    catch (e) {
      throw new ErrorException(this.getMessage("snkFilterBar.failToLoadConfig"), e);
    }
  }
  async attachDataUnit() {
    if (this.dataUnit == undefined) {
      let parent = this._element.parentElement;
      while (parent) {
        if (parent.tagName.toUpperCase() === "SNK-DATA-UNIT") {
          const snkDataUnit = parent;
          this.dataUnit = snkDataUnit.dataUnit;
          if (this.dataUnit) {
            await this.registryFilterProvider();
          }
          else {
            snkDataUnit.addEventListener("dataUnitReady", async (evt) => {
              this.dataUnit = evt.detail;
              await this.registryFilterProvider();
            });
          }
          break;
        }
      }
      parent = parent.parentElement;
    }
    else {
      await this.registryFilterProvider();
    }
  }
  /**
  * Emitido quando acontece a alteração do estado do filtro.
  */
  filterChangeListener(evt) {
    this.updateFilter(evt.detail);
  }
  /**
   * Escuta quando há um filtro do tipo pesquisa retorna um valor vazio.
   */
  async emptySearchListener(_evt) {
    await this.showPersonalizedFilterItem();
  }
  /**
   * @description Abre o modal de filtros.
   * @async
  */
  async showFilterModal() {
    if (this.isFilterModalOpen) {
      return; // Evita abrir múltiplos modais
    }
    this.isFilterModalOpen = true;
  }
  async showPersonalizedFilterItem() {
    const popUp = this._element.querySelector('#filter-PERSONALIZED_FILTER_GROUP');
    await (popUp === null || popUp === void 0 ? void 0 : popUp.showUp(true));
  }
  addPersonalizedFilter(isDefault = false) {
    this.isFilterModalOpen = false;
    this._isDefaultFilter = isDefault;
    this.personalizedFilterId = undefined;
    this.showPersonalizedFilter = true;
    window.requestAnimationFrame(() => {
      this._elPersonalizedFilter.createPersonalizedFilter();
    });
  }
  editPersonalizedFilter(id, isDefault = false) {
    this.isFilterModalOpen = false;
    this._isDefaultFilter = isDefault;
    this.showPersonalizedFilter = true;
    this.personalizedFilterId = id;
  }
  deletePersonalizedFilter(filter, filterItemType, configName, isDefault = false) {
    if (isDefault) {
      ConfigStorage.removeDefaultFilter(filter, this.resourceID, configName);
      this._isDefaultFilter = false;
      return;
    }
    if (filterItemType === FilterItemType.PERSONALIZED) {
      ConfigStorage.removePersonalizedFilter(filter, this.resourceID, configName);
    }
  }
  closeFilterModal() {
    this.isFilterModalOpen = false;
  }
  applyFiltersFromModal(filters) {
    var _a;
    this.filterConfig = filters.map(this.normalizeItem).sort((a, b) => this._filtersComparator(a, b));
    (_a = this.afterApplyConfig) === null || _a === void 0 ? void 0 : _a.call(this);
    this.isFilterModalOpen = false;
  }
  handleHidePersonalizedFilter(reloadFilterBar) {
    if (reloadFilterBar) {
      this.loadConfigFromStorage().then(() => {
        this.hidePersonalizedFilter();
      });
    }
    else {
      this.hidePersonalizedFilter();
    }
  }
  hidePersonalizedFilter() {
    this.personalizedFilterId = undefined;
    this.showPersonalizedFilter = false;
    this._isDefaultFilter = false;
  }
  async componentWillLoad() {
    var _a;
    try {
      this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
      await this.attachDataUnit();
      if (this._application) {
        if (this._application.enableLockManagerLoadingApp && this.enableLockManagerLoadingComp) {
          const appLoadLockerID = LockManager.addLockManagerCtxId(this._element);
          this._resolveLoading = LockManager.lock(appLoadLockerID, LockManagerOperation.APP_LOADING);
        }
        await Promise.all([
          this.loadPermitions(),
          this.addFilterBarLegacyConfigName(),
          this.loadConfigFromStorage(),
        ]);
      }
    }
    finally {
      (_a = this._resolveLoading) === null || _a === void 0 ? void 0 : _a.call(this);
    }
  }
  componentDidRender() {
    this.processPendingFilter();
  }
  render() {
    if (!this.dataUnit || !this.filterConfig || this.filterConfig.length === 0) {
      return undefined;
    }
    if (this.showPersonalizedFilter) {
      return h("snk-personalized-filter", { class: "filter-bar__personalized-filter", filterId: this.personalizedFilterId, ref: (el) => this._elPersonalizedFilter = el, isDefaultFilter: this._isDefaultFilter, onEzCancel: () => this.handleHidePersonalizedFilter(false), onEzAfterSave: () => this.handleHidePersonalizedFilter(true), entityUri: this.dataUnit.name, configName: this.configName, resourceID: this.resourceID });
    }
    let filtersConfigCopy = ObjectUtils.copy(this.filterConfig);
    filtersConfigCopy = filtersConfigCopy.sort((itemA, itemB) => {
      return itemA.originOrder - itemB.originOrder;
    });
    if (this.mode !== "regular") {
      return (h(Host, { "data-mode": this.mode }, this.getPersonalizedFilterVariableItems(), this.mode === 'button' && (h("ez-button", { class: "ez-margin-left--medium", size: "small", label: this.getMessage('snkFilterBar.filters', undefined, this.getMessage("snkFilterBar.filters")), onClick: this.showFilterModal.bind(this) })), h("snk-filter-modal", { opened: this.isFilterModalOpen, filterConfig: this.filterConfig, configName: this.configName, disablePersonalizedFilter: this.disablePersonalizedFilter, getMessage: (key, props) => this.getMessage(key, props), applyFilters: (filters) => this.applyFiltersFromModal(filters), closeModal: () => this.closeFilterModal(), addPersonalizedFilter: (isDefault) => this.addPersonalizedFilter(isDefault), editPersonalizedFilter: (id, isDefault) => this.editPersonalizedFilter(id, isDefault), deletePersonalizedFilter: (filter, configName, isDefault) => this.deletePersonalizedFilter(filter, FilterItemType.PERSONALIZED, configName, isDefault), filterCustomConfigInterceptor: this.filterCustomConfigInterceptor })));
    }
    return (h(Host, null, h("div", null, h("span", { class: "snk-filter-bar__title", title: this.title, "data-tooltip": this.title, "data-flow": "bottom" }, this.title)), h("ez-scroller", { class: "snk-filter-bar__scroller", direction: EzScrollDirection.HORIZONTAL, activeShadow: true, locked: this.scrollerLocked }, h("section", { class: "snk-filter-bar__filter-item-container" }, this.getFilterItems())), h("ez-button", { class: "ez-padding-left--medium ez-margin-top--extra-small", size: "small", label: this.getMessage('snkFilterBar.filters', undefined, this.getMessage("snkFilterBar.filters")), onClick: this.showFilterModal.bind(this) }, h("ez-icon", { slot: "leftIcon", iconName: "plus", class: "ez-padding-right--small" })), h("snk-filter-modal", { opened: this.isFilterModalOpen, filterConfig: this.filterConfig, configName: this.configName, disablePersonalizedFilter: this.disablePersonalizedFilter, getMessage: (key, props) => this.getMessage(key, props), applyFilters: (filters) => this.applyFiltersFromModal(filters), closeModal: () => this.closeFilterModal(), addPersonalizedFilter: (isDefault) => this.addPersonalizedFilter(isDefault), editPersonalizedFilter: (id, isDefault) => this.editPersonalizedFilter(id, isDefault), deletePersonalizedFilter: (filter, configName, isDefault) => this.deletePersonalizedFilter(filter, FilterItemType.PERSONALIZED, configName, isDefault), filterCustomConfigInterceptor: this.filterCustomConfigInterceptor })));
  }
  get _element() { return this; }
  static get watchers() { return {
    "filterConfig": ["observeFilterConfig"]
  }; }
  static get style() { return snkFilterBarCss; }
}, [2, "snk-filter-bar", {
    "enableLockManagerLoadingComp": [4, "enable-lock-manager-loading-comp"],
    "customFilterBarConfig": [16],
    "dataUnit": [1040],
    "title": [1],
    "configName": [1, "config-name"],
    "resourceID": [1, "resource-i-d"],
    "mode": [1],
    "filterConfig": [1040],
    "messagesBuilder": [1040],
    "disablePersonalizedFilter": [4, "disable-personalized-filter"],
    "filterBarLegacyConfigName": [1, "filter-bar-legacy-config-name"],
    "autoLoad": [4, "auto-load"],
    "afterApplyConfig": [16],
    "filterCustomConfig": [16],
    "filterCustomConfigInterceptor": [16],
    "allowDefault": [32],
    "scrollerLocked": [32],
    "showPersonalizedFilter": [32],
    "personalizedFilterId": [32],
    "isFilterModalOpen": [32],
    "reload": [64],
    "getFilterItem": [64],
    "updateFilterItem": [64],
    "addFilterItem": [64],
    "removeFilterItem": [64],
    "getFilters": [64],
    "showFilterModal": [64]
  }, [[0, "filterChange", "filterChangeListener"], [8, "ezEmptySearch", "emptySearchListener"]]]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-filter-bar", "snk-default-filter", "snk-expression-group", "snk-expression-item", "snk-filter-advanced-mode", "snk-filter-assistent-mode", "snk-filter-detail", "snk-filter-field-search", "snk-filter-item", "snk-filter-modal", "snk-filter-modal-item", "snk-filter-param-config", "snk-personalized-filter", "snk-simple-bar"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-filter-bar":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkFilterBar);
      }
      break;
    case "snk-default-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$d();
      }
      break;
    case "snk-expression-group":
      if (!customElements.get(tagName)) {
        defineCustomElement$c();
      }
      break;
    case "snk-expression-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$b();
      }
      break;
    case "snk-filter-advanced-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "snk-filter-assistent-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "snk-filter-detail":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "snk-filter-field-search":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "snk-filter-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "snk-filter-modal":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "snk-filter-modal-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "snk-filter-param-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "snk-personalized-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
    case "snk-simple-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$1();
      }
      break;
  } });
}

export { SnkFilterBar as S, defineCustomElement as d };
