import { r as registerInstance, h, f as Host, g as getElement, e as createEvent } from './index-e9c7ceaa.js';
import { ApplicationContext, StringUtils, ErrorException, WarningException, ObjectUtils, DateUtils, ServiceUtils, StorageType, ArrayUtils, ElementIDUtils } from '@sankhyalabs/core';
import { D as DataFetcher } from './DataFetcher-955ee53e.js';
import { P as ParamType } from './ParamType-d5152b06.js';
import './ISave-c8bf12c4.js';
import './index-b40568ff.js';
import '@sankhyalabs/ezui/dist/collection/utils/constants';
import '@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata';
import './dataunit-fetcher-6cacb959.js';
import './filter-item-type.enum-d45e026f.js';
import { F as FormConfigFetcher } from './form-config-fetcher-baa89098.js';
import { O as ORDER_VALUES } from './constants-7b422de0.js';
import { g as getSelectedRecordsIDsInfo } from './GetSelectedRecordsIDsInfo-9fa41508.js';
import { R as ResourceIDUtils } from './ResourceIDUtils-a114189a.js';
import { ApplicationUtils, DialogType, FormLayout } from '@sankhyalabs/ezui/dist/collection/utils';
import { C as ConfigStorage } from './ConfigStorage-4eee53da.js';
import './PrintUtils-3e4ff0f5.js';
import '@sankhyalabs/ezui/dist/collection/components/ez-grid/utils';
import '@sankhyalabs/core/dist/utils/SortingUtils';

const SERVICE_ACTION_EXECUTE_JAVA = 'ActionButtonsSP.executeJava';
class JavaExecutor {
  execute(action) {
    var _a;
    const execSource = {
      actionID: action.actionID,
      refreshType: (_a = action.actionConfig.javaCall) === null || _a === void 0 ? void 0 : _a.refreshType
    };
    return new Promise((resolve) => {
      resolve({ execSource, callback: this.callExecJava });
    });
  }
  async callExecJava(execSource) {
    const request = {
      requestBody: {
        javaCall: execSource
      }
    };
    await DataFetcher.get().callServiceBroker(SERVICE_ACTION_EXECUTE_JAVA, JSON.stringify(request));
  }
}

const SERVICE_ACTION_EXECUTE_SCRIPT = 'ActionButtonsSP.executeScript';
class JavascriptExecutor {
  execute(action) {
    var _a;
    const execSource = {
      actionID: action.actionID,
      refreshType: (_a = action.actionConfig.runScript) === null || _a === void 0 ? void 0 : _a.refreshType
    };
    return new Promise((resolve) => {
      resolve({ execSource, callback: this.callExecScript });
    });
  }
  async callExecScript(execSource) {
    const request = {
      runScript: execSource
    };
    await DataFetcher.get().callServiceBroker(SERVICE_ACTION_EXECUTE_SCRIPT, request);
  }
}

class LaunchScreenExecutor {
  constructor() {
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
  }
  async execute(action, dataUnit) {
    const resourceID = action.resourceID;
    if (!resourceID)
      return;
    let launchObject = await this.buildLaunchObject(action, dataUnit);
    this._application.openApp(resourceID, launchObject);
    return null;
  }
  buildLaunchObject(action, dataUnit) {
    return new Promise((resolve) => {
      let params = action.actionConfig.params.param;
      if (params && params.length > 0) {
        let launchObject = {};
        let processedParams = [];
        params.forEach(param => {
          const localField = param.localField;
          let value = dataUnit.getFieldValue(localField);
          if (!value) {
            let localFieldLabel = dataUnit.getField(localField).label;
            localFieldLabel = StringUtils.isEmpty(dataUnit.getField(localField).label) ? localField : localFieldLabel;
            throw new ErrorException(this._application.messagesBuilder.getMessage("snkActionsButton.title.error", undefined), this._application.messagesBuilder.getMessage("snkActionsButton.launchScreen.emptyField", { description: action.description, localFieldLabel: localFieldLabel }));
          }
          if (value !== null && typeof value === 'object' && 'value' in value) {
            value = value.value;
          }
          const finalValue = StringUtils.isEmpty(value === null || value === void 0 ? void 0 : value.toString()) ? undefined : value.toString();
          launchObject[param.targetField] = finalValue;
          processedParams.push({
            fieldName: param.targetField,
            value: finalValue
          });
        });
        launchObject.ACTION_PARAMETERS = processedParams;
        launchObject.call_time = Date.now();
        resolve(launchObject);
      }
      resolve(null);
    });
  }
}

const SERVICE_ACTION_EXECUTE_STP = 'ActionButtonsSP.executeSTP';
class ProcedureExecutor {
  execute(action) {
    var _a, _b, _c;
    const procName = (_a = action.actionConfig.dbCall) === null || _a === void 0 ? void 0 : _a.name;
    const rootEntity = (_b = action.actionConfig.dbCall) === null || _b === void 0 ? void 0 : _b.rootEntity;
    const execSource = {
      actionID: action.actionID,
      refreshType: (_c = action.actionConfig.dbCall) === null || _c === void 0 ? void 0 : _c.refreshType,
      procName: procName,
      rootEntity: rootEntity
    };
    return new Promise((resolve) => {
      resolve({ execSource, callback: this.callExecProcedure });
    });
  }
  async callExecProcedure(execSource) {
    const request = {
      requestBody: {
        stpCall: execSource
      }
    };
    await DataFetcher.get().callServiceBroker(SERVICE_ACTION_EXECUTE_STP, JSON.stringify(request));
  }
}

var ActionsType;
(function (ActionsType) {
  ActionsType["LAUNCH_SCREEN"] = "LC";
  ActionsType["JAVASCRIPT"] = "SC";
  ActionsType["JAVA"] = "RJ";
  ActionsType["PROCEDURE"] = "SP";
  ActionsType["EMBEDDED"] = "EB";
})(ActionsType || (ActionsType = {}));

class ExecutorFactory {
  constructor(actionType) {
    this.actionType = actionType;
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
  }
  get executor() {
    switch (this.actionType) {
      case ActionsType.LAUNCH_SCREEN:
        return new LaunchScreenExecutor();
      case ActionsType.JAVASCRIPT:
        return new JavascriptExecutor();
      case ActionsType.JAVA:
        return new JavaExecutor();
      case ActionsType.PROCEDURE:
        return new ProcedureExecutor();
      default:
        throw new ErrorException(this._application.messagesBuilder.getMessage("snkActionsButton.title.error", undefined), this._application.messagesBuilder.getMessage("snkActionsButton.action.nonExistentType", { actionType: this.actionType }));
    }
  }
}

var RefreshType;
(function (RefreshType) {
  RefreshType["NONE"] = "NONE";
  RefreshType["PARENT"] = "PARENT";
  RefreshType["MASTER"] = "MASTER";
  RefreshType["ALL"] = "ALL";
})(RefreshType || (RefreshType = {}));

const MASTER_ROW_PROPERTY = "__MASTER_ROW__";
const ENTITY_NAME_PROPERTY = '__ENTITY_NAME__';
const SERVICE_GET_CONFIGURATIONS = 'SystemUtilsSP.getConf';
class Actions {
  constructor(actionsExecuteInterface, dataUnit, appResourceId) {
    var _a;
    this._lastValuesCache = {};
    this._actionsExecuteInterface = actionsExecuteInterface;
    this._dataUnit = dataUnit;
    this._selectedRows = ((_a = dataUnit === null || dataUnit === void 0 ? void 0 : dataUnit.getSelectionInfo()) === null || _a === void 0 ? void 0 : _a.isAllRecords()) ? [] : dataUnit === null || dataUnit === void 0 ? void 0 : dataUnit.getSelectionInfo().records;
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    this._appResourceId = appResourceId;
  }
  getPrimaryKeys() {
    const ids = getSelectedRecordsIDsInfo(this._dataUnit);
    return ids.map(({ name }) => name);
  }
  apply(action, hasParamsToSave) {
    this._application.closePopUp();
    this._actionsExecuteInterface.execute(action, this._dataUnit)
      .then(({ execSource, callback }) => {
      this.resolvePromptParams(action, execSource, hasParamsToSave)
        .then(() => {
        this.actionExecute(execSource, callback);
      });
    });
  }
  ;
  async execute(action) {
    var _a;
    if (!action.actionConfig) {
      throw new WarningException(this._application.messagesBuilder.getMessage("snkActionsButton.title.warning", undefined), this._application.messagesBuilder.getMessage("snkActionsButton.action.incorrectAction", { description: action.description }));
    }
    if (!!((_a = action.actionConfig.params) === null || _a === void 0 ? void 0 : _a.promptParam)) {
      const paramsSource = action.actionConfig.params.promptParam;
      let hasParamsToSave = false;
      for (let i = 0; i < paramsSource.length; i++) {
        let paramSource = paramsSource[i];
        if (!hasParamsToSave && paramSource.saveLast === 'true') {
          hasParamsToSave = true;
          break;
        }
      }
      if (hasParamsToSave) {
        action.actionConfig.params.promptParam = await this.loadSavedValuesIntoParams(action);
      }
      const form = document.createElement("snk-actions-form");
      window.document.body.appendChild(form);
      form.action = ObjectUtils.copy(action);
      form.applyParameters = (resultAction) => {
        this.apply(resultAction, hasParamsToSave);
      };
      form.openPopup();
    }
    else if (action.type != ActionsType.LAUNCH_SCREEN) {
      this._actionsExecuteInterface.execute(action, this._dataUnit)
        .then(({ execSource, callback }) => {
        this.actionExecute(execSource, callback);
      });
    }
    else {
      this._actionsExecuteInterface.execute(action, this._dataUnit);
    }
  }
  loadSavedValuesIntoParams(action) {
    return this.loadLastValues(action)
      .then((lastParams) => {
      let resultParams = action.actionConfig.params.promptParam;
      if (lastParams) {
        lastParams.param.forEach(lastParam => {
          resultParams = resultParams.map((param) => {
            if (param.name !== lastParam.paramName)
              return param;
            if (param.paramType === 'B') {
              return Object.assign(Object.assign({}, param), { value: lastParam.$ === 'S' });
            }
            return Object.assign(Object.assign({}, param), { value: lastParam.$ });
          });
        });
      }
      return resultParams;
    });
  }
  async actionExecute(execSource, callback) {
    execSource.virtualPage = this.buildVirtualPage();
    await this.prepareAndExecute(execSource, callback);
    this.recordsReloader(execSource.refreshType);
  }
  resolvePromptParams(action, execSource, hasParamsToSave) {
    return new Promise(resolve => {
      const paramsSource = action.actionConfig.params.promptParam;
      let params = [];
      paramsSource.forEach(paramSource => {
        params.push(this.buildPromptParam(paramSource));
      });
      this.putParamsOnExecSource(params, execSource);
      if (hasParamsToSave) {
        this.saveLastValues(action, params);
      }
      resolve();
    });
  }
  buildPromptParam(param) {
    let type = param.paramType;
    let isCheckbox = false;
    let fieldProps;
    let entityPK;
    let value = param.value;
    switch (type) {
      case ParamType.DATE:
        type = 'D';
        break;
      case ParamType.DATETIME:
        type = 'H';
        break;
      case ParamType.DECIMAL:
        type = 'F';
        fieldProps = {
          'sk-precision': Number(param.precision)
        };
        break;
      case ParamType.BOOLEAN:
        type = 'S';
        isCheckbox = true;
        value = param.value ? 'S' : 'N';
        break;
      case ParamType.ENTITY:
        fieldProps = {
          'sk-entity-name': param.entityName,
          'sk-allow-show-hierarchical-mode': param.hierarchyEntity,
          'sk-data-type': 'S'
        };
        if (param.hierarchyEntity && param.entityPK) {
          entityPK = param.entityPK;
        }
        value = param.value ? Number(param.value) : null;
        break;
      case ParamType.OPTIONS:
        type = 'O';
        let options = param.options.split(';').map(function (opc, index) {
          let data;
          let value;
          if (opc.indexOf('=') > -1) {
            let opcArr = opc.split('=');
            data = opcArr[0];
            value = opcArr[1];
          }
          else {
            data = (index + 1);
            value = opc;
          }
          return {
            data: data,
            value: value
          };
        });
        fieldProps = {
          'sk-options': options
        };
        break;
    }
    return {
      description: param.label,
      required: param.required == 'true',
      fieldName: param.name,
      fieldNameOri: param.name,
      entityPK: entityPK,
      paramType: param.paramType,
      type: type,
      isCheckbox: isCheckbox,
      saveLast: param.saveLast,
      fieldProp: fieldProps,
      value: value,
      isGeneratedName: param.isGeneratedName
    };
  }
  putParamsOnExecSource(params, execSource) {
    execSource.params = {
      param: []
    };
    params.forEach(param => {
      if (param.isGeneratedName && param.value) {
        throw new ErrorException(this._application.messagesBuilder.getMessage("snkActionsButton.title.error", undefined), this._application.messagesBuilder.getMessage("snkActionsButton.action.emptyParamName", undefined));
      }
      if (!StringUtils.isEmpty(param.value)) {
        execSource.params.param.push({
          type: this.getParamDataType(param.paramType),
          paramName: param.fieldName,
          $: this.getParamValue(param)
        });
      }
    });
  }
  getParamDataType(type) {
    let dataType;
    switch (type) {
      case "D":
        dataType = "F";
        break;
      case "DT":
      case "DH":
        dataType = "D";
        break;
      case "B":
      case "ENTITY":
      case "SO":
        dataType = "S";
        break;
      default:
        dataType = type;
    }
    return dataType;
  }
  getParamValue(param) {
    let value = param.value;
    if (!value) {
      return value;
    }
    if (param.paramType == 'DT') {
      value = DateUtils.formatDate(value);
    }
    else if (param.paramType == 'DH') {
      value = DateUtils.formatDateTime(value);
    }
    return value;
  }
  async loadLastValues(action) {
    const resourceId = await this.buildResourceId(action.actionID);
    return new Promise((resolve, reject) => {
      if (this._lastValuesCache[resourceId]) {
        resolve(this._lastValuesCache[resourceId]);
      }
      else {
        const config = {
          config: {
            chave: resourceId,
            tipo: 'T'
          }
        };
        DataFetcher.get().callServiceBroker(SERVICE_GET_CONFIGURATIONS, config)
          .then((result) => {
          var _a, _b;
          let lastParams;
          if ((_b = (_a = result.config) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.params) {
            lastParams = result.config.data.params;
            if (!Array.isArray(lastParams.param)) {
              lastParams.param = [lastParams.param];
            }
          }
          this._lastValuesCache[resourceId] = lastParams;
          resolve(lastParams);
        }).catch((error) => {
          reject(error);
        });
      }
    });
  }
  async saveLastValues(action, params) {
    if (this._application) {
      let config = {
        params: {
          param: []
        }
      };
      params.forEach(param => {
        if (param.saveLast == 'true') {
          config.params.param.push({
            paramName: param.fieldName,
            $: param.value
          });
        }
      });
      const resourceId = await this.buildResourceId(action.actionID);
      this._lastValuesCache[resourceId] = config.params;
      this._application.saveConfig(resourceId, config);
    }
  }
  async buildResourceId(actionId) {
    return this._appResourceId + '.actionconfig.' + actionId;
  }
  async prepareAndExecute(execSource, executeAction) {
    this.addRows(execSource);
    await executeAction(execSource);
  }
  addRows(execSource) {
    const primaryKeys = this.getPrimaryKeys();
    const rows = {
      row: []
    };
    const sourceRows = this._selectedRows;
    for (const i in sourceRows) {
      const sourceRow = sourceRows[i];
      const row = {};
      if (sourceRow.hasOwnProperty(MASTER_ROW_PROPERTY)) {
        row.master = 'S';
        row.entityName = sourceRow.__ENTITY_NAME__;
        delete sourceRow[MASTER_ROW_PROPERTY];
        delete sourceRow[ENTITY_NAME_PROPERTY];
      }
      if (!row.field) {
        row.field = [];
      }
      for (const primaryKey of primaryKeys) {
        row.field.push({
          fieldName: primaryKey,
          $: sourceRow[primaryKey]
        });
      }
      rows.row.push(row);
    }
    if (rows.row.length > 0) {
      execSource.rows = rows;
    }
  }
  recordsReloader(refreshType) {
    switch (refreshType) {
      case RefreshType.NONE:
        break;
      case RefreshType.PARENT:
      case RefreshType.MASTER:
      case RefreshType.ALL:
        this._dataUnit.loadData();
        break;
      default:
        this._dataUnit.reloadCurrentRecord();
    }
  }
  ;
  buildVirtualPage() {
    var _a, _b, _c, _d;
    if ((_b = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.getSelectionInfo()) === null || _b === void 0 ? void 0 : _b.isAllRecords()) {
      const virtualPage = {
        filters: { filters: (_c = this._dataUnit) === null || _c === void 0 ? void 0 : _c.getAppliedFilters() },
        orders: { orders: (_d = this._dataUnit) === null || _d === void 0 ? void 0 : _d.getSort() },
      };
      return virtualPage;
    }
  }
}

const CONFIRMACAO = "__CONFIRMACAO__";
const ESCOLHA_SIM_NAO = "__ESCOLHA_SIMNAO__";
class ClientEventConfirm {
  async clientConfirm(clientEvent, recaller) {
    return new Promise((resolve) => {
      var _a, _b;
      const application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
      let actionType = "";
      if (clientEvent.content.event.hasOwnProperty('stpCall')) {
        recaller.requestBody = clientEvent.content.event.stpCall;
        actionType = ActionsType.PROCEDURE;
      }
      else if (clientEvent.content.event.hasOwnProperty('runScript')) {
        recaller.requestBody = clientEvent.content.event.runScript;
        actionType = ActionsType.JAVASCRIPT;
      }
      else if (clientEvent.content.event.hasOwnProperty('javaCall')) {
        recaller.requestBody = clientEvent.content.event.javaCall;
        actionType = ActionsType.JAVA;
      }
      let param = {
        type: 'S',
        sequence: clientEvent.content.event.sequence
      };
      if (!recaller.requestBody.params) {
        recaller.requestBody.params = {
          param: []
        };
      }
      else {
        if (!Array.isArray(recaller.requestBody.params.param)) {
          recaller.requestBody.params.param = [recaller.requestBody.params.param];
        }
      }
      recaller.requestBody.params.param.push(param);
      const title = clientEvent.content.event.title.$;
      const message = clientEvent.content.event.message.$;
      let requestBody;
      switch (actionType) {
        case ActionsType.JAVASCRIPT:
          requestBody = { runScript: recaller.requestBody };
          break;
        case ActionsType.PROCEDURE:
          requestBody = {
            requestBody: {
              stpCall: recaller.requestBody
            }
          };
          break;
        case ActionsType.JAVA:
          requestBody = {
            requestBody: {
              javaCall: recaller.requestBody
            }
          };
          break;
      }
      if (clientEvent.content.event.showNoOption == 'S') {
        param.paramName = ESCOLHA_SIM_NAO;
        const form = document.createElement("snk-client-confirm");
        window.document.body.appendChild(form);
        form.titleMessage = title;
        form.message = message;
        form.accept = async () => {
          param.$ = 'S';
          await recaller.reCall(requestBody);
          resolve();
        };
        form.cancel = async () => {
          param.$ = 'N';
          await recaller.reCall(requestBody);
          resolve();
        };
        form.openPopup();
      }
      else {
        application.confirm(title, message, null, 'warn', {
          labelCancel: (_a = application === null || application === void 0 ? void 0 : application.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage("snkActionsButton.clientEvent.labelCancel"),
          labelConfirm: (_b = application === null || application === void 0 ? void 0 : application.messagesBuilder) === null || _b === void 0 ? void 0 : _b.getMessage("snkActionsButton.clientEvent.labelConfirm")
        }).then(async (confirmResult) => {
          if (confirmResult) {
            param.paramName = CONFIRMACAO;
            param.$ = 'S';
            await recaller.reCall(requestBody);
            resolve();
          }
        });
      }
    });
  }
}

const snkActionsButtonCss = ".sc-snk-actions-button-h{display:flex;width:fit-content;height:fit-content}.snk-actions-button.sc-snk-actions-button{display:flex;width:fit-content;height:fit-content}.snk-actions-button__dropdown--show.sc-snk-actions-button{display:flex;flex-direction:column;position:fixed}.snk-actions-button__dropdown.sc-snk-actions-button>ez-dropdown.sc-snk-actions-button{position:relative}.snk-actions-button__dropdown.sc-snk-actions-button{display:none}";

const SnkActionsButton = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.CLIENT_EVENT_CONFIRM_NAME = "br.com.sankhya.actionbutton.clientconfirm";
    this._actions = [];
    this.handleClick = (evt) => {
      const selectedAction = this._actions.find((action) => action.actionID == evt.detail.id);
      const executor = new ExecutorFactory(selectedAction.type).executor;
      const action = new Actions(executor, this._dataUnit, this._resourceID);
      action.execute(Object.assign({}, selectedAction));
      this._showDropdown = false;
    };
    this._items = [];
    this._showDropdown = false;
  }
  async getActions() {
    const actions = await ServiceUtils.useCacheWithService(`SnkActionsButton_${this._entityName}-${this._resourceID}`, async () => {
      var _a;
      const param = {
        param: {
          entityName: this._entityName,
          resourceID: this._resourceID,
        },
      };
      const result = await DataFetcher.get().callServiceBroker('ActionButtonsSP.getActions', param);
      return ((_a = result.actions) === null || _a === void 0 ? void 0 : _a.action) || [];
    }, StorageType.IN_MEMORY_CACHE);
    this._actions = SnkActionsButton.parameters.isOrderActions
      ? ArrayUtils.sortAlphabetically(actions, 'description')
      : actions;
  }
  controlDropdown() {
    this._showDropdown = !this._showDropdown;
  }
  canShowDropdown() {
    var _a;
    return this._showDropdown && ((_a = this._items) === null || _a === void 0 ? void 0 : _a.length) > 0;
  }
  positionDropdown() {
    var _a;
    const bounding = (_a = this._ezButton) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
    if (!bounding || !this._dropdownParent)
      return;
    this._dropdownParent.style.top = (bounding.y + bounding.height + 5) + "px";
    this._dropdownParent.style.left = bounding.x + "px";
  }
  closeDropdown(evt) {
    const target = evt === null || evt === void 0 ? void 0 : evt.target;
    if (!target)
      return;
    if (!target.closest(".snk-actions-button")) {
      this._showDropdown = false;
    }
  }
  setEvents() {
    document.removeEventListener("click", this.closeDropdown.bind(this));
    document.addEventListener("click", this.closeDropdown.bind(this));
    document.removeEventListener("scroll", this.positionDropdown.bind(this));
    document.addEventListener("scroll", this.positionDropdown.bind(this));
  }
  async componentWillLoad() {
    var _a, _b;
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    await this.loadParameters();
    const snkDataUnit = this._element.parentElement;
    this._dataUnit = snkDataUnit === null || snkDataUnit === void 0 ? void 0 : snkDataUnit.dataUnit;
    this._resourceID = snkDataUnit === null || snkDataUnit === void 0 ? void 0 : snkDataUnit.resourceID;
    this._entityName = (_b = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.split('/')[2];
    if (this._resourceID == undefined) {
      this._resourceID = await ResourceIDUtils.getResourceID();
    }
    this.setEvents();
    await this.getActions();
    this.loadItems();
  }
  async componentDidLoad() {
    if (!this._element)
      return;
    ElementIDUtils.addIDInfo(this._element);
    this.positionDropdown();
    if (!(await this._application.hasClientEvent(this.CLIENT_EVENT_CONFIRM_NAME))) {
      const clientEventConfirm = new ClientEventConfirm();
      this._application.addClientEvent(this.CLIENT_EVENT_CONFIRM_NAME, clientEventConfirm.clientConfirm);
    }
  }
  componentDidUpdate() {
    this.positionDropdown();
  }
  loadItems() {
    if (!this._actions || this._actions.length == 0)
      return;
    this._actions.forEach(action => {
      this._items.push({ id: action.actionID, label: action.description });
    });
  }
  getElementID(sufix) {
    return {
      [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(sufix)
    };
  }
  async loadParameters() {
    if (SnkActionsButton.parameters.isOrderActions != null)
      return;
    SnkActionsButton.parameters.isOrderActions = await this._application.getBooleanParam('global.ordenar.acoes.personalizadas');
  }
  render() {
    return (h(Host, null, (this._actions && this._actions.length > 0) &&
      (h("div", { class: `ez-padding-left--medium snk-actions-button
                            ${this.canShowDropdown() ? " ez-elevation--16" : ""}
                        ` }, h("ez-button", Object.assign({ ref: (ref) => this._ezButton = ref, iconName: "acao", size: "small", mode: "icon", title: this._application.messagesBuilder.getMessage("snkActionsButton.title.actions", undefined), onClick: () => this.controlDropdown() }, this.getElementID("button"))), h("div", Object.assign({ ref: (ref) => this._dropdownParent = ref, class: `${this.canShowDropdown() ?
          "snk-actions-button__dropdown--show" :
          "snk-actions-button__dropdown"}
                            ` }, this.getElementID("dropdown")), (this.canShowDropdown()) &&
        (h("ez-dropdown", Object.assign({ items: this._items, onEzClick: (evt) => this.handleClick(evt) }, this.getElementID("dropdown"))))))), (this.canShowDropdown()) &&
      (h("div", Object.assign({ class: "ez-scrim ez-scrim--light" }, this.getElementID("ezScrim"))))));
  }
  get _element() { return getElement(this); }
};
SnkActionsButton.parameters = {
  isOrderActions: null
};
SnkActionsButton.style = snkActionsButtonCss;

const snkGridConfigCss = ".sc-snk-grid-config-h{--snk-grid-config__footer--padding-top:var(--space--medium, 12px);--snk-grid-config__main--padding-right:var(--space--medium, 12px);--snk-grid-config__tabselector-container--padding:var(--space--medium, 12px);--snk-grid-config__button-close--padding-left:var(--space--medium, 12px);--snk-grid-config__title--color:var(--title--primary, #2B3A54);--snk-grid-config__title--font-family:var(--font-pattern, \"Roboto\");--snk-grid-config__title--font-size:var(--title--large, 20px);--snk-grid-config__title--font-weight:var(--text-weight--extra-large, 700);--snk-grid-config__subtitle--font-family:var(--font-pattern, \"Roboto\");--snk-grid-config__subtitle--font-size:var(--text--medium, 14px);--snk-grid-config__group--font-family:var(--font-pattern, \"Roboto\");--snk-grid-config__group--font-size:var(--text--medium, 14px);--snk-grid-config__group--font-weight:var(--text-weight--large, 600);--snk-grid-config__group--padding-bottom:var(--space-small, 6px);--snk-grid-config__scrollbar--color-default:var(--scrollbar--default, #626e82);--snk-grid-config__scrollbar--color-background:var(--scrollbar--background, #E5EAF0);--snk-grid-config__scrollbar--color-hover:var(--scrollbar--hover, #2B3A54);--snk-grid-config__scrollbar--color-clicked:var(--scrollbar--clicked, #a2abb9);--snk-grid-config__scrollbar--border-radius:var(--border--radius-small, 6px);--snk-grid-config__scrollbar--width:var(--space--small, 6px);display:flex;flex-direction:column;max-height:100%;width:100%}.grid-config__body.sc-snk-grid-config{overflow:auto}.padding-right--medium.sc-snk-grid-config{padding-right:var(--space--medium)}ez-list.sc-snk-grid-config{height:100%}.height-calc.sc-snk-grid-config{max-height:calc(100% - 24px)}.grid-config__footer.sc-snk-grid-config{display:flex;justify-content:flex-end;width:100%;padding-top:var(--snk-grid-config__footer--padding-top)}.hidden.sc-snk-grid-config{display:none}.tabselector-container.sc-snk-grid-config{padding:var(--snk-grid-config__tabselector-container--padding) 0}.button-close.sc-snk-grid-config{padding-left:var(--snk-grid-config__button-close--padding-left)}.title-container.sc-snk-grid-config{display:flex;justify-content:space-between;align-items:center;width:100%}.title.sc-snk-grid-config{display:flex;margin:0;line-height:normal;letter-spacing:0em;text-align:left;color:var(--snk-grid-config__title--color);font-size:var(--snk-grid-config__title--font-size);font-family:var(--snk-grid-config__title--font-family);font-weight:var(--snk-grid-config__title--font-weight)}.subtitle.sc-snk-grid-config{color:var(--text--primary);font-size:var(--snk-grid-config__subtitle--font-size);font-family:var(--snk-grid-config__subtitle--font-family)}.grid-config__main.sc-snk-grid-config{overflow-y:auto;scrollbar-width:thin;width:100%;padding-bottom:20px;scrollbar-color:var(--snk-grid-config__scrollbar--color-clicked) var(--snk-grid-config__scrollbar--color-background)}.group-name.sc-snk-grid-config{font-family:var(--snk-grid-config__group--font-family);font-size:var(--snk-grid-config__group--font-size);font-weight:var(--snk-grid-config__group--font-weight);padding-bottom:var(--snk-grid-config__group--padding-bottom)}";

const SnkGridConfig = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.configChange = createEvent(this, "configChange", 7);
    this.configCancel = createEvent(this, "configCancel", 7);
    this._orderListItems = [];
    this._orderPriorityList = [];
    this._visibleList = [];
    this._hiddenList = [];
    this._columListItems = [];
    this._dataChanged = false;
    this._componenteInternalKey = Date.now();
    this.selectedIndex = 0;
    this.columns = undefined;
    this.config = undefined;
    this.configName = undefined;
    this.resourceID = undefined;
    this._collapsibleBoxListOrder = true;
    this._collapsibleBoxListSelect = false;
  }
  /* Creation Methods */
  /**
   * Conforme mecanismo de mensagens, é possível customizar as mensagens dos blocos de construção
   * através de um pequeno modulo na estrutura da aplicação:
   * - Criar um arquivo no seguinte caminho: /messages/appmessages.msg.js.
   * Para conhecer os detalhes do módulo, vide o arquivo neste projeto "/src/lib/message/resources/snk-grid.msg.ts"
   */
  getMessage(key, params) {
    const application = ApplicationContext.getContextValue('__SNK__APPLICATION__');
    return application.messagesBuilder.getMessage(key, params);
  }
  getSortableColumns() {
    let newList = [];
    this.columns.filter(col => { var _a; return StringUtils.getBooleanValue((_a = col === null || col === void 0 ? void 0 : col.props) === null || _a === void 0 ? void 0 : _a.get('sortable'), true); }).forEach((column) => {
      var _a, _b;
      let configItem = (_a = this.config) === null || _a === void 0 ? void 0 : _a.columns.find((item) => item.name === column.name);
      let item = { label: column.label, sort: (_b = column === null || column === void 0 ? void 0 : column.sort) !== null && _b !== void 0 ? _b : ORDER_VALUES.asc.value, id: column.name };
      if (configItem) {
        item['orderIndex'] = configItem.orderIndex;
        item['ascending'] = configItem.ascending;
      }
      if (!column.hidden) {
        newList.push(item);
      }
    });
    return newList;
  }
  createOrderList() {
    var _a;
    let newSortableList = this.getSortableColumns();
    if (((_a = this._orderPriorityList) === null || _a === void 0 ? void 0 : _a.length) > 0) {
      const orderedList = [];
      this._orderPriorityList.forEach((priorityItem) => {
        const item = newSortableList.find(col => col.id === priorityItem.id);
        if (item) {
          orderedList.push(item);
        }
      });
      newSortableList.forEach(item => {
        if (!orderedList.find(o => o.id === item.id)) {
          orderedList.push(item);
        }
      });
      this._orderListItems = orderedList;
    }
    else {
      newSortableList.sort((a, b) => {
        //OS dois tem order index 0 e pelo menos um deles tem orientação de ordenação.
        if (a.orderIndex == 0 && b.orderIndex == 0 && (a.ascending != undefined || b.ascending != undefined)) {
          if (a.ascending != undefined)
            return -1;
          if (b.ascending != undefined)
            return 1;
          return 0;
          //Pelo menos um deles tem order index diferente de 0 e os dois tem orientação de ordenação.
        }
        else if (a.ascending != undefined && b.ascending != undefined) {
          return (a.orderIndex - b.orderIndex);
          //Pelo menos um deles tem order index diferente de 0 e pelo menos um deles tem orientação de ordenação.
        }
        else if (a.ascending != undefined || b.ascending != undefined) {
          if (a.ascending != undefined)
            return -1;
          if (b.ascending != undefined)
            return 1;
          return 0;
        }
        return (a.orderIndex - b.orderIndex);
      });
      this._orderListItems = newSortableList;
    }
  }
  createColumnList() {
    const visibleGroup = this.buildVisibleGroup();
    const hiddenGroup = this.buildHiddenGroup();
    this.columns.forEach(column => {
      const item = this.buildListItemFromColumn(column);
      if (column.hidden) {
        hiddenGroup.items.push(item);
      }
      else {
        visibleGroup.items.push(item);
      }
    });
    this._columListItems = [visibleGroup, hiddenGroup];
    this._visibleList = visibleGroup.items;
    this._hiddenList = hiddenGroup.items;
    this.createOrderList();
  }
  buildVisibleGroup() {
    return {
      group: this.getMessage('snkGridConfig.group.visible'),
      items: [],
    };
  }
  buildHiddenGroup() {
    return {
      group: this.getMessage('snkGridConfig.group.hidden'),
      items: [],
      sort: ORDER_VALUES.asc.value,
    };
  }
  createOrderListSlotDataElementId(item) {
    var _a;
    return `${this._element.getAttribute(ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME)}_configItem_${StringUtils.toCamelCase((_a = item.id) !== null && _a !== void 0 ? _a : item.label)}`;
  }
  buildOrderListSlot(item) {
    const dataElementId = this.createOrderListSlotDataElementId(item);
    let selectedOption = ORDER_VALUES.none.value;
    if ((item === null || item === void 0 ? void 0 : item.ascending) != undefined) {
      selectedOption = item.ascending == true ? ORDER_VALUES.asc.value : ORDER_VALUES.desc.value;
    }
    return (h("snk-select-box", { selectedOption: selectedOption, key: 'snk-select-box-' + this._componenteInternalKey + '-' + item, "data-element-id": dataElementId, onEzChange: (evt) => {
        evt.stopPropagation();
        this.updateOrder(evt.detail, item.id);
      }, preventAutoFocus: true }));
  }
  updateOrder(sortOrder, updatedItemId) {
    var _a;
    this._dataChanged = true;
    let newList = [...this.columns];
    let newItem = newList.find((item) => item.name === updatedItemId);
    if (newItem) {
      newItem.sort = sortOrder.value === ORDER_VALUES.none.value ? undefined : sortOrder.value;
    }
    let orderArray;
    if (((_a = this._orderPriorityList) === null || _a === void 0 ? void 0 : _a.length) > 0) {
      const priorityItem = this._orderPriorityList.find((item) => item.id === newItem.name);
      if (priorityItem) {
        priorityItem.sort = sortOrder.value === ORDER_VALUES.none.value ? undefined : sortOrder.value;
      }
      this._orderPriorityList.filter((item) => item.sort != undefined).forEach((item, index) => {
        if (item.id === newItem.name) {
          newItem.sortIndex = index;
        }
      });
    }
    else {
      orderArray = newList.filter((item) => item.sort && item.hidden !== true)
        .map((item, index) => {
        return { name: item.name, orderIndex: index };
      });
      orderArray.forEach((element) => {
        newList.find((item) => item.name === element.name).sortIndex = element.orderIndex;
      });
    }
    this.columns = newList;
  }
  finish() {
    if (!this._dataChanged) {
      this.closeConfig();
      return;
    }
    this.updateColumns();
    this._dataChanged = false;
    this.closeConfig();
    this.save();
    this._orderPriorityList = [];
  }
  updateColumns() {
    this.columns = this._columListItems.flatMap((group) => group.items.map((item) => this.buildColumnFromListItem(item, group)));
  }
  buildColumnFromListItem(item, group) {
    const baseColumn = this.columns.find((column) => column.name === item.id);
    if (!baseColumn) {
      throw new Error(`Column with name "${item.id}" not found.`);
    }
    return Object.assign(Object.assign({}, baseColumn), { hidden: group.group === this.getMessage('snkGridConfig.group.hidden') });
  }
  saveGridConfigOnStorage(_newConfig) {
    ConfigStorage.saveGridConfig(_newConfig, this.configName, this.resourceID)
      .then((savedConfig) => {
      this.configChange.emit(savedConfig);
      ApplicationUtils.info(this.getMessage('snkGridConfig.info.successfullyConfigSaved'), { iconName: 'check' });
    });
  }
  reOrderPriorityColumns(columns, orderPriorityList) {
    let orderArray = [];
    orderArray = columns.filter((item) => item.sort && item.hidden !== true)
      .map((item) => {
      return { name: item.name, orderIndex: 0 };
    });
    let indexCount = 0;
    let newOrderArray = [];
    orderPriorityList.forEach((orderPriorityItem) => {
      let item = orderArray.find((column) => column.name === orderPriorityItem.id);
      if (item) {
        item.orderIndex = indexCount;
        newOrderArray.push(item);
        indexCount++;
      }
    });
    if (newOrderArray.length > 0) {
      orderArray = newOrderArray;
    }
    return orderArray;
  }
  save() {
    var _a;
    let _newConfig;
    if (this.config) {
      _newConfig = this.config;
    }
    else {
      _newConfig = this.createConfigFromState(this.columns);
    }
    let _newColumnConfigList = [];
    let orderArray;
    if (((_a = this._orderPriorityList) === null || _a === void 0 ? void 0 : _a.length) > 0) {
      orderArray = this.reOrderPriorityColumns(this.columns, this._orderPriorityList);
    }
    this.columns.forEach((column) => {
      let _newColumnConfig = _newConfig.columns.find((_newColumnConfig) => column.name === _newColumnConfig.name);
      if (column.hidden === true && _newColumnConfig)
        return;
      if (!_newColumnConfig && column.hidden === false) {
        _newColumnConfig = { name: column.name, orderIndex: 0 };
      }
      if (_newColumnConfig) {
        if (column.sort) {
          _newColumnConfig.ascending = column.sort.toUpperCase() === ORDER_VALUES.asc.value ? true : false;
          if (orderArray) {
            adjustPriorityOrder(column, _newColumnConfig);
          }
          else {
            _newColumnConfig.orderIndex = column.sortIndex;
          }
        }
        else {
          delete _newColumnConfig.ascending;
          _newColumnConfig.orderIndex = 0;
        }
        _newColumnConfig.configVersion = SnkGridConfig.CURRENT_CONFIG_VERSION;
        _newColumnConfigList.push(_newColumnConfig);
      }
    });
    _newConfig.columns = _newColumnConfigList;
    this.saveGridConfigOnStorage(_newConfig);
    function adjustPriorityOrder(column, _newColumnConfig) {
      if (orderArray) {
        let orderItem = orderArray.find((item) => item.name === column.name);
        if (orderItem) {
          _newColumnConfig.orderIndex = orderItem.orderIndex;
        }
      }
    }
  }
  createConfigFromState(state) {
    let newConfig = { columns: [] };
    state.forEach((columnState) => {
      if (!columnState.hidden) {
        let newConfigColumn = { name: columnState.name };
        if (columnState.width) {
          newConfigColumn['width'] = columnState.width;
        }
        if (columnState.sort) {
          newConfigColumn['ascending'] = (columnState.sort.toUpperCase() === ORDER_VALUES.asc.value);
          newConfigColumn['orderIndex'] = columnState.sortIndex;
        }
        else {
          newConfigColumn['orderIndex'] = 0;
        }
        if (newConfigColumn) {
          newConfig.columns.push(newConfigColumn);
        }
      }
    });
    return newConfig;
  }
  closeConfig() {
    if (this._dataChanged) {
      let options = {
        canClose: false,
        labelCancel: this.getMessage('snkGridConfig.confirm.cancel'),
        labelConfirm: this.getMessage('snkGridConfig.confirm.save'),
        btnConfirmDanger: false,
      };
      ApplicationUtils.confirm(this.getMessage('snkGridConfig.confirm.alert'), this.getMessage('snkGridConfig.confirm.msgCancel'), null, DialogType.WARN, options)
        .then((response) => {
        if (!response) {
          this._dataChanged = false;
          this._orderPriorityList = [];
          this.configCancel.emit();
          this._componenteInternalKey = Date.now();
        }
        else {
          this.finish();
        }
      });
    }
    else {
      this.configCancel.emit();
    }
  }
  handleColumnListChange(evt) {
    var _a;
    if (evt.detail) {
      let visibleItems = (_a = evt.detail.find((group) => group.group === this.getMessage('snkGridConfig.group.visible'))) === null || _a === void 0 ? void 0 : _a.items;
      if (visibleItems) {
        this._dataChanged = true;
        this._orderListItems = visibleItems;
      }
    }
  }
  handleOrderListChange(evt) {
    if (evt.detail) {
      let orderPriorityList = evt.detail;
      if (orderPriorityList) {
        this._dataChanged = true;
        this._orderPriorityList = orderPriorityList;
      }
    }
  }
  componentWillRender() {
    var _a;
    if (((_a = this.columns) === null || _a === void 0 ? void 0 : _a.length) > 0) {
      this.createColumnList();
    }
  }
  componentDidLoad() {
    ElementIDUtils.addIDInfo(this._element);
  }
  handleRightListChange(rightList) {
    const visibleGroup = this._columListItems.find(group => group.group === this.getMessage('snkGridConfig.group.visible'));
    if (visibleGroup && visibleGroup.items != rightList) {
      visibleGroup.items = rightList;
      this._dataChanged = true;
    }
  }
  getListSlots() {
    return {
      RIGHT_LIST: {
        itemRightSlotBuilder: (item) => this.buildOrderListSlot(item),
      },
    };
  }
  renderResetConfigBtn() {
    if (!this.resourceID)
      return;
    return h("ez-button", { class: "padding-right--medium", label: this.getMessage('snkGridConfig.reset'), onClick: () => this.setDefaultConfig() });
  }
  async setDefaultConfig() {
    var _a;
    if (!this.resourceID)
      return;
    this._dataChanged = true;
    this._orderPriorityList = [];
    const config = await ConfigStorage.getDefaultGridConfig(this.resourceID);
    const defaultVisibleCols = (_a = config === null || config === void 0 ? void 0 : config.columns.map(col => col.name)) !== null && _a !== void 0 ? _a : [];
    const visibleGroup = this.buildVisibleGroup();
    const hiddenGroup = this.buildHiddenGroup();
    const visibleItemsMap = new Map();
    this.columns.forEach(column => {
      const item = this.buildListItemFromColumn(column);
      if (defaultVisibleCols.includes(column.name)) {
        visibleItemsMap.set(column.name, item);
      }
      else {
        hiddenGroup.items.push(item);
      }
    });
    visibleGroup.items = defaultVisibleCols
      .map(name => visibleItemsMap.get(name))
      .filter(item => item);
    this._columListItems = [visibleGroup, hiddenGroup];
    this._visibleList = visibleGroup.items;
    this._hiddenList = hiddenGroup.items;
    this.updateColumns();
    this.createOrderList();
  }
  buildListItemFromColumn(column) {
    var _a;
    return {
      label: column.label,
      selected: false,
      sort: (_a = column === null || column === void 0 ? void 0 : column.sort) !== null && _a !== void 0 ? _a : ORDER_VALUES.asc.value,
      id: column.name,
    };
  }
  render() {
    return (h(Host, null, h("div", { class: "grid-config__header" }, h("div", { class: "title-container" }, h("div", { class: "ez-margin-bottom--medium" }, h("label", { class: "title" }, this.getMessage('snkGridConfig.gridConfiguration')), h("label", { class: "subtitle" }, this.getMessage('snkGridConfig.columnVisibilityOrder'))), h("div", { class: "button-close" }, h("ez-button", { mode: "icon", iconName: "close", size: "medium", class: "ez-button--tertiary", onClick: () => this.closeConfig() })))), h("div", { class: 'grid-config__body' }, h("ez-collapsible-box", { id: 'group-select-columns', label: this.getMessage('snkGridConfig.columnsSelection'), "header-size": "medium", key: 'key_group-select-columns', value: this._collapsibleBoxListSelect, onEzChange: ({ detail }) => this._collapsibleBoxListOrder = !detail }, h("div", { class: "grid-config__main" }, h("ez-double-list", { leftList: this._hiddenList, leftTitle: this.getMessage('snkGridConfig.availableColumns'), rightList: this._visibleList, rightTitle: this.getMessage('snkGridConfig.selectedColumns'), onEzRightListChanged: ({ detail }) => this.handleRightListChange(detail), emptyMessage: {
        LEFT_LIST: this.getMessage('snkGridConfig.emptyMensage.left'),
        RIGHT_LIST: this.getMessage('snkGridConfig.emptyMensage.right'),
      }, entityLabel: 'coluna', entityLabelPlural: 'colunas' }))), h("ez-collapsible-box", { id: 'ID_group-order-columns', label: this.getMessage('snkGridConfig.dataOrdering'), "header-size": "medium", key: 'KEY_group-order-columns', value: this._collapsibleBoxListOrder, onEzChange: ({ detail }) => this._collapsibleBoxListSelect = !detail }, h("div", { class: "grid-config__main" }, h("ez-double-list", { rightList: this._orderListItems, rightTitle: this.getMessage('snkGridConfig.selectedColumns'), useOnlyRightList: true, slotsListBuilder: this.getListSlots(), onEzRightListChanged: (evt) => this.handleOrderListChange(evt), emptyMessage: {
        RIGHT_LIST: this.getMessage('snkGridConfig.emptyMensage.right'),
      }, entityLabel: 'coluna', entityLabelPlural: 'colunas' })))), h("div", { class: "grid-config__footer" }, this.renderResetConfigBtn(), h("ez-button", { class: "padding-right--medium", label: this.getMessage('snkGridConfig.cancel'), onClick: () => this.closeConfig() }), h("ez-button", { label: this.getMessage('snkGridConfig.complete'), class: "ez-button--primary", onClick: () => this.finish() }))));
  }
  static get assetsDirs() { return ["../assets"]; }
  get _element() { return getElement(this); }
};
SnkGridConfig.CURRENT_CONFIG_VERSION = 1;
SnkGridConfig.style = snkGridConfigCss;

const snkLayoutFormConfigCss = ".sc-snk-layout-form-config-h{display:block}";

const FORM_COL_CONFIG_PREFIX = 'formColCfg.';
const SnkLayoutFormConfig = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this._formConfigFetcher = new FormConfigFetcher();
    this.messagesBuilder = undefined;
    this.layoutType = FormLayout.SIDE_BY_SIDE;
  }
  /**
   * Salva o tipo de layout escolhido. Sem retorno.
   */
  async save() {
    this._LayoutFormConfigSingleton.setConfig(this.layoutType);
    this._formConfigFetcher.saveLayoutFormConfig(FORM_COL_CONFIG_PREFIX + this._resourceID, { config: this.layoutType, newConfig: true });
  }
  async componentWillLoad() {
    const _application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    this._LayoutFormConfigSingleton = await (_application === null || _application === void 0 ? void 0 : _application.getLayoutFormConfig());
    this._resourceID = await (_application === null || _application === void 0 ? void 0 : _application.getResourceID());
    this.setLayoutInit();
  }
  setLayoutInit() {
    if (!this._LayoutFormConfigSingleton)
      return;
    const { config } = this._LayoutFormConfigSingleton;
    if (config == null) {
      this.layoutType = FormLayout.SIDE_BY_SIDE;
      return;
    }
    const configAsNumber = Number(config);
    this.layoutType = Object.values(FormLayout).includes(configAsNumber)
      ? configAsNumber
      : FormLayout.SIDE_BY_SIDE;
  }
  toggleLayout(key) {
    this.layoutType = key;
  }
  getMessage(key, params) {
    var _a;
    return (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage(key, params);
  }
  render() {
    return (h("div", { class: "ez-flex ez-flex--column" }, h("div", { class: "ez-margin-bottom--small" }, h("ez-check", { label: this.getMessage('snkLayoutFormConfig.cascadeLayout.label'), class: "ez-margin-bottom--small", onEzChange: () => this.toggleLayout(FormLayout.CASCADE), value: this.layoutType === FormLayout.CASCADE }), h("snk-view-representation", { mode: FormLayout.CASCADE }), h("label", { class: "ez-label ez-margin--small ez-flex ez-text--medium" }, this.getMessage('snkLayoutFormConfig.cascadeLayout.description'))), h("div", null, h("ez-check", { label: this.getMessage('snkLayoutFormConfig.sideBySideLayout.label'), class: "ez-margin-bottom--small", onEzChange: () => this.toggleLayout(FormLayout.SIDE_BY_SIDE), value: this.layoutType === FormLayout.SIDE_BY_SIDE }), h("snk-view-representation", { mode: FormLayout.SIDE_BY_SIDE }), h("label", { class: "ez-label ez-margin--small ez-flex ez-text--medium" }, this.getMessage('snkLayoutFormConfig.sideBySideLayout.description')))));
  }
};
SnkLayoutFormConfig.style = snkLayoutFormConfigCss;

const snkSelectBoxCss = "ez-combo-box{width:100px;--ez-text-input__margin-bottom:0px}.grid-config-combo{--ez-text-input--height:28px;--ez-text-input__input--background-color:#fff;--ez-text-input__input--border-color:#dce0e8}";

const SelectBox = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezChange = createEvent(this, "ezChange", 7);
    this.selectedOption = ORDER_VALUES.none;
    this.preventAutoFocus = false;
  }
  render() {
    return (h("ez-combo-box", { class: "grid-config-combo ez-input--inverted", label: "", suppressSearch: true, value: this.selectedOption, enabled: true, canShowError: false, suppressEmptyOption: true, preventAutoFocus: this.preventAutoFocus }, Object.keys(ORDER_VALUES).map((key) => {
      return h("option", { value: ORDER_VALUES[key].value }, ORDER_VALUES[key].label);
    })));
  }
  static get assetsDirs() { return ["../assets"]; }
};
SelectBox.style = snkSelectBoxCss;

const snkSimpleFormConfigCss = ":host{display:block}.config-container{display:flex;flex-direction:column;align-items:center;justify-content:space-between}.config-lists{width:100%;margin-bottom:12px}.config-actions{display:flex;flex-direction:row;justify-content:flex-end;width:100%;gap:12px}";

const SnkSimpleFormConfig = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.snkConfigSaved = createEvent(this, "snkConfigSaved", 7);
    this._formConfigFetcher = new FormConfigFetcher();
    this.fieldsToSave = [];
    this.dataUnit = undefined;
    this.configName = undefined;
    this.messagesBuilder = undefined;
    this.avaliableFields = [];
    this.selectedFields = [];
  }
  /**
   * Responsável por abrir o configurador.
   */
  async show() {
    var _a;
    await ((_a = this.ezDoubleListRef) === null || _a === void 0 ? void 0 : _a.resetSelectedLists());
    await this.initializeFormConfig();
    this.ezPopupRef.opened = true;
  }
  ;
  async initializeFormConfig() {
    if (!this.configName)
      return;
    const allFields = this.getAllVisibleFieldsFromDataUnit();
    const displayedFieldNameList = await this.getConfig();
    //Quando não retorna dados, é por quê não existe configuração do usuário salva.
    if (displayedFieldNameList.length === 0) {
      this.avaliableFields = [];
      this.selectedFields = [...allFields];
      this.fieldsToSave = [...this.selectedFields];
      return;
    }
    const selectedFieldsAux = this.sortDisplayedFields(displayedFieldNameList, allFields);
    const avaliableFieldsAux = allFields.filter(field => !displayedFieldNameList.includes(field.id));
    this.avaliableFields = [...avaliableFieldsAux];
    this.selectedFields = [...selectedFieldsAux];
    this.fieldsToSave = [...this.selectedFields];
  }
  async getConfig() {
    const fieldList = await this._formConfigFetcher.fetchSimpleFormConfig(this.configName);
    return [...this.removeDuplicates(fieldList)];
  }
  getMessage(key, params) {
    var _a;
    return (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage(key, params);
  }
  removeDuplicates(strings) {
    return strings.filter((item, index) => strings.indexOf(item) === index);
  }
  sortDisplayedFields(displayedFieldNameList, allFields) {
    const selectedFieldsAux = [];
    //É preciso garantir a ordem na qual os campos vieram na resposta do fetchSimpleFormConfig.
    displayedFieldNameList.forEach(fieldName => {
      const field = allFields.find(field => field.id === fieldName);
      if (!field)
        return;
      selectedFieldsAux.push(field);
    });
    return selectedFieldsAux;
  }
  getAllVisibleFieldsFromDataUnit() {
    var _a, _b, _c;
    const visibleFields = ((_c = (_b = (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.fields) !== null && _c !== void 0 ? _c : []).filter(field => field.visible);
    return visibleFields.map(field => {
      return { id: field.name, label: field.label };
    });
  }
  close() {
    this.ezPopupRef.opened = false;
  }
  async handleResetConfigs() {
    await this._formConfigFetcher.restoreFormConfig(this.configName);
    await this.initializeFormConfig();
    await this.handleSave();
  }
  handleCancel() {
    this.close();
  }
  async handleSave() {
    const saveList = this.fieldsToSave.map(field => field.id);
    await this._formConfigFetcher.saveSimpleFormConfig(this.configName, saveList);
    this.close();
    this.snkConfigSaved.emit();
  }
  render() {
    return (h("ez-popup", { ref: (ref) => this.ezPopupRef = ref, heightMode: 'auto', size: 'medium', ezTitle: this.getMessage("snkSimpleFormConfig.popup.title") }, h("div", { class: 'config-container' }, h("div", { class: 'config-lists' }, h("ez-double-list", { ref: (ref) => this.ezDoubleListRef = ref, leftList: this.avaliableFields, leftTitle: this.getMessage("snkSimpleFormConfig.lists.availableFields"), rightList: this.selectedFields, rightTitle: this.getMessage("snkSimpleFormConfig.lists.selectedFields"), onEzRightListChanged: ({ detail }) => this.fieldsToSave = [...detail], entityLabel: this.getMessage("snkSimpleFormConfig.lists.entityLabel"), entityLabelPlural: this.getMessage("snkSimpleFormConfig.lists.entityLabelPlural") })), h("div", { class: 'config-actions' }, h("ez-button", { label: this.getMessage("snkSimpleFormConfig.buttons.restore"), onClick: this.handleResetConfigs.bind(this), size: 'small' }), h("ez-button", { label: this.getMessage("snkSimpleFormConfig.buttons.cancel"), onClick: this.handleCancel.bind(this), size: 'small' }), h("ez-button", { label: this.getMessage("snkSimpleFormConfig.buttons.save"), class: 'ez-button--primary', onClick: this.handleSave.bind(this), size: 'small' })))));
  }
};
SnkSimpleFormConfig.style = snkSimpleFormConfigCss;

const snkViewRepresentationCss = ".sc-snk-view-representation-h{display:block}.svg-container.sc-snk-view-representation{display:flex;width:185px;height:125px;border-radius:8px;background-color:#f7f7f7;padding:10px 12px;box-sizing:border-box;position:relative}.svg-container__background.sc-snk-view-representation{display:flex;flex-direction:column;width:100%}.svg-container__header.sc-snk-view-representation{display:flex;gap:2px;margin-bottom:12px}.svg-container__circle.sc-snk-view-representation{width:9px;height:9px;border-radius:50%}.svg-container__circle--red.sc-snk-view-representation{background-color:#ed7678}.svg-container__circle--yellow.sc-snk-view-representation{background-color:#eddb76}.svg-container__circle--green.sc-snk-view-representation{background-color:#7ad08e}.svg-container__section.sc-snk-view-representation{width:100%}.svg-container__collumn.sc-snk-view-representation{width:100%;display:flex;flex-direction:column}.svg-container__inline.sc-snk-view-representation{display:flex;flex-direction:row;gap:6px}.svg-container__line.sc-snk-view-representation{height:13px;border-radius:4px;background-color:#d9d9d9;margin-bottom:4px}.svg-container__line--short.sc-snk-view-representation{width:39.68px;height:7px;border-radius:3.5px}.svg-container__line--long.sc-snk-view-representation{width:100%}";

const SnkViewRepresentation = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.mode = FormLayout.SIDE_BY_SIDE;
  }
  renderCascadeLayout() {
    return (h("div", { class: "svg-container__collumn" }, [...Array(3)].map(() => (h("div", { class: "svg-container__section" }, h("div", { class: "svg-container__line svg-container__line--short" }), h("div", { class: "svg-container__line svg-container__line--long" }))))));
  }
  renderSideBySideLayout() {
    return (h("div", { class: "svg-container__inline" }, [...Array(2)].map(() => this.renderCascadeLayout())));
  }
  render() {
    return (h("div", { class: "svg-container ez-margin-left--small" }, h("div", { class: "svg-container__background" }, h("div", { class: "svg-container__header" }, h("div", { class: "svg-container__circle svg-container__circle--red" }), h("div", { class: "svg-container__circle svg-container__circle--yellow" }), h("div", { class: "svg-container__circle svg-container__circle--green" })), this.mode === FormLayout.CASCADE
      ? this.renderCascadeLayout()
      : this.renderSideBySideLayout())));
  }
};
SnkViewRepresentation.style = snkViewRepresentationCss;

const taskbarActionsButtonCss = ".sc-taskbar-actions-button-h{--ez-dropdown--min-width:150px;display:flex;width:fit-content;height:fit-content}.ez-dropdown-container.sc-taskbar-actions-button{position:relative;display:inline-block}.ez-dropdown--sticky.sc-taskbar-actions-button{position:absolute;display:block;min-width:var(--ez-dropdown--min-width)}";

const TaskbarActionsButton = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.taskbarActionSelected = createEvent(this, "taskbarActionSelected", 7);
    this.taskbarActionsOpened = createEvent(this, "taskbarActionsOpened", 7);
    this.taskbarActionsButtonDisconnected = createEvent(this, "taskbarActionsButtonDisconnected", 7);
    this._showDropdown = false;
    this.title = undefined;
    this.enabled = undefined;
    this.actions = undefined;
  }
  async handleKeyDown(event) {
    if (event.key === 'Escape' || event.key === 'Esc') {
      await this.hideActions();
    }
  }
  async handleClose() {
    await this.hideActions();
  }
  /**
   * Exibe a lista de ações.
   */
  async showActions() {
    this._showDropdown = true;
    requestAnimationFrame(() => {
      this._element.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' });
    });
  }
  /**
   * Esaconde a lista de ações.
   */
  async hideActions() {
    this._showDropdown = false;
  }
  /**
   * Informa se a lista de ações está aberta.
   */
  async isOpened() {
    return this._showDropdown;
  }
  controlDropdown() {
    this._showDropdown = !this._showDropdown;
  }
  loadItems() {
    return this.actions.filter(action => action !== undefined).map(action => {
      var _a;
      return {
        id: action.value,
        label: action.label,
        value: action.value,
        type: (_a = action.type) !== null && _a !== void 0 ? _a : 'item',
        children: action.children,
        iconName: action.iconName,
        subAction: action.subAction,
        group: action.group,
        disableCloseOnSelect: action.disableCloseOnSelect,
      };
    });
  }
  canShowDropdown() {
    var _a;
    return this._showDropdown && ((_a = this.actions) === null || _a === void 0 ? void 0 : _a.length) > 0;
  }
  onSelectAction(iAction) {
    const actions = this.actions.map(action => (Object.assign(Object.assign({}, action), { id: action.value })));
    const selectedAction = this.getSelectedAction(iAction.id, actions);
    this.taskbarActionSelected.emit(selectedAction);
    if (!selectedAction.disableCloseOnSelect) {
      this._showDropdown = false;
    }
  }
  getSelectedAction(id, actions) {
    let selectedItem = null;
    for (const item of actions) {
      if (item.id === id) {
        selectedItem = item;
        break;
      }
      if (!(item === null || item === void 0 ? void 0 : item.children))
        continue;
      selectedItem = this.getSelectedAction(id, item.children);
      if (selectedItem)
        break;
    }
    return selectedItem;
  }
  dropdownItemBuilder(item, _level) {
    const itemAction = this.actions.find(action => action.value === item.id);
    if (!itemAction || !itemAction.itemBuilder) {
      return undefined;
    }
    const customContent = itemAction.itemBuilder(this._element, itemAction);
    if (typeof customContent === 'string') {
      return h("div", { innerHTML: customContent });
    }
    return customContent;
  }
  /**
   * Existem algumas actions que precisam ser inicializadas assim que o componente é carregado,
   * pois necessitam de algumas informações, como por exemplo a referência do elemento taskbar-actions-button na tela.
   * É o caso do searchColumn/searhField
   */
  initializeEagerItems() {
    var _a;
    (_a = this.actions) === null || _a === void 0 ? void 0 : _a.forEach(action => {
      var _a;
      if (action && action.eagerInitialize && action.itemBuilder) {
        (_a = action.itemBuilder) === null || _a === void 0 ? void 0 : _a.call(action, this._element, action);
      }
    });
  }
  componentDidLoad() {
    this.initializeEagerItems();
  }
  componentDidRender() {
    if (this._showDropdown) {
      this.taskbarActionsOpened.emit(this._element);
    }
  }
  disconnectedCallback() {
    this.taskbarActionsButtonDisconnected.emit();
  }
  render() {
    return (h(Host, null, h("div", { class: `${this.canShowDropdown() ? ' ez-elevation--16' : ''} ez-dropdown-container` }, h("ez-button", { title: this.title, mode: 'icon', iconName: 'dots-vertical', size: 'small', enabled: this.enabled, onClick: () => this.controlDropdown() }), this.canShowDropdown() && h("ez-dropdown", { class: `ez-dropdown--sticky`, items: this.loadItems(), onEzClick: (evt) => this.onSelectAction(evt.detail), onEzOutsideClick: () => this._showDropdown = false, itemBuilder: (item, level) => this.dropdownItemBuilder(item, level) }))));
  }
  get _element() { return getElement(this); }
};
TaskbarActionsButton.style = taskbarActionsButtonCss;

const taskbarSplitButtonCss = "";

const TaskbarSplitButton = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this._showDropdown = false;
    this.iconName = undefined;
    this.action = undefined;
    this.name = undefined;
    this.className = undefined;
    this.dataElementId = undefined;
    this.title = undefined;
    this.enabled = undefined;
    this.actions = undefined;
  }
  initializeEagerItems() {
    var _a;
    (_a = this.actions) === null || _a === void 0 ? void 0 : _a.forEach(action => {
      var _a;
      if (action && action.eagerInitialize && action.itemBuilder) {
        (_a = action.itemBuilder) === null || _a === void 0 ? void 0 : _a.call(action, this._splitButtonRef, action);
      }
    });
  }
  componentDidLoad() {
    this.initializeEagerItems();
  }
  dropdownItemBuilder(item, _level) {
    const itemAction = this.actions.find(action => action.value === item.id);
    if (!itemAction || !itemAction.itemBuilder) {
      return undefined;
    }
    const customContent = itemAction.itemBuilder(this._splitButtonRef, itemAction);
    if (typeof customContent === 'string') {
      return h("div", { innerHTML: customContent });
    }
    return customContent;
  }
  loadItems() {
    return this.actions.filter(action => action !== undefined).map(action => {
      var _a;
      return {
        id: action.value,
        label: action.label,
        value: action.value,
        type: (_a = action.type) !== null && _a !== void 0 ? _a : 'item',
        children: action.children,
        iconName: action.iconName,
        subAction: action.subAction,
        group: action.group,
        disableCloseOnSelect: action.disableCloseOnSelect,
      };
    });
  }
  render() {
    return (h(Host, null, h("ez-split-button", { ref: (ref) => this._splitButtonRef = ref, key: this.dataElementId, class: `${this.className} "ez-split-button--tertiary ez-padding--medium"`, items: this.loadItems(), mode: "icon-only", iconName: this.iconName, enabled: this.enabled, show: this._showDropdown, onButtonClick: () => this.action(this.name), itemBuilder: (item, level) => this.dropdownItemBuilder(item, level) })));
  }
};
TaskbarSplitButton.style = taskbarSplitButtonCss;

export { SnkActionsButton as snk_actions_button, SnkGridConfig as snk_grid_config, SnkLayoutFormConfig as snk_layout_form_config, SelectBox as snk_select_box, SnkSimpleFormConfig as snk_simple_form_config, SnkViewRepresentation as snk_view_representation, TaskbarActionsButton as taskbar_actions_button, TaskbarSplitButton as taskbar_split_button };
