'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index$1 = require('./index-17105557.js');
const core = require('@sankhyalabs/core');
const utils = require('@sankhyalabs/ezui/dist/collection/utils');
const IFetchDataExporterParams = require('./IFetchDataExporterParams-e78ec415.js');
const index = require('./index-e3e39724.js');
const constants = require('./constants-6d82e405.js');
const DataFetcher = require('./DataFetcher-21f8c2dc.js');
const snkDataUnit = require('./snk-data-unit-42138745.js');
require('./ISave-f926fe9e.js');
require('@sankhyalabs/ezui/dist/collection/utils/constants');
require('@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata');
require('./dataunit-fetcher-6c85a04d.js');
require('./filter-item-type.enum-a7ffdaa6.js');
require('./form-config-fetcher-fef79845.js');
require('./PrintUtils-bcaeb82f.js');
require('@sankhyalabs/core/dist/dataunit/metadata/DataType');
require('./GetSelectedRecordsIDsInfo-bd50caf1.js');
require('@sankhyalabs/ezui/dist/collection/components/ez-grid/utils');
require('@sankhyalabs/core/dist/utils/SortingUtils');
require('./ResourceIDUtils-5ff86aa7.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 === index.DataExporterOption.EXPORT_TO_PDF) {
      items.push(this.getExportToPDF(groupName));
    }
    if (option === index.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 = [index.DataExporterOption.EXPORT_PAGE_TO_PDF, index.DataExporterOption.EXPORT_PAGE_TO_XLS];
    if (option === index.DataExporterOption.EXPORT_CURRENT_PAGE) {
      items.push(this.getCurrentPage());
    }
    if (pageOptions.includes(option)) {
      let item = items.find((item) => item.id === index.DataExporterOption.EXPORT_CURRENT_PAGE);
      if (item == undefined) {
        items.push(this.getCurrentPage());
        item = items.find((item) => item.id === index.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 === index.DataExporterOption.EXPORT_PAGE_TO_PDF) {
        item.children.push(this.getExportPageToPDF());
      }
      if (option === index.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 = [index.DataExporterOption.EXPORT_ALL_RECORDS_TO_PDF, index.DataExporterOption.EXPORT_ALL_RECORDS_TO_XLS];
    if (option === index.DataExporterOption.EXPORT_ALL_RECORDS) {
      items.push(this.getAllRecords());
    }
    if (pageOptions.includes(option)) {
      let item = items.find((item) => item.id === index.DataExporterOption.EXPORT_ALL_RECORDS);
      if (item == undefined) {
        items.push(this.getAllRecords());
        item = items.find((item) => item.id === index.DataExporterOption.EXPORT_ALL_RECORDS);
      }
      if (!((_a = item.children) === null || _a === void 0 ? void 0 : _a.length)) {
        item.children = [];
      }
      if (option === index.DataExporterOption.EXPORT_ALL_RECORDS_TO_PDF) {
        item.children.push(this.getExportAllRecordsToPDF());
      }
      if (option === index.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 === index.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: index.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: index.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: index.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: index.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: index.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: index.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: index.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: index.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: index.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 = core.ApplicationContext.getContextValue("__SNK__APPLICATION__");
  window.open(`${window.location.protocol}//${window.location.hostname}:${window.location.port}/mge/visualizadorArquivos.mge?chaveArquivo=${fileSessionKey}${isDownload ? "&download=S" : ""}`);
  utils.ApplicationUtils.info(getMessage(application, "fileViewer.message.exportSuccess"), { iconName: "check" });
}

function getPersonalizedReports(requestBody) {
  const application = core.ApplicationContext.getContextValue("__SNK__APPLICATION__");
  const serviceName = `${application.getModuleName()}@DataExporterSPBean.getPersonalizedReports`;
  const payload = { serviceName, requestBody };
  return new Promise((resolve, reject) => (DataFetcher.DataFetcher.get()
    .callServiceBroker(serviceName, core.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 core.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(index.DataExporterOption)
    .find((key) => {
    return index.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 = [
      index.DataExporterOption.EXPORT_PAGE_TO_PDF,
      index.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 = core.ApplicationContext.getContextValue("__SNK__APPLICATION__");
    const serviceName = `${application.getModuleName()}@DataExporterSPBean.${methodName}`;
    const payload = { serviceName, requestBody };
    return new Promise((resolve, reject) => {
      DataFetcher.DataFetcher.get()
        .callServiceBroker(serviceName, core.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 core.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.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 = {
  [core.UserInterface.DATE]: { type: "D", align: "center" },
  [core.UserInterface.DATETIME]: { type: "H", align: "center" },
  [core.UserInterface.TIME]: { type: "I", align: "right" },
  [core.UserInterface.ELAPSEDTIME]: { type: "I", align: "right" },
  [core.UserInterface.DECIMALNUMBER]: { type: "F", align: "right" },
  [core.UserInterface.INTEGERNUMBER]: { type: "I", align: "right" },
  [core.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) {
    index$1.registerInstance(this, hostRef);
    this._selectedNumber = 0;
    this._customPrefix = "$custom$";
    this._releasedToExport = [
      index.DataExporterOption.EXPORT_TO_PDF,
      index.DataExporterOption.EXPORT_TO_XLS,
      index.DataExporterOption.EXPORT_BY_EMAIL,
      index.DataExporterOption.EXPORT_PDF_TO_EMAIL,
      index.DataExporterOption.EXPORT_XLS_TO_EMAIL,
      index.DataExporterOption.EXPORT_PAGE_TO_PDF,
      index.DataExporterOption.EXPORT_PAGE_TO_XLS,
      index.DataExporterOption.EXPORT_ALL_RECORDS_TO_PDF,
      index.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 = index.DataExporterFormat[format === null || format === void 0 ? void 0 : format.toUpperCase()]) !== null && _a !== void 0 ? _a : index.DataExporterFormat.PDF;
        this.resolveExporter({ type, methodName, to, subject, message, fileName: this._appLabel, gridTitle: this._appLabel }, () => {
          this._snkEmailSender.close();
          utils.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.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 || {};
      utils.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(index.DataExporterOption)
      .find((key) => {
      return index.DataExporterOption[key] === option;
    });
  }
  getExportType(option) {
    if (option === index.DataExporterOption.EXPORT_ALL_RECORDS_TO_PDF || option === index.DataExporterOption.EXPORT_ALL_RECORDS_TO_XLS) {
      return IFetchDataExporterParams.IExportType.ALL;
    }
    if (option === index.DataExporterOption.EXPORT_PAGE_TO_PDF || option === index.DataExporterOption.EXPORT_PAGE_TO_XLS) {
      return IFetchDataExporterParams.IExportType.PAGE;
    }
    return IFetchDataExporterParams.IExportType.SELECTION;
  }
  async dispatchExporter(option) {
    var _a, _b, _c;
    const optionKey = this.getOptionKey(option);
    const fileType = (_a = index.DataExporterType[optionKey]) !== null && _a !== void 0 ? _a : index.DataExporterType.EXPORT_TO_PDF;
    const params = {
      methodName: index.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 === index.DataExporterType.EXPORT_TO_PDF) {
        fileViewer(Object.assign(Object.assign({}, response), { fileType }));
      }
      else {
        utils.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 = [index.DataExporterOption.EXPORT_PAGE_TO_PDF, index.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) === index.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 utils.ApplicationUtils.confirm(limitModalMessages.title, limitModalMessages.description, null, utils.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 === index.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(`${constants.REPORT_LAUNCHER_RESOURCE_ID}${appId}`, pkObject);
  }
  parseDataType(type) {
    switch (type) {
      case core.DataType.NUMBER:
        return "I";
      case core.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 {
      [core.ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: core.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 = core.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;
    }
    core.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 (index$1.h(index$1.Host, null, index$1.h("div", { class: `snk-data-exporter
          ${this.canShowDropdown() ? " ez-elevation--16" : ""}
        ` }, index$1.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"))), index$1.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() &&
      index$1.h("ez-dropdown", Object.assign({ items: this._items, onEzClick: (evt) => this.processExporter(evt) }, this.getElementID("dropdown"))))), this.canShowDropdown() &&
      index$1.h("div", Object.assign({ class: "ez-scrim ez-scrim--light" }, this.getElementID("ezScrim"))), index$1.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 index$1.getElement(this); }
};
SnkDataExporter.style = snkDataExporterCss;

exports.snk_data_exporter = SnkDataExporter;
