import { r as registerInstance, h, f as Host, g as getElement } from './index-e9c7ceaa.js';
import { ApplicationContext, ObjectUtils, UserInterface, DataType, ElementIDUtils } from '@sankhyalabs/core';
import { ApplicationUtils, DialogType } from '@sankhyalabs/ezui/dist/collection/utils';
import { I as IExportType } from './IFetchDataExporterParams-d73bed3d.js';
import { D as DataExporterOption, a as DataExporterType, b as DataExporterFormat } from './index-b40568ff.js';
import { R as REPORT_LAUNCHER_RESOURCE_ID } from './constants-7b422de0.js';
import { D as DataFetcher } from './DataFetcher-955ee53e.js';
import { S as SnkDataUnit } from './snk-data-unit-b02cb4e0.js';
import './ISave-c8bf12c4.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 './form-config-fetcher-baa89098.js';
import './PrintUtils-3e4ff0f5.js';
import '@sankhyalabs/core/dist/dataunit/metadata/DataType';
import './GetSelectedRecordsIDsInfo-9fa41508.js';
import '@sankhyalabs/ezui/dist/collection/components/ez-grid/utils';
import '@sankhyalabs/core/dist/utils/SortingUtils';
import './ResourceIDUtils-a114189a.js';

class ItemBuilder {
  constructor(getMessage, selectedNumber) {
    this._selectedNumber = 0;
    this._getMessage = getMessage;
    this._selectedNumber = selectedNumber;
  }
  /**
   * Método responsável por inserir os items no array de opções.
   * @param option - Nome da opção que será inserida no array.
   * @param items - Array que será alimentado com as opções permitidas.
   */
  setExportOption(option, items) {
    const groupName = this.getExportGroupName();
    if (option === DataExporterOption.EXPORT_TO_PDF) {
      items.push(this.getExportToPDF(groupName));
    }
    if (option === DataExporterOption.EXPORT_TO_XLS) {
      items.push(this.getExportToXLS(groupName));
    }
    this.setExportCurrentPage(option, items);
    if (this._selectedNumber > 0) {
      this.setExportAllRecords(option, items);
    }
    this.setExportByEmail(option, items);
  }
  /**
   * Método responsável por inserir os itens de exportação personalizada.
   * @param option - Nome da opção que será inserida no array.
   * @param items - Array que será alimentado com as opções permitidas.
   */
  setExportCurrentPage(option, items) {
    var _a;
    const pageOptions = [DataExporterOption.EXPORT_PAGE_TO_PDF, DataExporterOption.EXPORT_PAGE_TO_XLS];
    if (option === DataExporterOption.EXPORT_CURRENT_PAGE) {
      items.push(this.getCurrentPage());
    }
    if (pageOptions.includes(option)) {
      let item = items.find((item) => item.id === DataExporterOption.EXPORT_CURRENT_PAGE);
      if (item == undefined) {
        items.push(this.getCurrentPage());
        item = items.find((item) => item.id === DataExporterOption.EXPORT_CURRENT_PAGE);
      }
      if (!((_a = item === null || item === void 0 ? void 0 : item.children) === null || _a === void 0 ? void 0 : _a.length)) {
        item.children = [];
      }
      if (option === DataExporterOption.EXPORT_PAGE_TO_PDF) {
        item.children.push(this.getExportPageToPDF());
      }
      if (option === DataExporterOption.EXPORT_PAGE_TO_XLS) {
        item.children.push(this.getExportPageToXLS());
      }
    }
  }
  /**
   * Método responsável por inserir os itens de exportação para todos os registros.
   * @param option - Nome da opção que será inserida no array.
   * @param items - Array que será alimentado com as opções permitidas.
   */
  setExportAllRecords(option, items) {
    var _a;
    const pageOptions = [DataExporterOption.EXPORT_ALL_RECORDS_TO_PDF, DataExporterOption.EXPORT_ALL_RECORDS_TO_XLS];
    if (option === DataExporterOption.EXPORT_ALL_RECORDS) {
      items.push(this.getAllRecords());
    }
    if (pageOptions.includes(option)) {
      let item = items.find((item) => item.id === DataExporterOption.EXPORT_ALL_RECORDS);
      if (item == undefined) {
        items.push(this.getAllRecords());
        item = items.find((item) => item.id === DataExporterOption.EXPORT_ALL_RECORDS);
      }
      if (!((_a = item.children) === null || _a === void 0 ? void 0 : _a.length)) {
        item.children = [];
      }
      if (option === DataExporterOption.EXPORT_ALL_RECORDS_TO_PDF) {
        item.children.push(this.getExportAllRecordsToPDF());
      }
      if (option === DataExporterOption.EXPORT_ALL_RECORDS_TO_XLS) {
        item.children.push(this.getExportAllRecordsToXLS());
      }
    }
  }
  /**
   * Método responsável por inserir os itens de exportação por e-mail.
   * @param option - Nome da opção que será inserida no array.
   * @param items - Array que será alimentado com as opções permitidas.
   */
  setExportByEmail(option, items) {
    if (option === DataExporterOption.EXPORT_BY_EMAIL) {
      items.push(this.getExportByEmail());
    }
  }
  /**
   * Método responsável por capturar o objeto com os dados de exportação em PDF.
   * @param groupName - Nome do grupo da opção que será inserida na lista.
   * @returns Retorna o objeto com os dados de exportação em PDF.
   */
  getExportToPDF(groupName) {
    return {
      id: DataExporterOption.EXPORT_TO_PDF,
      label: "PDF (.pdf)",
      group: groupName
    };
  }
  /**
   * Método responsável por capturar o objeto com os dados de exportação em XLS.
   * @param groupName - Nome do grupo da opção que será inserida na lista.
   * @returns Retorna o objeto com os dados de exportação em XLS.
   */
  getExportToXLS(groupName) {
    return {
      id: DataExporterOption.EXPORT_TO_XLS,
      label: `${this._getMessage("snkDataExporter.label.spreadsheet")} (.xls)`,
      group: groupName
    };
  }
  /**
   * Método responsável por capturar o objeto com os dados de exportação personalizada.
   * @returns Retorna o objeto com os dados de exportação personalizada.
   */
  getCurrentPage() {
    return {
      id: DataExporterOption.EXPORT_CURRENT_PAGE,
      label: this._getMessage("snkDataExporter.label.currentPage"),
      group: this._getMessage("snkDataExporter.group.custom")
    };
  }
  /**
   * Método responsável por capturar o objeto com todos os dados de exportação.
   * @returns Retorna o objeto com todos os dados de exportação.
   */
  getAllRecords() {
    return {
      id: DataExporterOption.EXPORT_ALL_RECORDS,
      label: this._getMessage("snkDataExporter.label.allRecords"),
      group: this._getMessage("snkDataExporter.group.custom")
    };
  }
  /**
   * Método responsável por capturar o objeto com os dados de exportação personalizada em PDF.
   * @returns Retorna o objeto com os dados de exportação personalizada em PDF.
   */
  getExportPageToPDF() {
    return {
      id: DataExporterOption.EXPORT_PAGE_TO_PDF,
      label: "PDF (.pdf)"
    };
  }
  /**
   * Método responsável por capturar o objeto com os dados de exportação personalizada em XLS.
   * @returns Retorna o objeto com os dados de exportação personalizada em XLS.
   */
  getExportPageToXLS() {
    return {
      id: DataExporterOption.EXPORT_PAGE_TO_XLS,
      label: `${this._getMessage("snkDataExporter.label.spreadsheet")} (.xls)`
    };
  }
  /**
   * Método responsável por capturar o objeto com todos os dados de exportação em PDF.
   * @returns Retorna o objeto com todos os dados de exportação em PDF.
   */
  getExportAllRecordsToPDF() {
    return {
      id: DataExporterOption.EXPORT_ALL_RECORDS_TO_PDF,
      label: "PDF (.pdf)"
    };
  }
  /**
   * Método responsável por capturar o objeto com todos os dados de exportação em XLS.
   * @returns Retorna o objeto com todos os dados de exportação em XLS.
   */
  getExportAllRecordsToXLS() {
    return {
      id: DataExporterOption.EXPORT_ALL_RECORDS_TO_XLS,
      label: `${this._getMessage("snkDataExporter.label.spreadsheet")} (.xlsx)`
    };
  }
  /**
   * Método responsável por capturar o objeto com os dados de exportação por e-mail.
   * @returns Retorna o objeto com os dados de exportação por e-mail.
   */
  getExportByEmail() {
    return {
      id: DataExporterOption.EXPORT_BY_EMAIL,
      label: `${this._getMessage("snkDataExporter.label.sendByEmail")}...`
    };
  }
  /**
   * Método responsável por capturar o nome do grupo da opção que será inserida na lista.
   * @returns Retorna o nome do grupo da opção que será inserida na lista.
   */
  getExportGroupName() {
    if (this._selectedNumber === 1) {
      return this._getMessage("snkDataExporter.group.export.selectedLine");
    }
    if (this._selectedNumber > 1) {
      return this._getMessage("snkDataExporter.group.export.multiSelected").replace('{0}', this._selectedNumber.toString());
    }
    return this._getMessage("snkDataExporter.group.export.default");
  }
}

function getMessage(application, key, params) {
  var _a;
  return (_a = application === null || application === void 0 ? void 0 : application.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage(key, params);
}
function fileViewer({ fileSessionKey, isDownload }) {
  const application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
  window.open(`${window.location.protocol}//${window.location.hostname}:${window.location.port}/mge/visualizadorArquivos.mge?chaveArquivo=${fileSessionKey}${isDownload ? "&download=S" : ""}`);
  ApplicationUtils.info(getMessage(application, "fileViewer.message.exportSuccess"), { iconName: "check" });
}

function getPersonalizedReports(requestBody) {
  const application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
  const serviceName = `${application.getModuleName()}@DataExporterSPBean.getPersonalizedReports`;
  const payload = { serviceName, requestBody };
  return new Promise((resolve, reject) => (DataFetcher.get()
    .callServiceBroker(serviceName, ObjectUtils.objectToString(payload))
    .then(result => resolve(getFormatResponse(result)))
    .catch(error => reject(error))));
}
function getFormatResponse(result) {
  var _a;
  const response = (_a = result === null || result === void 0 ? void 0 : result.json) === null || _a === void 0 ? void 0 : _a.$;
  if (response == undefined) {
    return;
  }
  return ObjectUtils.stringToObject(response);
}

const DOC_MAX_WIDTH = 860;
function getVisibleColumns(columns) {
  const visibleColumns = [];
  let totalWidth = 0;
  for (const column of columns) {
    totalWidth += column.width;
    if (totalWidth >= DOC_MAX_WIDTH) {
      break;
    }
    visibleColumns.push(column);
  }
  return visibleColumns;
}
function getOptionKey(option) {
  return Object.keys(DataExporterOption)
    .find((key) => {
    return DataExporterOption[key] === option;
  });
}

var __rest = (undefined && undefined.__rest) || function (s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
    t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
class ServerSideExporterStrategy {
  constructor(provider) {
    this._provider = provider;
  }
  async getParsedColumns() {
    const columns = await this._provider.getColumnsMetadata();
    const visibleColumns = getVisibleColumns(columns);
    return visibleColumns;
  }
  async getColumns(resolveProps) {
    var _a;
    if ((_a = getOptionKey(resolveProps === null || resolveProps === void 0 ? void 0 : resolveProps.exportOption)) === null || _a === void 0 ? void 0 : _a.includes("PDF")) {
      return await this.getParsedColumns();
    }
    return await this._provider.getColumnsMetadata();
  }
  async getParams(resolveProps) {
    var _a, _b, _c, _d, _e, _f;
    const filters = (_b = (_a = this._provider).getFilters) === null || _b === void 0 ? void 0 : _b.call(_a);
    const columns = await this.getColumns(resolveProps);
    const sort = (_d = (_c = this._provider).getOrders) === null || _d === void 0 ? void 0 : _d.call(_c);
    const resourceURI = (_f = (_e = this._provider).getResourceURI) === null || _f === void 0 ? void 0 : _f.call(_e);
    const selectedIDs = this._provider.getSelectedIDs();
    const option = resolveProps.exportOption;
    const currentPageOptions = [
      DataExporterOption.EXPORT_PAGE_TO_PDF,
      DataExporterOption.EXPORT_PAGE_TO_XLS
    ];
    delete resolveProps.exportOption;
    let params = Object.assign({ filters,
      columns,
      sort,
      resourceURI, selectedIDs: selectedIDs.slice(0, this._provider.getExportLimit()) }, resolveProps);
    if (currentPageOptions.includes(option) || resolveProps.type == "page") {
      const offset = this._provider.getOffset();
      const limit = this._provider.getPageSize();
      params = Object.assign(Object.assign({}, params), { offset,
        limit, selectedIDs: [] });
    }
    else if (resolveProps.type == "all") {
      params = Object.assign(Object.assign({}, params), { offset: 0, limit: this._provider.getExportLimit(), selectedIDs: [] });
    }
    return Promise.resolve(params);
  }
  async executeExport(resolveProps) {
    const _a = await this.getParams(resolveProps), { methodName } = _a, requestBody = __rest(_a, ["methodName"]);
    const application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    const serviceName = `${application.getModuleName()}@DataExporterSPBean.${methodName}`;
    const payload = { serviceName, requestBody };
    return new Promise((resolve, reject) => {
      DataFetcher.get()
        .callServiceBroker(serviceName, ObjectUtils.objectToString(payload))
        .then(result => resolve(this.getFormatResponse(result)))
        .catch(error => reject(error));
    });
  }
  getFormatResponse(result) {
    var _a;
    const response = (_a = result === null || result === void 0 ? void 0 : result.json) === null || _a === void 0 ? void 0 : _a.$;
    if (response == undefined) {
      return;
    }
    return ObjectUtils.stringToObject(response);
  }
}

class ClientSideExporterStrategy {
  constructor(provider) {
    this._provider = provider;
  }
  async getParsedColumns() {
    const columns = await this._provider.getColumnsMetadata();
    const visibleColumns = getVisibleColumns(columns);
    return visibleColumns;
  }
  async executeExport(resolveProps) {
    var _a;
    const { methodName, gridTitle } = resolveProps;
    const records = await this._provider.getRecords(resolveProps.type);
    const columns = ((_a = getOptionKey(resolveProps === null || resolveProps === void 0 ? void 0 : resolveProps.exportOption)) === null || _a === void 0 ? void 0 : _a.includes("PDF")) ? await this.getParsedColumns() : await this._provider.getColumnsMetadata();
    const [serviceName, processor] = this.getExecutor(methodName);
    const payload = {
      serviceName,
      requestBody: {
        grid: {
          gridTitle,
          columns: this.buildColumnsObject(columns),
          rows: this.buildRowsObject(columns, records),
          customOptions: { xlsxExtension: false }
        }
      }
    };
    return new Promise((resolve, reject) => {
      DataFetcher.get()
        .callServiceBroker(serviceName, payload)
        .then(result => resolve(processor(result)))
        .catch(error => reject(error));
    });
  }
  getExecutor(methodName) {
    if (methodName === "exportToPDF") {
      return [
        "GridPDFBuilderSP.buildPDFFromJson",
        responseBody => ({
          fileSessionKey: responseBody.chavePDF.valor,
          canPrint: responseBody.permiteImprimir.valor === "S",
          canExport: responseBody.permiteExportar.valor === "S",
          canSendEmail: responseBody.canSendEmail.valor === "S",
          useAppPrint: true
        })
      ];
    }
    return [
      "GridXLSBuilderSP.buildXLSFromJson",
      responseBody => ({
        fileSessionKey: responseBody.chaveXLS.valor,
        canPrint: true,
        canExport: true,
        canSendEmail: true,
        useAppPrint: false,
      })
    ];
  }
  buildColumnsObject(columns) {
    return {
      column: columns.map((column, index) => {
        const { label, id, width, userInterface } = column;
        return Object.assign({ index: index + 1, id,
          label,
          width, presentationType: "P" }, (TYPE_MAP[userInterface] || { type: "S", align: "left" }));
      })
    };
  }
  buildRowsObject(columns, records) {
    return {
      row: records.map(rawRecord => {
        const record = {};
        columns.forEach((column, index) => record["c" + (index + 1)] = { $: this.formatValue(rawRecord, column) });
        return record;
      })
    };
  }
  formatValue(record, column) {
    if (this._provider.formatValue != undefined) {
      return this._provider.formatValue(record, column);
    }
    return record[column.id] || "";
  }
}
const TYPE_MAP = {
  [UserInterface.DATE]: { type: "D", align: "center" },
  [UserInterface.DATETIME]: { type: "H", align: "center" },
  [UserInterface.TIME]: { type: "I", align: "right" },
  [UserInterface.ELAPSEDTIME]: { type: "I", align: "right" },
  [UserInterface.DECIMALNUMBER]: { type: "F", align: "right" },
  [UserInterface.INTEGERNUMBER]: { type: "I", align: "right" },
  [UserInterface.SEARCH]: { type: "S", align: "right" }
};

const snkDataExporterCss = ".sc-snk-data-exporter-h{display:flex;width:fit-content;height:fit-content}.snk-data-exporter.sc-snk-data-exporter{display:flex;width:fit-content;height:fit-content}.snk-data-exporter__dropdown.sc-snk-data-exporter{display:none}.snk-data-exporter__dropdown--show.sc-snk-data-exporter{display:flex;flex-direction:column;position:fixed}.snk-data-exporter__dropdown.sc-snk-data-exporter>ez-dropdown.sc-snk-data-exporter{position:relative}";

const SnkDataExporter = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this._selectedNumber = 0;
    this._customPrefix = "$custom$";
    this._releasedToExport = [
      DataExporterOption.EXPORT_TO_PDF,
      DataExporterOption.EXPORT_TO_XLS,
      DataExporterOption.EXPORT_BY_EMAIL,
      DataExporterOption.EXPORT_PDF_TO_EMAIL,
      DataExporterOption.EXPORT_XLS_TO_EMAIL,
      DataExporterOption.EXPORT_PAGE_TO_PDF,
      DataExporterOption.EXPORT_PAGE_TO_XLS,
      DataExporterOption.EXPORT_ALL_RECORDS_TO_PDF,
      DataExporterOption.EXPORT_ALL_RECORDS_TO_XLS,
    ];
    this._items = [];
    this._showDropdown = false;
    this.provider = null;
    this.messagesBuilder = undefined;
  }
  async exportByEmail() {
    const selectedRows = this._selectedNumber;
    const config = {
      type: selectedRows > 0 ? "selection" : "all",
      selectedRows,
      email: {
        attachments: [
          { name: this._appLabel }
        ]
      },
      resolver: ({ type, format, email: { to, subject, message } }) => {
        var _a;
        const methodName = (_a = DataExporterFormat[format === null || format === void 0 ? void 0 : format.toUpperCase()]) !== null && _a !== void 0 ? _a : DataExporterFormat.PDF;
        this.resolveExporter({ type, methodName, to, subject, message, fileName: this._appLabel, gridTitle: this._appLabel }, () => {
          this._snkEmailSender.close();
          ApplicationUtils.info(this.getMessage("snkDataExporter.message.emailSuccess"), { iconName: "check" });
        });
      }
    };
    this._snkEmailSender.open(config);
  }
  /**
   * 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-data-exporter.msg.ts"
   */
  getMessage(key, params) {
    if (this.messagesBuilder == undefined) {
      const dataUnit = SnkDataUnit.getNearestInstance(this._element);
      if (dataUnit) {
        this.messagesBuilder = dataUnit.messagesBuilder;
      }
    }
    return this.messagesBuilder.getMessage(key, params);
  }
  positionDropdown() {
    var _a;
    const bounding = (_a = this._ezButton) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
    if (bounding == undefined || this._dropdownParent == undefined) {
      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 == undefined) {
      return;
    }
    if (!target.closest(".snk-data-exporter")) {
      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));
  }
  controlDropdown() {
    this._showDropdown = !this._showDropdown;
  }
  async resolveExporter(resolveProps, callbackResolver) {
    if (this.provider == undefined || resolveProps == undefined || callbackResolver == undefined) {
      return;
    }
    this.getExporterStrategy().executeExport(resolveProps)
      .then((result) => callbackResolver(result))
      .catch((exception) => {
      console.error(exception);
      let { title, message, statusMessage } = exception || {};
      ApplicationUtils.error(title || this.getMessage("snkDataExporter.message.exportError"), statusMessage || message || this.getMessage("snkDataExporter.message.unknownFailure"));
    });
  }
  getExporterStrategy() {
    return this.provider.getRecords == undefined
      ? new ServerSideExporterStrategy(this.provider)
      : new ClientSideExporterStrategy(this.provider);
  }
  getOptionKey(option) {
    return Object.keys(DataExporterOption)
      .find((key) => {
      return DataExporterOption[key] === option;
    });
  }
  getExportType(option) {
    if (option === DataExporterOption.EXPORT_ALL_RECORDS_TO_PDF || option === DataExporterOption.EXPORT_ALL_RECORDS_TO_XLS) {
      return IExportType.ALL;
    }
    if (option === DataExporterOption.EXPORT_PAGE_TO_PDF || option === DataExporterOption.EXPORT_PAGE_TO_XLS) {
      return IExportType.PAGE;
    }
    return IExportType.SELECTION;
  }
  async dispatchExporter(option) {
    var _a, _b, _c;
    const optionKey = this.getOptionKey(option);
    const fileType = (_a = DataExporterType[optionKey]) !== null && _a !== void 0 ? _a : DataExporterType.EXPORT_TO_PDF;
    const params = {
      methodName: DataExporterOption[`EXPORT_TO_${fileType}`],
      fileName: this._appLabel,
      gridTitle: this._appLabel,
      exportOption: option,
      limit: (_c = (_b = this.provider) === null || _b === void 0 ? void 0 : _b.getExportLimit) === null || _c === void 0 ? void 0 : _c.call(_b),
      type: this.getExportType(option),
    };
    await this.resolveExporter(params, (response) => {
      if (response.canExport || fileType === DataExporterType.EXPORT_TO_PDF) {
        fileViewer(Object.assign(Object.assign({}, response), { fileType }));
      }
      else {
        ApplicationUtils.error(this.getMessage("snkDataExporter.title.permission"), this.getMessage("snkDataExporter.message.exportPermission"));
      }
    });
  }
  async processExporter(evt) {
    var _a, _b, _c, _d, _e, _f, _g;
    const item = evt === null || evt === void 0 ? void 0 : evt.detail;
    const exportCurrentPageOptions = [DataExporterOption.EXPORT_PAGE_TO_PDF, DataExporterOption.EXPORT_PAGE_TO_XLS];
    const isCustomReport = (_a = item === null || item === void 0 ? void 0 : item.id) === null || _a === void 0 ? void 0 : _a.includes(this._customPrefix);
    if ((item === null || item === void 0 ? void 0 : item.id) === DataExporterOption.EXPORT_CURRENT_PAGE)
      return;
    const selectedRecords = (_b = this.provider) === null || _b === void 0 ? void 0 : _b.getSelectedIDs();
    const totalRecords = (_c = this.provider) === null || _c === void 0 ? void 0 : _c.getTotalRecords();
    const totalPerPage = (_e = (_d = this.provider) === null || _d === void 0 ? void 0 : _d.getPageSize) === null || _e === void 0 ? void 0 : _e.call(_d);
    const exportLimit = (_g = (_f = this.provider) === null || _f === void 0 ? void 0 : _f.getExportLimit) === null || _g === void 0 ? void 0 : _g.call(_f);
    let limitExceeded = false;
    if ((exportCurrentPageOptions.includes(item === null || item === void 0 ? void 0 : item.id) && totalPerPage <= exportLimit) || isCustomReport) {
      limitExceeded = false;
    }
    else if (selectedRecords === null || selectedRecords === void 0 ? void 0 : selectedRecords.length) {
      limitExceeded = selectedRecords.length > exportLimit;
    }
    else if (totalRecords > exportLimit)
      limitExceeded = true;
    if (limitExceeded) {
      const formattedLimit = exportLimit.toLocaleString('pt-BR', { minimumFractionDigits: 0 });
      const limitModalMessages = {
        title: this.getMessage("snkDataExporter.limitExceeded.title"),
        description: `
          ${this.getMessage("snkDataExporter.limitExceeded.description", { limit: formattedLimit })}
          <br/><br/>
          <b>
          ${this.getMessage("snkDataExporter.limitExceeded.subdescription")}
          </b>
        `,
        cancel: this.getMessage("snkDataExporter.limitExceeded.cancel"),
        confirm: this.getMessage("snkDataExporter.limitExceeded.continue")
      };
      const isAccepted = await ApplicationUtils.confirm(limitModalMessages.title, limitModalMessages.description, null, DialogType.WARN, {
        labelCancel: limitModalMessages.cancel,
        labelConfirm: limitModalMessages.confirm,
      });
      if (!isAccepted)
        return;
    }
    if (isCustomReport) {
      this.openPersonalizedReports(item.id);
      this._showDropdown = false;
      return;
    }
    if (!this.getFilteredReleasedToExport().includes(item === null || item === void 0 ? void 0 : item.id)) {
      return;
    }
    if (item.id === DataExporterOption.EXPORT_BY_EMAIL) {
      this.exportByEmail();
    }
    else {
      this.dispatchExporter(item.id);
    }
    this._showDropdown = false;
  }
  getFilteredReleasedToExport() {
    var _a, _b;
    if (this.provider == undefined) {
      return this._releasedToExport;
    }
    const hiddenOptions = (_b = (_a = this.provider).getHiddenOptions) === null || _b === void 0 ? void 0 : _b.call(_a);
    if (hiddenOptions == undefined) {
      return this._releasedToExport;
    }
    return this._releasedToExport.filter(option => !hiddenOptions.includes(option));
  }
  loadItems() {
    const items = [];
    this.getFilteredReleasedToExport()
      .forEach((option) => {
      var _a;
      (_a = this._itemBuilder) === null || _a === void 0 ? void 0 : _a.setExportOption(option, items);
    });
    this.loadPersonalizedItems(items);
  }
  async loadPersonalizedItems(items) {
    var _a, _b;
    const recordID = (_b = (_a = this.provider) === null || _a === void 0 ? void 0 : _a.getRecordID) === null || _b === void 0 ? void 0 : _b.call(_a);
    if (recordID == undefined) {
      this._items = items;
      return;
    }
    const personalizedReports = await getPersonalizedReports({ recordID });
    personalizedReports === null || personalizedReports === void 0 ? void 0 : personalizedReports.forEach((item) => {
      items.push({
        id: `${this._customPrefix}_${item.ID}`,
        label: item.label,
        group: this.getMessage("snkDataExporter.group.custom")
      });
    });
    this._items = items;
  }
  openPersonalizedReports(option) {
    var _a, _b;
    const pkObject = [];
    const appId = (option === null || option === void 0 ? void 0 : option.replace(this._customPrefix, "")) || "";
    (_b = (_a = this.provider) === null || _a === void 0 ? void 0 : _a.getSelectedIDs) === null || _b === void 0 ? void 0 : _b.call(_a).forEach(({ name, type, value }, index) => {
      const fields = {};
      fields['fields'] = [];
      // Se for o primeiro elemento, adiciona essa primeira PK
      if (index === 0) {
        pkObject[`PK_${name}`] = { type: this.parseDataType(type), value };
        pkObject['pks'] = [];
      }
      const dataFields = { nome: `PK_${name}`, tipo: this.parseDataType(type), valor: value };
      fields['fields'].push(dataFields);
      pkObject['pks'].push(fields);
    });
    this._application.openApp(`${REPORT_LAUNCHER_RESOURCE_ID}${appId}`, pkObject);
  }
  parseDataType(type) {
    switch (type) {
      case DataType.NUMBER:
        return "I";
      case DataType.DATE:
        return "D";
      default:
        return "S";
    }
  }
  loadDropdown() {
    var _a;
    this._selectedNumber = ((_a = this.provider) === null || _a === void 0 ? void 0 : _a.getSelectedNumber()) || 0;
    this._itemBuilder = new ItemBuilder(this.getMessage.bind(this), this._selectedNumber);
    this.loadItems();
  }
  getElementID(sufix) {
    return {
      [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(sufix)
    };
  }
  canShowDropdown() {
    var _a;
    return this._showDropdown && ((_a = this._items) === null || _a === void 0 ? void 0 : _a.length) > 0;
  }
  componentWillLoad() {
    var _a;
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    (_a = this._application) === null || _a === void 0 ? void 0 : _a.getAppLabel().then(result => this._appLabel = result);
    this.setEvents();
  }
  componentDidLoad() {
    if (this._element == undefined) {
      return;
    }
    ElementIDUtils.addIDInfo(this._element);
    this.positionDropdown();
  }
  componentWillUpdate() {
    var _a;
    if (this._showDropdown && !((_a = this._items) === null || _a === void 0 ? void 0 : _a.length)) {
      this.loadDropdown();
    }
  }
  componentDidUpdate() {
    var _a;
    if (this._showDropdown) {
      this.positionDropdown();
    }
    else if (((_a = this._items) === null || _a === void 0 ? void 0 : _a.length) > 0) {
      this._items = [];
    }
  }
  render() {
    return (h(Host, null, h("div", { class: `snk-data-exporter
          ${this.canShowDropdown() ? " ez-elevation--16" : ""}
        ` }, h("ez-button", Object.assign({ ref: (ref) => this._ezButton = ref, iconName: "file-download", size: "small", mode: "icon", title: this.getMessage("snkDataExporter.group.export.title"), onClick: () => this.controlDropdown() }, this.getElementID("button"))), h("div", Object.assign({ ref: (ref) => this._dropdownParent = ref, class: `snk-data-exporter__dropdown
              ${this.canShowDropdown() ? "snk-data-exporter__dropdown--show" : ""}
            ` }, this.getElementID("dropdown")), this.canShowDropdown() &&
      h("ez-dropdown", Object.assign({ items: this._items, onEzClick: (evt) => this.processExporter(evt) }, this.getElementID("dropdown"))))), this.canShowDropdown() &&
      h("div", Object.assign({ class: "ez-scrim ez-scrim--light" }, this.getElementID("ezScrim"))), h("snk-exporter-email-sender", Object.assign({ ref: ref => this._snkEmailSender = ref, getMessage: (key, params) => this.getMessage(key, params) }, this.getElementID("snkExporterEmailSender")))));
  }
  get _element() { return getElement(this); }
};
SnkDataExporter.style = snkDataExporterCss;

export { SnkDataExporter as snk_data_exporter };
