import { r as registerInstance, e as createEvent, h, f as Host, g as getElement, i as forceUpdate } from './index-e9c7ceaa.js';
import { DataType, StringUtils, ObjectUtils, ElementIDUtils, ErrorException, ApplicationContext, LockManager, LockManagerOperation, DateUtils, MaskFormatter, KeyboardManager, FloatingManager, ArrayUtils } from '@sankhyalabs/core';
import { EzScrollDirection } from '@sankhyalabs/ezui/dist/collection/components/ez-scroller/EzScrollDirection';
import { C as ConfigStorage } from './ConfigStorage-4eee53da.js';
import { P as PersonalizedFilterUtils } from './PersonalizedFilterUtils-d2439a9a.js';
import { toString } from '@sankhyalabs/core/dist/dataunit/metadata/DataType';
import { F as FilterItemType } from './filter-item-type.enum-d45e026f.js';
import { F as FilterOperand, D as DefaultFilter } from './index-8acbae97.js';
import { F as FilterNumberVariation } from './filterNumberVariation-8cee02ea.js';
import { ModalAction } from '@sankhyalabs/ezui/dist/collection/components/ez-modal-container';
import { ApplicationUtils } from '@sankhyalabs/ezui/dist/collection/utils';
import { A as ActionDefaultFilter } from './default-filters-50105e43.js';
import { F as FilterType } from './filter-type.enum-f6a8fe23.js';
import { g as getInvalidFilters } from './filter-validate-faf51fa9.js';
import './form-config-fetcher-baa89098.js';
import './DataFetcher-955ee53e.js';
import './PrintUtils-3e4ff0f5.js';
import '@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata';

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 = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    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 getElement(this); }
  static get watchers() { return {
    "filterConfig": ["observeFilterConfig"]
  }; }
};
SnkFilterBar.style = snkFilterBarCss;

const snkFilterItemCss = "ez-popover-core.sc-snk-filter-item{--ez-popover__box--z-index:var(--elevation--20, 20);--ez-popover__box--overlay-z-index:var(--elevation--16, 16)}ez-chip.sc-snk-filter-item{--ez-label-chip__label__container--margin:var(--space--2, 2px)}";

const SnkFilterItem = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.visibleChanged = createEvent(this, "visibleChanged", 7);
    this.filterChange = createEvent(this, "filterChange", 3);
    this._keyboardManager = undefined;
    this.detailIsVisible = undefined;
    this.config = undefined;
    this.getMessage = undefined;
    this.showChips = true;
  }
  observeDetailIsVisible(value) {
    this.visibleChanged.emit(value);
  }
  /**
   * Emitido quando o estado do filtro é alterado.
   */
  filterChangeListener(_event) {
    this.hideDetail();
  }
  /**
   * Exibe os detalhes de um item da lista.
   */
  async showUp(open = false) {
    var _a;
    this._filterItemElement.scrollIntoView({ behavior: "auto", block: "nearest", inline: "nearest" });
    if (open) {
      await ((_a = this._chipElement) === null || _a === void 0 ? void 0 : _a.setBlur());
      await this._popover.showUnder(this._chipElement);
      await this._filterDetail.setFocusField();
    }
  }
  /**
   * Oculta os detalhes de um item da lista.
   */
  async hideDetail() {
    var _a;
    await ((_a = this._popover) === null || _a === void 0 ? void 0 : _a.hide());
  }
  getConfigChanges() {
    var _a;
    const configToBeCleared = this.config;
    if (!!((_a = configToBeCleared.groupedItems) === null || _a === void 0 ? void 0 : _a.length)) {
      configToBeCleared.visible = false;
      configToBeCleared.groupedItems = configToBeCleared.groupedItems.map(item => (Object.assign(Object.assign({}, item), { visible: false })));
    }
    const hasMultiValues = configToBeCleared.type === FilterItemType.MULTI_LIST && Array.isArray(configToBeCleared.value);
    const newValue = hasMultiValues ? configToBeCleared.value.map((valueItem) => (Object.assign(Object.assign({}, valueItem), { check: false }))) : undefined;
    return Object.assign(Object.assign({}, configToBeCleared), { value: newValue });
  }
  clearFilter(event) {
    event === null || event === void 0 ? void 0 : event.stopPropagation();
    if (this.canClearFilter()) {
      const configChanged = this.getConfigChanges();
      this.filterChange.emit(configChanged);
    }
    else {
      this.togglePopover(event);
    }
  }
  async togglePopover(event) {
    event === null || event === void 0 ? void 0 : event.preventDefault();
    event === null || event === void 0 ? void 0 : event.stopPropagation();
    if (this.config.enabled === false) {
      return;
    }
    if (this.detailIsVisible) {
      await this.hideDetail();
    }
    else {
      await this.showUp(true);
    }
  }
  getLabel(isTooltipLabel = false) {
    var _a, _b;
    const { type, value, label, props, groupedItems = [] } = this.config;
    if (value || groupedItems.length) {
      if (type === FilterItemType.BINARY_SELECT) {
        const [optOne, optTwo] = props.options;
        const tooltip = this.getMessage('snkFilterBar.binarySelectTooltip');
        if (optOne.name === value) {
          return isTooltipLabel ? `${tooltip} ${String(optOne.label).toLowerCase()}` : optOne.label;
        }
        if (optTwo.name === value) {
          return isTooltipLabel ? `${tooltip} ${String(optTwo.label).toLowerCase()}` : optTwo.label;
        }
      }
      if (type === FilterItemType.MULTI_SELECT) {
        const opt = props.options.find(opt => opt.value === value);
        return `${label}: ${opt.label}`;
      }
      if (type === FilterItemType.PERIOD) {
        let { end, start } = value;
        if (typeof end === "string") {
          end = new Date(end);
          end.setMinutes(end.getMinutes() + end.getTimezoneOffset());
        }
        if (typeof start === "string") {
          start = new Date(start);
          start.setMinutes(start.getMinutes() + start.getTimezoneOffset());
        }
        const dateFormater = new Intl.DateTimeFormat("pt-BR");
        if (end && start) {
          const isSameYear = start.getFullYear() === end.getFullYear();
          const formatOptions = Object.assign({ day: '2-digit', month: '2-digit' }, ((!isSameYear || isTooltipLabel) && { year: '2-digit' }));
          const startLabel = DateUtils.formatDate(start, formatOptions);
          const endLabel = DateUtils.formatDate(end, formatOptions);
          if (isTooltipLabel) {
            return this.getMessage('snkFilterBar.fullPeriodTooltip', { LABEL: label, START_LABEL: startLabel, END_LABEL: endLabel });
          }
          return `${label}: ${startLabel} \u2192 ${endLabel}`;
        }
        else {
          if (start) {
            return `${label}: ${this.getMessage('snkFilterBar.onlyStartToltip')} ${dateFormater.format(start)}`;
          }
          else if (end) {
            return `${label}: ${this.getMessage('snkFilterBar.onlyEndToltip')} ${dateFormater.format(end)}`;
          }
          else {
            return label;
          }
        }
      }
      if (type === FilterItemType.SEARCH) {
        return `${label}: ${value.value} - ${value.label}`;
      }
      if (type === FilterItemType.PERSONALIZED) {
        const activeCount = this.calculateActiveCount(groupedItems);
        if (activeCount <= 0)
          return label;
        return `${label}: ${this.getMessage('snkFilterBar.personalizedCount', { activeCount })}`;
      }
      if (type === FilterItemType.MULTI_LIST) {
        const selectedOptions = ((_a = value.elements) !== null && _a !== void 0 ? _a : value).filter(item => item === null || item === void 0 ? void 0 : item.check);
        return this.getLabelFromCheckedOptions(selectedOptions, label, isTooltipLabel);
      }
      if (type === FilterItemType.CHECK_BOX_LIST) {
        const selectedValues = Object.entries(value !== null && value !== void 0 ? value : {})
          .filter(([_, value]) => value === true)
          .map(([key, _]) => key);
        const options = (_b = props.options) !== null && _b !== void 0 ? _b : [];
        const selectedOptions = options.filter(option => selectedValues.includes(option.name));
        return this.getLabelFromCheckedOptions(selectedOptions, label, isTooltipLabel);
      }
      if (type === FilterItemType.NUMBER && props.variation === FilterNumberVariation.INTERVAL) {
        const { start, end } = value;
        if (!isNaN(start) && !isNaN(end)) {
          return this.getMessage('snkFilterBar.fullIntervalTooltip', { LABEL: label, START_LABEL: start, END_LABEL: end });
        }
        if (!isNaN(start)) {
          return `${label}: ${this.getMessage('snkFilterBar.onlyStartToltip')} ${Number(start)}`;
        }
        if (!isNaN(end)) {
          return `${label}: ${this.getMessage('snkFilterBar.onlyEndToltip')} ${Number(end)}`;
        }
      }
      if (this.config.mask) {
        const _maskFormatter = new MaskFormatter(this.config.mask);
        return `${label}: ${_maskFormatter.format(value)}`;
      }
      return `${label}: ${value}`;
    }
    return label;
  }
  getLabelFromCheckedOptions(selectedOptions, label, isTooltipLabel) {
    const checkedAmount = selectedOptions.length;
    if (checkedAmount === 0) {
      return `${label}`;
    }
    if (checkedAmount > 1) {
      if (isTooltipLabel) {
        const selectedOptionsDescrptions = selectedOptions.map(item => item.label);
        return `${label}: ${selectedOptionsDescrptions.join(',')}`;
      }
      return `${label}: ${checkedAmount} ${this.getMessage('snkFilterBar.multiListToltip')}`;
    }
    return `${label}: ${selectedOptions[0].label}`;
  }
  calculateActiveCount(groupedItems) {
    return groupedItems.reduce((total, item) => {
      if (!!item.visible)
        return total + 1;
      return total;
    }, 0);
  }
  componentDidLoad() {
    if (this._filterItemElement) {
      ElementIDUtils.addIDInfo(this._filterItemElement);
      this._idSnkFilterDetail = `filterDetail_${this.config.id}`;
    }
  }
  canClearFilter() {
    const { value, groupedItems = [] } = this.config;
    if (value != undefined && this.config.type === FilterItemType.MULTI_LIST) {
      return value.some((item) => item.check);
    }
    return value !== undefined || groupedItems.some(item => item.visible);
  }
  getRightIconName() {
    if (this.canClearFilter())
      return "close";
    return this.detailIsVisible ? "chevron-up" : "chevron-down";
  }
  getLeftIconName() {
    switch (this.config.type) {
      case FilterItemType.PERIOD:
        return "calendar";
      case FilterItemType.PERSONALIZED:
        return "tune";
    }
    return undefined;
  }
  hasActiveElements(value) {
    var _a;
    const list = Array.isArray(value) ? value : value === null || value === void 0 ? void 0 : value.elements;
    return ((_a = list === null || list === void 0 ? void 0 : list.filter((val) => val === null || val === void 0 ? void 0 : val.check)) === null || _a === void 0 ? void 0 : _a.length) > 0;
  }
  hasActiveValue(config) {
    var _a, _b;
    if (config.type === FilterItemType.PERIOD) {
      return (!!((_a = config.value) === null || _a === void 0 ? void 0 : _a.start) || !!((_b = config.value) === null || _b === void 0 ? void 0 : _b.end));
    }
    return (config.type !== FilterItemType.MULTI_LIST && config.value !== undefined) || this.hasActiveElements(config.value);
  }
  getEnabledChip() {
    if (this.detailIsVisible) {
      return true;
    }
    if (this.config.type === FilterItemType.PERSONALIZED) {
      const { groupedItems = [] } = this.config;
      return groupedItems.some(item => item.visible);
    }
    return this.hasActiveValue(this.config);
  }
  async handleVisibilityPopover(event) {
    this.detailIsVisible = event.detail;
    if (!this.detailIsVisible) {
      await this._filterDetail.clearValue();
    }
  }
  getCustomMessage(key, params) {
    var _a;
    return (_a = this.getMessage) === null || _a === void 0 ? void 0 : _a.call(this, `snkFilterBar.filterModal.${key}`, params);
  }
  hasValue() {
    if (this.config.type === FilterItemType.MULTI_LIST) {
      return this.hasActiveElements(this.config.value);
    }
    return this.config.value !== undefined && this.config.value !== null;
  }
  getTooltipMessage() {
    var _a, _b;
    if (this.config.required && !this.hasValue()) {
      return {
        message: (_a = this.config.requiredMessage) !== null && _a !== void 0 ? _a : this.getCustomMessage('validations.requiredFilter'),
        type: 'error'
      };
    }
    if (this.config.enabled === false && this.config.disabledMessage) {
      return { message: this.config.disabledMessage, type: 'warning' };
    }
    return {
      message: (_b = this.config.defaultMessage) !== null && _b !== void 0 ? _b : this.getLabel(true),
      type: 'default'
    };
  }
  getTypeChip(type) {
    switch (type) {
      case 'default':
        return 'secondary';
      case 'warning':
        return 'warning-light';
      case 'error':
        return 'error-light';
      case 'success':
        return 'success-light';
      default:
        return type;
    }
  }
  initKeyboardManager() {
    this._keyboardManager = new KeyboardManager({ element: this._filterItemElement, propagate: true });
    this._keyboardManager
      .bind("Escape", () => this.hideDetail());
  }
  connectedCallback() {
    this.initKeyboardManager();
  }
  disconnectedCallback() {
    this._keyboardManager.unbindAllShortcutKeys();
  }
  render() {
    const leftIcon = this.getLeftIconName();
    const { type, message } = this.getTooltipMessage();
    return (h(Host, null, this.showChips && (h("ez-tooltip", { id: this.config.id, message: message, type: type, active: !this.detailIsVisible, strategy: "fixed" }, h("ez-chip", { id: this.config.id, ref: ref => this._chipElement = ref, label: this.getLabel(), value: this.getEnabledChip(), onClick: (event) => this.togglePopover(event), disableAutoUpdateValue: true, type: this.getTypeChip(type), enabled: this.config.enabled }, leftIcon && (h("ez-icon", { ref: ref => this._leftIconElement = ref, iconName: leftIcon, slot: "leftIcon" })), h("ez-icon", { ref: ref => this._rightIconElement = ref, iconName: this.getRightIconName(), slot: "rightIcon", id: "removeFilter", onClick: (event) => this.clearFilter(event) })))), h("ez-popover-core", { ref: elem => this._popover = elem, onEzVisibilityChange: (event) => this.handleVisibilityPopover(event) }, h("snk-filter-detail", { ref: ref => this._filterDetail = ref, key: this.config.id, config: this.config, getMessage: this.getMessage, class: "sc-snk-filter-bar snk-filter__popover ez-padding--small ez-elevation--16", "data-element-id": this._idSnkFilterDetail, showHardFixed: this.showChips && !this.config.required, removalBlocked: this.config.required }))));
  }
  get _filterItemElement() { return getElement(this); }
  static get watchers() { return {
    "detailIsVisible": ["observeDetailIsVisible"]
  }; }
};
SnkFilterItem.style = snkFilterItemCss;

const SHOW_MORE_ITEM_NAME = "__SHOWMORE__";
const MAX_FILTERS = 5;
const SnkFilterList = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.snkItemSelected = createEvent(this, "snkItemSelected", 7);
    this._preselection = -1;
    this.innerClickCheck = (_floatingContainer, node) => {
      if (node.id != FloatingManager.MODAL_ELEMENT_ID) {
        return true;
      }
      this._detailIsVisible = false;
      return false;
    };
    this._filterArgument = undefined;
    this._showAll = undefined;
    this.label = undefined;
    this.iconName = undefined;
    this.items = undefined;
    this.getMessage = undefined;
    this.emptyText = undefined;
    this.findFilterText = undefined;
    this.buttonClass = undefined;
  }
  showDetail() {
    this._preselection = -1;
    this._floatingID = FloatingManager.float(this._popover, this._popoverContainer, {
      autoClose: true,
      innerClickTest: this.innerClickCheck,
      backClickListener: () => this.onListCloseCallback(),
      useOverlay: true
    });
    this._detailIsVisible = true;
    this._showAll = false;
    this._filterArgument = "";
    this._filterInput.setFocus();
  }
  /**
   * Oculta os detalhes do componente snk-filter-list.
   */
  async hideDetail() {
    if (this._floatingID != undefined) {
      FloatingManager.close(this._floatingID);
    }
  }
  onListCloseCallback() {
    this._floatingID = undefined;
    this._detailIsVisible = false;
  }
  buttonClick() {
    if (this._detailIsVisible) {
      this.hideDetail();
    }
    else {
      this.showDetail();
    }
  }
  componentDidLoad() {
    if (this._element) {
      ElementIDUtils.addIDInfo(this._element);
    }
  }
  componentDidRender() {
    if (this._floatingID == undefined) {
      if (this._popover) {
        this._popover.remove();
      }
    }
  }
  buildIdElement(buttonElement, name) {
    if (!buttonElement)
      return;
    const dataElement = { id: name };
    buttonElement.removeAttribute(ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME);
    ElementIDUtils.addIDInfoIfNotExists(buttonElement, "filterItemList", dataElement);
  }
  buildItemElement(item) {
    const itemId = ++this._selectableItemsCount;
    return (h("button", { ref: elem => elem && this.buildIdElement(elem, item.label), id: `filter-item${itemId}`, onFocusin: () => this._preselection = itemId, class: `ez-col ez-col--sd-12 ez-align--middle ez-padding--small sc-snk-filter-bar snk-filter-bar__filter-list-item`, onClick: () => this.itemSelected(item.name), name: item.label, key: itemId }, item.iconName ? h("ez-icon", { iconName: item.iconName, size: "small", class: `ez-padding-right--extra-small sc-snk-filter-bar snk-filter-bar__filter-list-item__icon ${item.iconClass || ""}` }) : undefined, h("div", { class: `ez-text ez-text--medium ez-text--primary ez-padding--extra-small sc-snk-filter-bar snk-filter-bar__filter-list-item__label ${item.labelClass || ""}` }, item.label)));
  }
  itemSelected(itemName) {
    if (itemName === SHOW_MORE_ITEM_NAME) {
      this._showAll = true;
    }
    else {
      this.hideDetail();
      this.snkItemSelected.emit(itemName);
    }
  }
  getFilterItems() {
    const items = this.items ? ArrayUtils.applyStringFilter(this._filterArgument, this.items.filter(item => item.kind === "FILTER")) : [];
    if (items.length === 0) {
      return h("div", { class: "ez-text ez-text--medium ez-text--primary ez-padding--extra-small sc-snk-filter-bar snk-filter-bar__filter-list-items-container--empty" }, this.emptyText);
    }
    const hideItems = !this._filterArgument && !this._showAll && (items.length > MAX_FILTERS + 1);
    if (hideItems) {
      items.splice(MAX_FILTERS);
      items.push({ kind: "INTERNAL", label: this.getMessage("snkFilterList.showMore"), iconName: "dots-horizontal", name: SHOW_MORE_ITEM_NAME, iconClass: "snk-filter-bar__filter-list-item__icon--secondary", labelClass: "snk-filter-bar__filter-list-item__label--secondary" });
    }
    this._selectableItemsCount = 0;
    return h("div", { class: "sc-snk-filter-bar snk-filter-bar__filter-list-items-container" }, items.map(item => this.buildItemElement(item)));
  }
  getFooterItems() {
    return this.items.filter(item => item.kind === "FOOTER");
  }
  keyDownHandler(event) {
    switch (event.key) {
      case "ArrowDown":
        this.changePreselection(this._preselection + 1);
        //Paramos a propagação do evento para evitar scroll indesejado
        event.stopImmediatePropagation();
        event.stopPropagation();
        event.preventDefault();
        break;
      case "ArrowUp":
        this.changePreselection(this._preselection - 1);
        //Paramos a propagação do evento para evitar scroll indesejado
        event.stopImmediatePropagation();
        event.stopPropagation();
        event.preventDefault();
        break;
    }
  }
  changePreselection(newSelection) {
    if (newSelection < 0) {
      newSelection = this._selectableItemsCount;
    }
    this._preselection = newSelection > this._selectableItemsCount ? 0 : newSelection;
    if (this._preselection === 0) {
      this._filterInput.setFocus();
    }
    else {
      const item = this._element.querySelector(`#filter-item${this._preselection}`);
      if (item) {
        item.focus();
      }
    }
  }
  render() {
    return (h(Host, { class: "ez-flex ez-flex--column" }, h("ez-button", { class: this.buttonClass, label: this.label, onClick: () => this.buttonClick(), mode: this.iconName ? "icon" : undefined, iconName: this.iconName, size: "small" }, h("slot", { name: "leftIcon" })), h("section", { class: "ez-margin-top--small sc-snk-filter-bar snk-filter__popover-container", ref: elem => this._popoverContainer = elem }, h("div", { class: "sc-snk-filter-bar snk-filter__popover ez-padding--small ez-elevation--4", ref: elem => this._popover = elem }, h("ez-filter-input", { ref: ref => this._filterInput = ref, "data-element-id": "serachFilters", mode: "slim", label: this.findFilterText, value: this._filterArgument, onEzChange: (evt) => this._filterArgument = evt.detail, onFocus: () => this._preselection = 0 }), this.getFilterItems(), h("hr", { class: "sc-snk-filter-bar snk-filter__popover-rule" }), this.items ? this.getFooterItems().map(item => this.buildItemElement(item)) : undefined))));
  }
  get _element() { return getElement(this); }
};

const snkFilterModalCss = "ez-modal{--ez-modal-content-padding:24px 12px}.snk-filter-modal__container{min-width:344px;overflow:hidden}.snk-filter-modal__content{display:flex;flex-direction:column;gap:var(--space--medium, 12px);padding-right:var(--space--3xs, 4px)}.snk-filter-modal__collapsible-box{border:var(--border--small, 1px solid) var(--color--strokes, #DCE0E8);border-radius:var(--border--radius-medium);padding:var(--space--medium, 12px) var(--space--small, 6px)}.snk-filter-modal__rendered-items{max-height:760px}.snk-filter-modal__rendered-items::-webkit-scrollbar{width:var(--space--small);min-width:var(--space--small);max-width:var(--space--small)}";

const SnkFilterModal = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this._isUserSup = false;
    this.filters = [];
    this.filtersWithError = [];
    this.getMessage = undefined;
    this.configName = undefined;
    this.filterConfig = undefined;
    this.opened = false;
    this.applyFilters = undefined;
    this.closeModal = undefined;
    this.addPersonalizedFilter = undefined;
    this.editPersonalizedFilter = undefined;
    this.deletePersonalizedFilter = undefined;
    this.filtersToDelete = [];
    this.filterDefaultToDelete = undefined;
    this.disablePersonalizedFilter = undefined;
    this.filterCustomConfigInterceptor = undefined;
  }
  filterConfigChangeHandler(newValue) {
    this.filters = ObjectUtils.copy(newValue);
    this.validateFilters();
  }
  /**
   * Emitido quando um filtro personalizado é deletado.
   */
  deletePersonalizedFilterListener(event) {
    this.filtersToDelete.push(event.detail);
  }
  getCustomMessage(key, params) {
    var _a;
    return (_a = this.getMessage) === null || _a === void 0 ? void 0 : _a.call(this, `snkFilterBar.filterModal.${key}`, params);
  }
  //TODO: tratar clear all dos filtros personalizados
  handleClearAll() {
    const { customFilters, quickFilters, otherFilters, multiListFilters } = this.filters.reduce((acc, filter) => {
      if (filter.type === FilterItemType.MULTI_LIST) {
        acc.multiListFilters.push(filter);
        return acc;
      }
      if (filter.filterType === FilterType.QUICK_FILTER) {
        acc.quickFilters.push(filter);
        return acc;
      }
      if (filter.filterType === FilterType.CUSTOM_FILTER) {
        acc.customFilters.push(filter);
        return acc;
      }
      if (filter.filterType === FilterType.OTHER_FILTERS) {
        acc.otherFilters.push(filter);
        return acc;
      }
      return acc;
    }, { quickFilters: [], customFilters: [], otherFilters: [], multiListFilters: [] });
    this.handleClearFilterList(quickFilters);
    this.handleClearCustomFilters(customFilters);
    this.handleClearOthersFilters(otherFilters);
    multiListFilters.forEach(multiListFilter => this.handleClearSigleFilter(multiListFilter));
    forceUpdate(this);
  }
  handleClearOthersFilters(otherFilters) {
    this.filters = this.filters.map(filter => otherFilters.includes(filter) ? (Object.assign(Object.assign({}, filter), { value: undefined })) : filter);
  }
  handleClearCustomFilters(customFilters) {
    this.filters.forEach((filter, index) => {
      if (filter.filterType === FilterType.CUSTOM_FILTER)
        this.filters[index] = this.clearAllCustomFilter(customFilters).shift();
    });
  }
  clearAllCustomFilter(filterConfigSnapshot) {
    return filterConfigSnapshot.map(filterItem => {
      const copy = Object.assign({}, filterItem);
      delete copy.value;
      copy.visible = false;
      if (copy.groupedItems) {
        copy.groupedItems = this.clearAllCustomFilter(copy.groupedItems);
      }
      return copy;
    });
  }
  hasChangeToSave() {
    const hasChangesPersonalizedFilters = ObjectUtils.objectToString(this.filters) !== ObjectUtils.objectToString(this.filters);
    return hasChangesPersonalizedFilters;
  }
  handleClose() {
    const hasChangesToSave = this.hasChangeToSave();
    if (!hasChangesToSave) {
      this.closeModal();
      return;
    }
    return ApplicationUtils.confirm(this.getCustomMessage('validations.notSaved.title'), this.getCustomMessage('validations.notSaved.message')).then((cancelAction) => {
      if (cancelAction)
        this.closeModal();
    });
  }
  handleApplyFilters() {
    if (!this.validateFilters()) {
      return;
    }
    const filterPersonalized = this.filters.find(filter => filter.filterType === FilterType.CUSTOM_FILTER || filter.filterType === FilterType.DEFAULT_FILTER);
    if (this.isValidCustomFilter(filterPersonalized)) {
      this.applyFilters(this.filters);
    }
    if (this.filtersToDelete.length > 0) {
      this.filtersToDelete.forEach(filter => {
        this.deletePersonalizedFilter(filter, this.configName);
      });
      this.filtersToDelete = [];
    }
    if (this.filterDefaultToDelete) {
      this.deletePersonalizedFilter(this.filterDefaultToDelete, this.configName, true);
      this._defaultFilter = undefined;
      this.filterDefaultToDelete = undefined;
    }
  }
  isValidCustomFilter(filterPersonalized) {
    const isValid = PersonalizedFilterUtils.validateVariableValues(filterPersonalized);
    if (!isValid) {
      ApplicationUtils.alert(this.getCustomMessage('validations.notFullFilled.title'), this.getCustomMessage('validations.notFullFilled.message'));
      return false;
    }
    return true;
  }
  modalActionListener(evt) {
    const modalAction = evt.detail;
    switch (modalAction) {
      case ModalAction.CANCEL:
        this.handleClearAll();
        break;
      case ModalAction.OK:
        this.handleApplyFilters();
        break;
      case ModalAction.CLOSE:
        this.handleClose();
        break;
    }
  }
  handleFilterChange(event) {
    event.stopPropagation();
    const filterConfig = event.detail;
    let config = this.filters.map(filter => filter.id === filterConfig.id ? filterConfig : filter);
    if (this.filterCustomConfigInterceptor) {
      config = this.filterCustomConfigInterceptor(config);
    }
    this.filters = ObjectUtils.copy(config);
  }
  handleClearFilterList(filterList) {
    this.filters = this.filters.map(filter => filterList.includes(filter) ? (Object.assign(Object.assign({}, filter), { value: undefined })) : filter);
  }
  handleClearSigleFilter(filterItem) {
    if (FilterItemType.MULTI_LIST === filterItem.type) {
      let filterItemCopy = ObjectUtils.copy(filterItem);
      this.uncheckFilterValues(filterItemCopy.value);
      const filterListCopy = ObjectUtils.copy(this.filters);
      const index = filterListCopy.findIndex(item => item.id === filterItem.id);
      filterListCopy.splice(index, 1, filterItemCopy);
      this.filters = ObjectUtils.copy(filterListCopy);
      return;
    }
    if (FilterItemType.CHECK_BOX_LIST === filterItem.type) {
      const filterListCopy = ObjectUtils.copy(this.filters);
      filterListCopy.find(filter => filter.id === filterItem.id).value = undefined;
      this.filters = ObjectUtils.copy(filterListCopy);
      return;
    }
    const filter = this.filters.find(filter => filter.id === filterItem.id);
    filter.value = undefined;
    this.filters = ObjectUtils.copy(this.filters);
  }
  uncheckFilterValues(valueList) {
    valueList.forEach(value => {
      if (!!value) {
        value.check = false;
      }
    });
    return valueList;
  }
  validateFilters() {
    const notValidFilters = getInvalidFilters(this.filters);
    this.filtersWithError = notValidFilters.map(item => item.id);
    if (notValidFilters.length === 0) {
      return true;
    }
    notValidFilters.forEach(item => {
      const filterItem = this._element.querySelector(`#filter-item-${item.id}`);
      if (filterItem) {
        filterItem["errorMessage"] = item.requiredMessage || this.getCustomMessage('validations.requiredFilter');
      }
    });
    return false;
  }
  renderFilterItem(filterItem, fullRow) {
    return (h("snk-filter-modal-item", { key: `modal-item-${filterItem.id}`, class: fullRow ? 'ez-col ez-col--sd-12' : 'ez-col ez-col--sd-6 ez-padding--small', filterItem: filterItem, configName: this.configName, onFilterChange: (event) => this.handleFilterChange(event), onEditPersonalizedFilter: evt => this.editPersonalizedFilter(evt.detail), onAddPersonalizedFilter: () => this.addPersonalizedFilter() }));
  }
  isDefaultFilterNumberVariation(filter) {
    var _a;
    return filter.type === FilterItemType.NUMBER
      && (!filter.props.variation || ((_a = filter.props) === null || _a === void 0 ? void 0 : _a.variation) === FilterNumberVariation.DEFAULT);
  }
  mountFiltersLines(filters) {
    const MAX_LINE_LENGTH = 2;
    let currentLine = 0;
    let forceAddCurrent = false;
    const filtersLines = {};
    for (let curr = 0; curr < filters.length; curr++) {
      filtersLines[currentLine] = filtersLines[currentLine] || [];
      const item = filters[curr];
      const isLast = curr === filters.length - 1;
      const currentItemMatch = item.type === FilterItemType.TEXT || this.isDefaultFilterNumberVariation(item);
      const nextItemMatch = isLast ? false : filters[curr + 1].type === FilterItemType.TEXT || this.isDefaultFilterNumberVariation(filters[curr + 1]);
      if ((currentItemMatch && nextItemMatch) || forceAddCurrent) {
        filtersLines[currentLine].push(item);
        forceAddCurrent = filtersLines[currentLine].length < MAX_LINE_LENGTH;
        if (filtersLines[currentLine].length === MAX_LINE_LENGTH)
          ++currentLine;
        continue;
      }
      filtersLines[currentLine] = filtersLines[currentLine] || [];
      filtersLines[currentLine].push(item);
      ++currentLine;
    }
    return Object.values(filtersLines);
  }
  renderFilterLine(filters) {
    const fullLine = filters.length === 1;
    return filters.map((filter) => this.renderFilterItem(filter, fullLine));
  }
  getIformedFiltersCount(listItems) {
    let countInformedItens = 0;
    listItems.forEach(localItem => {
      var _a, _b, _c, _d, _e, _f, _g, _h;
      const item = this.filterConfig.find(filter => filter.id === localItem.id);
      if (FilterItemType.MULTI_LIST === item.type) {
        countInformedItens += (_e = (_d = (_c = ((_b = (_a = item.value) === null || _a === void 0 ? void 0 : _a.elements) !== null && _b !== void 0 ? _b : item.value)) === null || _c === void 0 ? void 0 : _c.filter(value => value === null || value === void 0 ? void 0 : value.check)) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0;
        return;
      }
      if (FilterItemType.CHECK_BOX_LIST === item.type) {
        countInformedItens += Object.entries((_f = item.value) !== null && _f !== void 0 ? _f : {})
          .filter(([_, value]) => value === true)
          .map(([key, _]) => key).length;
        return;
      }
      if (FilterItemType.PERIOD === item.type) {
        if (!!((_g = item.value) === null || _g === void 0 ? void 0 : _g.start) || !!((_h = item.value) === null || _h === void 0 ? void 0 : _h.end)) {
          countInformedItens++;
        }
        return;
      }
      if (item.groupedItems != undefined) {
        countInformedItens = item.groupedItems.filter(item => item.visible).length;
        return;
      }
      if (!!item.value) {
        countInformedItens++;
      }
    });
    return countInformedItens;
  }
  renderCollapsibleFilterBox(label, listItems, isSingleItem, shouldRenderFooter = true) {
    if (!listItems.length)
      return null;
    const appliedFilters = this.getIformedFiltersCount(listItems);
    const lines = this.mountFiltersLines(listItems);
    const countFiltersWithError = this.filtersWithError.filter(item => listItems.some(filter => filter.id === item)).length;
    return (h("ez-collapsible-box", { class: "snk-filter-modal__collapsible-box", headerSize: "medium", value: true, label: label }, h("div", { class: "ez-flex ez-flex--justify-end grow", slot: "rightSlot" }, !!appliedFilters && (h("ez-badge", { class: "ez-badge--primary-subtle", label: appliedFilters === null || appliedFilters === void 0 ? void 0 : appliedFilters.toString() })), !!countFiltersWithError && (h("ez-badge", { class: "ez-badge--error-subtle", label: countFiltersWithError === null || countFiltersWithError === void 0 ? void 0 : countFiltersWithError.toString() }))), h("div", { class: "ez-row snk-filter-modal__rendered-items" }, lines.map(this.renderFilterLine.bind(this))), shouldRenderFooter && (h("div", { class: "ez-flex ez-flex--justify-end grow" }, h("ez-button", { class: "ez-button--tertiary", size: "medium", label: this.getCustomMessage("clearModal"), onClick: () => isSingleItem ? this.handleClearSigleFilter(listItems[0]) : this.handleClearFilterList(listItems) })))));
  }
  handleDeleteFilter() {
    this._application.confirm(this.getMessage('snkPersonalizedFilter.deleteConfirm.title'), this.getMessage('snkPersonalizedFilter.info.deleteDefaultFilterConfirm'), "alert-circle-inverted", "critical").then((actionConfirmed) => {
      if (!actionConfirmed) {
        return;
      }
      this.filterDefaultToDelete = this._defaultFilter;
      this.filters = this.filters.filter(filter => filter.id !== FilterType.DEFAULT_FILTER);
    });
  }
  handleActionSelectedDefaultFilter({ detail: action }) {
    switch (action) {
      case ActionDefaultFilter.CREATE:
        this.addPersonalizedFilter(true);
        break;
      case ActionDefaultFilter.EDIT:
        this.editPersonalizedFilter(this._defaultFilter.id, true);
        break;
      case ActionDefaultFilter.REMOVE:
        this.handleDeleteFilter();
        break;
    }
  }
  getCustomFilter(filters) {
    const customFilters = filters.filter((filter) => filter.filterType === FilterType.CUSTOM_FILTER);
    return customFilters;
  }
  getDefaultFilter(filters) {
    const defaultFilter = filters.find((item) => item.id === DefaultFilter.id);
    return defaultFilter;
  }
  async componentWillLoad() {
    this._application = ApplicationContext.getContextValue('__SNK__APPLICATION__');
    this._isUserSup = await this._application.isUserSup();
    this.filters = ObjectUtils.copy(this.filterConfig);
  }
  componentWillRender() {
    this._modalTitle = this.getCustomMessage('title');
    this._okButtonLabel = this.getCustomMessage('okButtonLabel');
    this._cancelButtonLabel = this.getCustomMessage('cancelButtonLabel');
  }
  componentDidLoad() {
    this.validateFilters();
  }
  render() {
    this._defaultFilter = this._isUserSup ? this.getDefaultFilter(this.filters) : undefined;
    const customFilters = this.getCustomFilter(this.filters);
    const quickFilters = this.filters.filter(filter => filter.filterType === FilterType.QUICK_FILTER);
    const otherFilters = this.filters.filter(filter => filter.filterType === FilterType.OTHER_FILTERS);
    return (h("ez-modal", { opened: this.opened, modalSize: "col--sd-3", align: "right", heightMode: "full", closeEsc: true }, h("ez-modal-container", { class: "snk-filter-modal__container", modalTitle: this._modalTitle, cancelButtonLabel: this._cancelButtonLabel, okButtonLabel: this._okButtonLabel, onEzModalAction: this.modalActionListener.bind(this) }, h("div", { class: "snk-filter-modal__content ez-col--sd-12" }, this._isUserSup &&
      h("snk-default-filter", { getMessage: this.getCustomMessage.bind(this), hasDefaultFilter: !!this._defaultFilter, onActionSelected: this.handleActionSelectedDefaultFilter.bind(this) }), !this.disablePersonalizedFilter && this.renderCollapsibleFilterBox(this.getCustomMessage('customFilters'), customFilters, false, false), this.renderCollapsibleFilterBox(this.getCustomMessage('quickFilters'), quickFilters, false), otherFilters.map(filter => this.renderCollapsibleFilterBox(filter.label, [filter], true))))));
  }
  get _element() { return getElement(this); }
  static get watchers() { return {
    "filterConfig": ["filterConfigChangeHandler"]
  }; }
};
SnkFilterModal.style = snkFilterModalCss;

export { SnkFilterBar as snk_filter_bar, SnkFilterItem as snk_filter_item, SnkFilterList as snk_filter_list, SnkFilterModal as snk_filter_modal };
