import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import { ApplicationContext, DataType, Action, UserInterface, StringUtils, DataUnitLoaderUtils, DataUnit } from '@sankhyalabs/core';
import { D as DataFetcher, S as SnkMessageBuilder } from './DataFetcher.js';
import { S as SaveErrorsEnum } from './ISave.js';
import { P as PreloadManager, D as DataUnitFetcher, I as InMemoryLoader } from './dataunit-fetcher.js';
import './filter-item-type.enum.js';
import './form-config-fetcher.js';
import { V as VIEW_MODE } from './constants.js';
import { A as AutorizationType } from './auth-fetcher.js';
import { T as TaskbarElement, d as defineCustomElement$4 } from './snk-taskbar2.js';
import { d as defineCustomElement$f } from './snk-actions-button2.js';
import { d as defineCustomElement$e } from './snk-configurator2.js';
import { d as defineCustomElement$d } from './snk-data-exporter2.js';
import { d as defineCustomElement$c } from './snk-data-unit2.js';
import { d as defineCustomElement$b } from './snk-exporter-email-sender2.js';
import { d as defineCustomElement$a } from './snk-grid-config2.js';
import { d as defineCustomElement$9 } from './snk-layout-form-config2.js';
import { d as defineCustomElement$8 } from './snk-select-box2.js';
import { d as defineCustomElement$7 } from './snk-simple-bar2.js';
import { d as defineCustomElement$6 } from './snk-simple-crud2.js';
import { d as defineCustomElement$5 } from './snk-simple-form-config2.js';
import { d as defineCustomElement$3 } from './snk-view-representation2.js';
import { d as defineCustomElement$2 } from './taskbar-actions-button2.js';
import { d as defineCustomElement$1 } from './taskbar-split-button2.js';

const SERVICE$1 = {
  save: "Attach.save",
  delete: "Attach.remove",
  view: "Attach.view",
  repository: "RepositorioArquivoSP.abreArquivo"
};
class AttachFetcher {
  constructor(dataUnitName) {
    this.dataUnitName = dataUnitName;
  }
  async save({ dataUnit: dataUnitName, record, updatingFields: fields, operation }) {
    var _a, _b;
    const isInsert = operation == "INSERT";
    const dataBody = isInsert ? fields : record;
    if (!isInsert && (fields === null || fields === void 0 ? void 0 : fields.DESCRICAO) && (fields === null || fields === void 0 ? void 0 : fields.DESCRICAO) !== (record === null || record === void 0 ? void 0 : record.DESCRICAO)) {
      throw new Error(SaveErrorsEnum.DESCRIPTION_CANNOT_BE_CHANGED);
    }
    const reqBody = {
      "anexo": {
        "codata": isInsert ? fields === null || fields === void 0 ? void 0 : fields.REGISTER_KEY : record === null || record === void 0 ? void 0 : record.CODATA,
        "sequencia": (dataBody === null || dataBody === void 0 ? void 0 : dataBody.SEQUENCIA) || "0",
        "tipo": (dataBody === null || dataBody === void 0 ? void 0 : dataBody.TIPO) || "N",
        "descricao": dataBody === null || dataBody === void 0 ? void 0 : dataBody.DESCRICAO,
        "arquivo": (_b = (_a = fields.CAMINHO_ARQUIVO) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.name,
        "ehInclusao": isInsert ? "S" : "N",
        "ehArquivoRepositorio": "N"
      }
    };
    return new Promise((resolve, reject) => {
      DataFetcher.get().callServiceBroker(SERVICE$1.save, JSON.stringify(reqBody))
        .then(result => {
        var _a;
        return resolve([Object.assign(Object.assign(Object.assign({}, result), fields), { __owner__dataunit__name__: (_a = this.dataUnitName) !== null && _a !== void 0 ? _a : dataUnitName })]);
      })
        .catch(error => reject(error));
    });
  }
  async edit(change) {
    throw new Error("Method not implemented.");
  }
  async delete(record) {
    var request = {
      anexo: {
        codata: record.CODATA,
        tipo: record.TIPO,
        descricao: record.DESCRICAO,
      }
    };
    const result = await DataFetcher.get().callServiceBroker(SERVICE$1.delete, JSON.stringify(request));
    return Promise.resolve(result);
  }
  async getDownloadKey(record) {
    var _a, _b, _c;
    if (record.EHARQUIVOREPOSITORIO == 'S') {
      const request = {
        config: {
          path: record.ARQUIVO,
          tipoconteudo: record.TIPOCONTEUDO
        }
      };
      const result = await DataFetcher.get().callServiceBroker(SERVICE$1.repository, JSON.stringify(request));
      return Promise.resolve({
        chave: {
          valor: (_b = (_a = result === null || result === void 0 ? void 0 : result.responseBody) === null || _a === void 0 ? void 0 : _a.chave) === null || _b === void 0 ? void 0 : _b.valor
        }
      });
    }
    const criteria = {
      anexo: {
        codata: record.CODATA,
        codemp: record.CODEMP,
        sequencia: record.SEQUENCIA,
        tipo: record.TIPO,
        descricao: record.DESCRICAO,
        tipoConteudo: record.TIPOCONTEUDO
      }
    };
    const result = await DataFetcher.get().callServiceBroker(SERVICE$1.view, JSON.stringify(criteria));
    if (result === null || result === void 0 ? void 0 : result.chaveAnexo) {
      return Promise.resolve({
        chave: {
          valor: (_c = result === null || result === void 0 ? void 0 : result.chaveAnexo) === null || _c === void 0 ? void 0 : _c.idChaveAnexo
        }
      });
    }
    return Promise.reject(new Error("File not found."));
  }
}

const SERVICE = {
  save: "AnexoSistemaSP.salvar",
  delete: "AnexoSistemaSP.excluir",
  download: "AnexoSistemaSP.baixar",
};
class AnexoSistemaFetcher {
  constructor(entityName, dataUnitName) {
    var _a;
    this.entityName = entityName;
    this.dataUnitName = dataUnitName;
    this.validateFields = (fields) => {
      if (!!fields.LINK && !!fields.NOMEARQUIVO)
        throw new Error(SaveErrorsEnum.LINK_AND_FILE_AT_THE_SAME_TIME);
      if (!fields.LINK && !fields.NOMEARQUIVO)
        throw new Error(SaveErrorsEnum.ANY_LINK_OR_FILE_FILLED);
      if (!this._registerKey)
        throw new Error('Register key can not be null');
    };
    this.resourceID = (window["resourceID"] || ((_a = window["workspace"]) === null || _a === void 0 ? void 0 : _a.resourceID));
  }
  set registerKey(registerKey) {
    this._registerKey = registerKey;
  }
  async save(change) {
    var _a, _b;
    let { updatingFields: fields } = change;
    fields = Object.assign(Object.assign({}, fields), { NOMEARQUIVO: (_a = fields.NOMEARQUIVO) === null || _a === void 0 ? void 0 : _a[0] });
    try {
      this.validateFields(fields);
      const fileInfo = !fields.LINK ? fields.NOMEARQUIVO : null;
      const reqBody = {
        serviceName: SERVICE.save,
        requestBody: {
          params: {
            resourceID: this.resourceID,
            description: fields.DESCRICAO,
            fileSelect: fileInfo ? 1 : 0,
            keySession: (_b = fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.properties) === null || _b === void 0 ? void 0 : _b.fileNameTmp,
            nameAttach: fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.name,
            link: fields.LINK,
            nameEntity: this.entityName,
            pkEntity: this._registerKey,
            typeAcess: fields.TIPOACESSO,
            typeApres: fields.TIPOAPRES,
          }
        }
      };
      const result = await DataFetcher.get().callServiceBroker(SERVICE.save, JSON.stringify(reqBody));
      return Promise.resolve([Object.assign(Object.assign(Object.assign({}, result), fields), { ARQUIVOOULINK: !!fields.LINK ? fields.LINK : fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.name, __owner__dataunit__name__: this.dataUnitName })]);
    }
    catch (error) {
      return Promise.reject(error);
    }
  }
  async edit(change) {
    var _a, _b, _c;
    let { updatingFields: fields, record } = change;
    const getFieldValue = (fieldValue) => {
      if (fields[fieldValue] !== undefined)
        return fields[fieldValue];
      return record[fieldValue];
    };
    const attachField = getFieldValue('NOMEARQUIVO');
    const hasNewAttachment = (_b = (_a = fields.NOMEARQUIVO) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.downloadURL;
    fields = Object.assign(Object.assign({}, fields), { DESCRICAO: getFieldValue('DESCRICAO'), LINK: getFieldValue('LINK'), TIPOACESSO: getFieldValue('TIPOACESSO'), TIPOAPRES: getFieldValue('TIPOAPRES'), CHAVEARQUIVO: record.CHAVEARQUIVO, NOMEARQUIVO: attachField === null || attachField === void 0 ? void 0 : attachField[0] });
    const fileInfo = !fields.LINK ? fields.NOMEARQUIVO : null;
    try {
      this.validateFields(fields);
      const reqBody = {
        serviceName: SERVICE.save,
        requestBody: {
          params: {
            resourceID: this.resourceID,
            nuAttach: record === null || record === void 0 ? void 0 : record.NUATTACH,
            description: fields.DESCRICAO,
            fileSelect: hasNewAttachment ? 1 : 0,
            keySession: (_c = fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.properties) === null || _c === void 0 ? void 0 : _c.fileNameTmp,
            keyAttach: fields.CHAVEARQUIVO,
            nameAttach: fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.name,
            link: fields.LINK,
            nameEntity: this.entityName,
            pkEntity: this._registerKey,
            typeAcess: fields.TIPOACESSO,
            typeApres: fields.TIPOAPRES,
          }
        }
      };
      const result = await DataFetcher.get().callServiceBroker(SERVICE.save, JSON.stringify(reqBody));
      return Promise.resolve([Object.assign(Object.assign(Object.assign({}, result), fields), { ARQUIVOOULINK: !!fields.LINK ? fields.LINK : fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.name, __owner__dataunit__name__: this.dataUnitName })]);
    }
    catch (error) {
      return Promise.reject(error);
    }
  }
  delete(record) {
    var _a;
    const attachField = ((_a = record.NOMEARQUIVO) === null || _a === void 0 ? void 0 : _a[0]) || {};
    const reqBody = {
      serviceName: SERVICE.delete,
      requestBody: {
        paramsDelete: {
          keyAttach: record.CHAVEARQUIVO,
          nameAttach: attachField === null || attachField === void 0 ? void 0 : attachField.name,
          nameEntity: record.NOMEINSTANCIA,
          nuAttach: record.NUATTACH,
          pkEntity: record.PKREGISTRO
        }
      }
    };
    return new Promise((resolve, reject) => {
      DataFetcher.get().callServiceBroker(SERVICE.delete, JSON.stringify(reqBody))
        .then(result => resolve(result))
        .catch(error => reject(error));
    });
  }
  getDownloadKey(record) {
    var _a;
    const attachField = ((_a = record.NOMEARQUIVO) === null || _a === void 0 ? void 0 : _a[0]) || {};
    const reqBody = {
      serviceName: SERVICE.download,
      requestBody: {
        paramsDown: {
          nameAttach: attachField === null || attachField === void 0 ? void 0 : attachField.name,
          nameEntity: record.NOMEINSTANCIA,
          nuAttach: record.NUATTACH,
          pkEntity: record.PKREGISTRO,
          keyAttach: record.CHAVEARQUIVO,
        }
      }
    };
    return new Promise((resolve, reject) => {
      DataFetcher.get().callServiceBroker(SERVICE.download, JSON.stringify(reqBody))
        .then(result => resolve(result))
        .catch(error => reject(error));
    });
  }
}

class AnexoSistemaDataUnitFactory {
  constructor(entityName, getMessage) {
    this.entityName = entityName;
    this.getMessage = getMessage;
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
  }
  initLoaders(dataUnit, fetcher, onSuccess) {
    if (!this.loader)
      this.loader = dataUnit.dataLoader;
    dataUnit.dataLoader = (dataUnit, request) => this.dataLoader(dataUnit, request);
    dataUnit.saveLoader = (_, changes) => this.saveLoader(changes, fetcher).then((recordIds) => {
      if (recordIds.length)
        onSuccess();
      return recordIds;
    });
    dataUnit.removeLoader = (dataUnit, ids) => this.removeLoader(dataUnit, ids, fetcher).then((recordIds) => {
      if (recordIds.length)
        onSuccess();
      return recordIds;
    });
  }
  metadataLoader(dataUnit) {
    throw new Error("Method not implemented.");
  }
  dataLoader(dataUnit, request) {
    return new Promise(resolve => {
      this.loader(dataUnit, request).then(response => {
        const records = ((response === null || response === void 0 ? void 0 : response.records) || []).map(record => {
          let fileInfo;
          if (!record.LINK)
            fileInfo = [{
                name: record.NOMEARQUIVO,
              }];
          return Object.assign(Object.assign({}, record), { ARQUIVOOULINK: !!record.LINK ? record.LINK : record.NOMEARQUIVO, NOMEARQUIVO: fileInfo });
        });
        resolve(Object.assign(Object.assign({}, response), { records }));
      });
    });
  }
  saveLoader(changes, fetcher) {
    return new Promise((resolve) => {
      var _a;
      const change = Array.isArray(changes) ? changes[0] : {};
      const savePromise = ((_a = change === null || change === void 0 ? void 0 : change.record) === null || _a === void 0 ? void 0 : _a.NUATTACH) >= 0 ? fetcher.edit.bind(fetcher) : fetcher.save.bind(fetcher);
      savePromise(change).then((records) => {
        resolve(records);
      }).catch((error) => {
        if (error.message === SaveErrorsEnum.LINK_AND_FILE_AT_THE_SAME_TIME) {
          this._application.alert(this.getMessage('snkAttach.alertValidation.fileAndLinkAtTheSameTime.title'), this.getMessage('snkAttach.alertValidation.fileAndLinkAtTheSameTime.message'));
          return resolve([]);
        }
        if (error.message === SaveErrorsEnum.ANY_LINK_OR_FILE_FILLED) {
          this._application.alert(this.getMessage('snkAttach.alertValidation.anyLinkOrFileFilled.title'), this.getMessage('snkAttach.alertValidation.anyLinkOrFileFilled.message'));
          return resolve([]);
        }
        if (error.message) {
          this._application.error((error.title || error.name), error.message);
          return resolve([]);
        }
        resolve([]);
      });
    });
  }
  removeLoader(dataUnit, ids, fetcher) {
    return new Promise((resolve) => {
      const { records } = dataUnit.getSelectionInfo();
      const recordToDelete = records[0];
      fetcher.delete(recordToDelete).then(() => {
        PreloadManager.removeRecords(dataUnit, [recordToDelete]);
        return resolve(ids);
      });
    });
  }
  getFilters(registerKey) {
    return [
      {
        name: 'AttachmentsByPK',
        expression: 'this.PKREGISTRO = :PKREGISTRO',
        params: [{
            name: "PKREGISTRO",
            dataType: DataType.TEXT,
            value: `${registerKey}_${this.entityName}`
          }]
      }
    ];
  }
  getInterceptions(dataUnit, action, crudRef) {
    return new Promise((resolve) => {
      if (action.type === Action.EDITION_CANCELED) {
        if (!dataUnit.isDirty())
          return resolve(action);
        return this._application.confirm(this.getMessage('snkAttach.cancelConfirmation.title'), this.getMessage('snkAttach.cancelConfirmation.message')).then((cancellationConfirmed) => {
          if (cancellationConfirmed) {
            crudRef.goToView(VIEW_MODE.GRID);
            return resolve(action);
          }
          return resolve(undefined);
        });
      }
      if (action.type === Action.DATA_SAVED) {
        dataUnit.loadData();
        return resolve(action);
      }
      resolve(action);
    });
  }
}

let messageBuilderInstance;
const getMessage$1 = (key) => {
  if (!messageBuilderInstance) {
    messageBuilderInstance = new SnkMessageBuilder();
  }
  return messageBuilderInstance.getMessage(key);
};
const attachCrudConfig = {
  grid: {
    columns: [
      { name: "CODATA", orderIndex: 0, width: 0 },
      { name: "DESCRICAO", orderIndex: 1, width: 0 },
      { name: "ARQUIVO", orderIndex: 2, width: 0 },
      { name: "DTALTER", orderIndex: 3, width: 0 },
      { name: "USUARIO", orderIndex: 4, width: 0 },
    ],
  },
  form: {
    emptyConfig: false,
    fields: [
      {
        name: "DESCRICAO",
        label: getMessage$1("snkAttach.attachMetadata.lblDescription"),
        visible: true,
        readOnly: false,
        required: true,
      },
      {
        name: "CAMINHO_ARQUIVO",
        label: getMessage$1("snkAttach.attachMetadata.lblFile"),
        visible: true,
        readOnly: false,
        required: true,
      },
    ],
  },
};
const attachFetcherMetadataBuilder = {
  name: "Attach",
  label: "Attach List",
  fields: [
    { name: "CODATA", label: getMessage$1("snkAttach.attachMetadata.lblCode"), dataType: DataType.TEXT },
    { name: "DESCRICAO", label: getMessage$1("snkAttach.attachMetadata.lblDescription"), dataType: DataType.TEXT, readOnly: false },
    { name: "ARQUIVO", label: getMessage$1("snkAttach.attachMetadata.lblFileOrLink"), dataType: DataType.TEXT },
    { name: "USUARIO", label: getMessage$1("snkAttach.attachMetadata.lblUser"), dataType: DataType.TEXT },
    { name: "DTALTER", label: getMessage$1("snkAttach.attachMetadata.lblDate"), dataType: DataType.TEXT },
    {
      name: "CAMINHO_ARQUIVO",
      label: getMessage$1("snkAttach.attachMetadata.lblFileUpload"),
      dataType: DataType.OBJECT,
      userInterface: UserInterface.FILE,
      readOnly: false,
      required: true,
      visible: true,
      properties: {
        subTitle: getMessage$1("snkAttach.attachMetadata.lblSubTitle"),
        MAX_FILES: 1,
        STORAGESTRATEGY: "SESSION",
        INTERNAL_FILENAME: "Attach.upload",
      }
    },
  ],
};

const SERVICE_LOAD = "Attach.load";
class AttachFetcherDataUnitFactory {
  constructor(getMessage) {
    this.getMessage = getMessage;
    this._records = [];
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
  }
  initLoaders(dataUnit, fetcher, onSuccess) {
    dataUnit.metadataLoader = (dataUnit) => this.metadataLoader(dataUnit);
    dataUnit.dataLoader = (dataUnit, request) => this.dataLoader(dataUnit, request);
    dataUnit.saveLoader = (_, changes) => this.saveLoader(changes, fetcher).then((recordIds) => {
      if (recordIds.length)
        onSuccess();
      return recordIds;
    });
    dataUnit.removeLoader = (dataUnit, ids) => this.removeLoader(dataUnit, ids, fetcher).then((recordIds) => {
      if (recordIds.length)
        onSuccess();
      return recordIds;
    });
  }
  metadataLoader(_) {
    return Promise.resolve(attachFetcherMetadataBuilder);
  }
  async dataLoader(dataUnit, request) {
    if (!request.source) {
      return Promise.resolve({ records: this._records });
    }
    if (!Number.isNaN(Number(request.source))) {
      const criteria = {
        criteria: {
          codata: request.source,
          tipoAnexo: "N"
        }
      };
      const applicationDataFetcher = await this._application.getDataFetcher();
      const { anexos: { anexo = [] } } = await applicationDataFetcher.callServiceBroker(SERVICE_LOAD, JSON.stringify(criteria));
      const records = [];
      anexo.forEach((param) => {
        records.push(Object.assign({ __record__id__: StringUtils.generateUUID(), CAMINHO_ARQUIVO: [{
              name: param === null || param === void 0 ? void 0 : param.ARQUIVO,
            }] }, param));
      });
      this._records = records;
    }
    return DataUnitLoaderUtils.buildLoadDataResponse(this._records, dataUnit, request);
  }
  saveLoader(changes, fetcher) {
    return new Promise((resolve) => {
      const change = Array.isArray(changes) ? changes[0] : {};
      fetcher.save(change)
        .then(resolve)
        .catch((error) => {
        if (error.message === SaveErrorsEnum.DESCRIPTION_CANNOT_BE_CHANGED) {
          this._application.alert(this.getMessage('snkAttach.alertValidation.descriptionCannotBeChanged.title'), this.getMessage('snkAttach.alertValidation.descriptionCannotBeChanged.message'));
          return resolve([]);
        }
        if (error.message === SaveErrorsEnum.LINK_AND_FILE_AT_THE_SAME_TIME) {
          this._application.alert(this.getMessage('snkAttach.alertValidation.fileAndLinkAtTheSameTime.title'), this.getMessage('snkAttach.alertValidation.fileAndLinkAtTheSameTime.message'));
          return resolve([]);
        }
        if (error.message === SaveErrorsEnum.ANY_LINK_OR_FILE_FILLED) {
          this._application.alert(this.getMessage('snkAttach.alertValidation.anyLinkOrFileFilled.title'), this.getMessage('snkAttach.alertValidation.anyLinkOrFileFilled.message'));
          return resolve([]);
        }
        if (error.message) {
          this._application.error((error.title || error.name), error.message);
          return resolve([]);
        }
        resolve([]);
      });
    });
  }
  removeLoader(dataUnit, ids, fetcher) {
    return new Promise((resolve) => {
      dataUnit.getSelectionInfo().records.forEach(async (record) => {
        this._application.hasAccess(AutorizationType.REMOVE)
          .then(async (hasAccess) => {
          if (hasAccess) {
            await fetcher.delete(record);
            resolve(ids);
          }
        });
      });
    });
  }
  getFilters() {
    throw new Error('Method not implemented.');
  }
  getInterceptions(dataUnit, action, crudRef) {
    return new Promise((resolve) => {
      var _a, _b, _c, _d, _e, _f;
      switch (action.type) {
        case Action.EDITION_CANCELED:
          if (!dataUnit.isDirty())
            return resolve(action);
          return this._application.confirm(this.getMessage('snkAttach.cancelConfirmation.title'), this.getMessage('snkAttach.cancelConfirmation.message')).then((cancellationConfirmed) => {
            if (cancellationConfirmed) {
              crudRef.goToView(VIEW_MODE.GRID);
              return resolve(action);
            }
            return resolve(undefined);
          });
        case Action.DATA_SAVED:
          dataUnit.loadData(undefined, undefined, false, (_c = (_b = (_a = action === null || action === void 0 ? void 0 : action.payload) === null || _a === void 0 ? void 0 : _a.records) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.REGISTER_KEY);
          return resolve(action);
        case Action.RECORDS_REMOVED:
          dataUnit.loadData(undefined, undefined, false, (_f = (_e = (_d = action === null || action === void 0 ? void 0 : action.payload) === null || _d === void 0 ? void 0 : _d.cachedRecords) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.CODATA);
          return resolve(action);
      }
      resolve(action);
    });
  }
}

let messagesBuilder;
const getMessage = (key) => {
  var _a;
  if (!messagesBuilder) {
    const application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    messagesBuilder = application === null || application === void 0 ? void 0 : application.messagesBuilder;
  }
  return (_a = messagesBuilder === null || messagesBuilder === void 0 ? void 0 : messagesBuilder.getMessage) === null || _a === void 0 ? void 0 : _a.call(messagesBuilder, key, null);
};
const TaskbarAttachButtons = {
  DOWNLOAD: {
    hint: getMessage("snkAttach.taskbar.titleDownload"),
    name: "DOWNLOAD",
    iconName: 'file-download'
  },
  LINK: {
    hint: getMessage("snkAttach.taskbar.titleLink"),
    name: "LINK",
    iconName: "launch"
  }
};
const buildTaskBarManager = () => {
  const disabledButtonsWithoutSelection = [
    TaskbarElement.REMOVE,
    "DOWNLOAD",
    "LINK"
  ];
  return {
    getButtons: (_, dataState, currentButtons) => {
      const refreshBtnIndex = currentButtons.indexOf(TaskbarElement.REFRESH);
      if ((dataState === null || dataState === void 0 ? void 0 : dataState.insertionMode) || (dataState === null || dataState === void 0 ? void 0 : dataState.isDirty)) {
        return currentButtons.reverse();
      }
      else if (refreshBtnIndex !== -1) {
        currentButtons.splice(refreshBtnIndex, 1);
      }
      const { selectedRecord } = dataState || {};
      const taskbarTobeAdded = !!(selectedRecord === null || selectedRecord === void 0 ? void 0 : selectedRecord.LINK) ? TaskbarAttachButtons.LINK : TaskbarAttachButtons.DOWNLOAD;
      currentButtons.splice(currentButtons.indexOf(TaskbarElement.DIVIDER) + 1, 0, TaskbarElement.REMOVE, taskbarTobeAdded, TaskbarElement.DIVIDER);
      const buttonsToRemove = [TaskbarElement.CLONE, TaskbarElement.DATA_EXPORTER];
      const updatedButtons = Array.from(new Set(currentButtons.filter((button) => !buttonsToRemove.includes(button))));
      updatedButtons.splice(updatedButtons.indexOf(taskbarTobeAdded) + 1, 0, TaskbarElement.DIVIDER);
      return updatedButtons;
    },
    isEnabled: (_, dataState, currentButton) => {
      const hasSelectedRecord = (dataState === null || dataState === void 0 ? void 0 : dataState.selectedRecord) !== undefined;
      const disabledButton = disabledButtonsWithoutSelection.includes(currentButton);
      if (disabledButton && !hasSelectedRecord)
        return false;
      return true;
    }
  };
};

const anexoSistemaCrudConfig = {
  grid: {
    columns: [
      { name: "ARQUIVOOULINK", orderIndex: 0, width: 0 },
      { name: "DESCRICAO", orderIndex: 1, width: 0 },
      { name: "DHCAD", orderIndex: 2, width: 0 },
      { name: "DHALTER", orderIndex: 3, width: 0 },
      { name: "TIPOAPRES", orderIndex: 4, width: 0 },
      { name: "TIPOACESSO", orderIndex: 5, width: 0 },
      { name: "CODUSU", orderIndex: 6, width: 0 },
      { name: "CODUSUALT", orderIndex: 7, width: 0 }
    ]
  },
  form: {
    emptyConfig: false,
    fields: [
      {
        name: "DESCRICAO",
        required: true
      },
      {
        name: "TIPOAPRES",
        required: true,
      },
      {
        name: "TIPOACESSO",
        required: true,
      },
      {
        name: "LINK"
      },
      {
        name: "NOMEARQUIVO"
      }
    ]
  },
};

const snkAttachCss = ".snk-attach__header.sc-snk-attach,.snk-attach__crud-section.sc-snk-attach{padding:0 var(--space--lg)}.snk-attach__file-info.sc-snk-attach{padding:var(--space--small);max-width:50%}.snk-attach__main.sc-snk-attach{height:85%}.ez-box__container.sc-snk-attach{height:100%}";

const RESOURCE_ID = 'AnexoSistema';
const DATA_UNIT_NAME = 'br.com.sankhya.core.v3.anexoSistema';
const GRID_LEGACY_CONFIG_NAME = 'GrdCfgHtml5:grdcfg.dynaform.anexo';
const LINKORFILE_COLUMN_NAME = "ARQUIVOOULINK";
const SnkAttach = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.back = createEvent(this, "back", 7);
    this.handleTaskbarClick = async ({ detail: taskbar }) => {
      if (["DOWNLOAD", "LINK"].includes(taskbar))
        return this.downloadAttachment(this._currentDataUnit.getSelectedRecord());
      if (this.fetcherType === "Attach" && ["SAVE"].includes(taskbar) && this._currentDataUnit.isDirty()) {
        await this._currentDataUnit.setFieldValue("REGISTER_KEY", this.registerKey);
      }
    };
    this.handleBack = () => {
      this._currentDataUnit.cancelEdition().then((cancelationConfirmed) => {
        if (cancelationConfirmed)
          this.back.emit();
      });
    };
    this.handleFinish = () => {
      if (!this._currentDataUnit.isDirty())
        return this.back.emit();
      if (!this.validateAnexoSistema()) {
        return;
      }
      this._currentDataUnit.saveData().then(() => {
        this.showFinishedToast();
        this.back.emit();
      });
    };
    this.gridLegacyConfigName = undefined;
    this.fetcherType = undefined;
    this.fetcher = undefined;
    this.dataUnit = undefined;
    this.dataUnitBuilder = undefined;
    this.registerKey = undefined;
    this.entityName = undefined;
    this.messagesBuilder = undefined;
    this._currentFetcher = undefined;
    this._currentDataUnit = undefined;
    this.crudConfig = undefined;
    this._appResourceID = undefined;
  }
  async registerKeyWatcher(newRegisterKey, oldRegisterKey) {
    var _a;
    if (this._currentDataUnit == null) {
      this.loadAttachmentDataUnit();
    }
    if (oldRegisterKey !== newRegisterKey) {
      if (this._currentFetcher instanceof AnexoSistemaFetcher) {
        this._currentFetcher.registerKey = newRegisterKey;
      }
      await ((_a = this._currentDataUnit) === null || _a === void 0 ? void 0 : _a.loadData());
    }
  }
  getAnexoSistemaFetcherInstance() {
    var _a;
    const anexoSistemaFetcher = new AnexoSistemaFetcher(this.entityName, (_a = this._currentDataUnit) === null || _a === void 0 ? void 0 : _a.name);
    anexoSistemaFetcher.registerKey = this.registerKey;
    return anexoSistemaFetcher;
  }
  async initAttach() {
    var _a, _b, _c, _d, _e;
    if (!this.fetcherType && !this.registerKey)
      return;
    if (!this.fetcherType) {
      this.fetcherType = "AnexoSistema";
    }
    this.returnToGridMode();
    if (this.fetcherType === "AnexoSistema") {
      this._currentFetcher = this.getAnexoSistemaFetcherInstance();
      (_a = this._currentDataUnitBuilder) === null || _a === void 0 ? void 0 : _a.initLoaders(this._currentDataUnit, this._currentFetcher, this.returnToGridMode.bind(this));
      await ((_b = this._currentDataUnit) === null || _b === void 0 ? void 0 : _b.loadData());
      return;
    }
    if (this.fetcherType === "Attach") {
      const hasMoreOneItem = ((_c = this.registerKey) === null || _c === void 0 ? void 0 : _c.split("_").length) > 1;
      if (hasMoreOneItem)
        return;
    }
    await ((_d = this._currentDataUnit) === null || _d === void 0 ? void 0 : _d.loadMetadata());
    await ((_e = this._currentDataUnit) === null || _e === void 0 ? void 0 : _e.loadData(undefined, undefined, true, this.registerKey));
  }
  /**
   * 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-attach.msg.ts"
  */
  getMessage(key, params) {
    if (this.messagesBuilder)
      return this.messagesBuilder.getMessage(key, params);
  }
  showFinishedToast() {
    this._application.info(this.getMessage('snkAttach.finishedMessage'), { iconName: "check" });
  }
  downloadAttachment(selectedRecord) {
    if (!selectedRecord)
      throw new Error(this.getMessage("snkAttach.alertValidation.noRecordSelected.message"));
    if (selectedRecord.LINK) {
      window.open(`${selectedRecord.LINK}`);
      return;
    }
    this._currentFetcher
      .getDownloadKey(selectedRecord)
      .then(({ chave }) => {
      var _a;
      let forceDownload = false;
      if (!((_a = selectedRecord === null || selectedRecord === void 0 ? void 0 : selectedRecord.ARQUIVO) === null || _a === void 0 ? void 0 : _a.endsWith(".pdf"))) {
        forceDownload = true;
      }
      window.open(`/mge/visualizadorArquivos.mge?chaveArquivo=${chave.valor}${forceDownload ? "&forcarDownload=S" : ""}`);
    });
  }
  returnToGridMode() {
    var _a;
    (_a = this._currentDataUnit) === null || _a === void 0 ? void 0 : _a.clearSelection();
    if (this._crudElement)
      this._crudElement.goToView(VIEW_MODE.GRID);
  }
  async loadAttachmentDataUnit() {
    try {
      switch (this.fetcherType) {
        case "AnexoSistema":
          await this.loadAnexoSistema();
          break;
        case "Attach":
          await this.loadAttach();
          break;
        default:
          this._currentFetcher = this.fetcher;
          this._currentDataUnit = this.dataUnit;
          this._currentDataUnitBuilder = this.dataUnitBuilder;
      }
    }
    catch (error) {
      throw new Error('There was an error while creating the data unit');
    }
  }
  async loadAnexoSistema() {
    var _a, _b;
    this._currentDataUnit = new DataUnitFetcher().getDataUnit(RESOURCE_ID, DATA_UNIT_NAME);
    this._currentFetcher = this.getAnexoSistemaFetcherInstance();
    let gridValidateForm;
    if (!this._currentDataUnit.metadata) {
      await ((_a = this._currentDataUnit) === null || _a === void 0 ? void 0 : _a.loadMetadata());
      this.crudConfig = this.entityName ? { form: anexoSistemaCrudConfig === null || anexoSistemaCrudConfig === void 0 ? void 0 : anexoSistemaCrudConfig.form } : Object.assign({}, anexoSistemaCrudConfig);
      gridValidateForm = { grid: anexoSistemaCrudConfig === null || anexoSistemaCrudConfig === void 0 ? void 0 : anexoSistemaCrudConfig.grid };
    }
    this.initDataUnitLoaders();
    this._currentDataUnit.addFilterProvider({
      getFilter: () => this._currentDataUnitBuilder.getFilters(this.registerKey)
    });
    this._currentDataUnit.addInterceptor({
      interceptAction: (action) => this._currentDataUnitBuilder.getInterceptions(this._currentDataUnit, action, this._crudElement)
    });
    await ((_b = this._currentDataUnit) === null || _b === void 0 ? void 0 : _b.loadData());
    this.disableEditFieldsNotInForm(gridValidateForm);
  }
  async loadAttach() {
    var _a, _b;
    this._currentFetcher = new AttachFetcher();
    this._currentDataUnit = new DataUnit(InMemoryLoader.IN_MEMORY_DATA_UNIT_NAME);
    this._currentDataUnit.pageSize = 150;
    let gridValidateForm;
    this.initDataUnitLoaders();
    this._currentDataUnit.addInterceptor({
      interceptAction: (action) => {
        var _a;
        if (action.type === Action.METADATA_LOADED) {
          this.crudConfig = this.entityName ? { form: attachCrudConfig === null || attachCrudConfig === void 0 ? void 0 : attachCrudConfig.form } : Object.assign({}, attachCrudConfig);
          gridValidateForm = { grid: attachCrudConfig === null || attachCrudConfig === void 0 ? void 0 : attachCrudConfig.grid };
          (_a = this._crudElement) === null || _a === void 0 ? void 0 : _a.updateConfig();
        }
        return this._currentDataUnitBuilder.getInterceptions(this._currentDataUnit, action, this._crudElement);
      }
    });
    if (!this._currentDataUnit.metadata) {
      await ((_a = this._currentDataUnit) === null || _a === void 0 ? void 0 : _a.loadMetadata());
      this.crudConfig = this.entityName ? { form: attachCrudConfig === null || attachCrudConfig === void 0 ? void 0 : attachCrudConfig.form } : Object.assign({}, attachCrudConfig);
      gridValidateForm = { grid: attachCrudConfig === null || attachCrudConfig === void 0 ? void 0 : attachCrudConfig.grid };
      await ((_b = this._currentDataUnit) === null || _b === void 0 ? void 0 : _b.loadData(undefined, undefined, true, this.registerKey));
      this.disableEditFieldsNotInForm(gridValidateForm);
    }
  }
  initDataUnitLoaders() {
    var _a, _b;
    if (this.fetcherType === "AnexoSistema") {
      this._currentFetcher = this.getAnexoSistemaFetcherInstance();
      this._currentDataUnitBuilder = new AnexoSistemaDataUnitFactory(this.entityName, this.getMessage.bind(this));
      (_a = this._currentDataUnitBuilder) === null || _a === void 0 ? void 0 : _a.initLoaders(this._currentDataUnit, this._currentFetcher, this.returnToGridMode.bind(this));
    }
    if (this.fetcherType === "Attach") {
      this._currentFetcher = new AttachFetcher();
      this._currentDataUnitBuilder = new AttachFetcherDataUnitFactory(this.getMessage.bind(this));
      (_b = this._currentDataUnitBuilder) === null || _b === void 0 ? void 0 : _b.initLoaders(this._currentDataUnit, this._currentFetcher, async () => {
        this.returnToGridMode();
        await this._currentDataUnit.loadData(undefined, undefined, true, this.registerKey);
      });
    }
  }
  disableEditFieldsNotInForm(gridValidateForm) {
    var _a, _b, _c, _d, _e;
    const gridColumns = ((_b = (_a = this._crudElement) === null || _a === void 0 ? void 0 : _a.gridConfig) === null || _b === void 0 ? void 0 : _b.columns) || ((_c = gridValidateForm === null || gridValidateForm === void 0 ? void 0 : gridValidateForm.grid) === null || _c === void 0 ? void 0 : _c.columns) || ((_e = (_d = this.crudConfig) === null || _d === void 0 ? void 0 : _d.grid) === null || _e === void 0 ? void 0 : _e.columns);
    if (!!this.getGridLegacyConfigName()) {
      this._currentDataUnit.disableField(LINKORFILE_COLUMN_NAME);
    }
    gridColumns === null || gridColumns === void 0 ? void 0 : gridColumns.forEach(column => {
      var _a, _b;
      const fieldName = column.name;
      if (!((_b = (_a = this.crudConfig) === null || _a === void 0 ? void 0 : _a.form) === null || _b === void 0 ? void 0 : _b.fields.some(field => (field === null || field === void 0 ? void 0 : field.name) === fieldName))) {
        this._currentDataUnit.disableField(fieldName);
      }
    });
  }
  validateAnexoSistema() {
    var _a;
    if (this._currentFetcher instanceof AnexoSistemaFetcher) {
      try {
        let fields = this._currentDataUnit.getSelectedRecord();
        fields = Object.assign(Object.assign({}, fields), { NOMEARQUIVO: (_a = fields.NOMEARQUIVO) === null || _a === void 0 ? void 0 : _a[0] });
        this._currentFetcher.validateFields(fields);
      }
      catch (error) {
        if (error.message === SaveErrorsEnum.LINK_AND_FILE_AT_THE_SAME_TIME) {
          this._application.alert(this.getMessage('snkAttach.alertValidation.fileAndLinkAtTheSameTime.title'), this.getMessage('snkAttach.alertValidation.fileAndLinkAtTheSameTime.message'));
          return false;
        }
        if (error.message === SaveErrorsEnum.ANY_LINK_OR_FILE_FILLED) {
          this._application.alert(this.getMessage('snkAttach.alertValidation.anyLinkOrFileFilled.title'), this.getMessage('snkAttach.alertValidation.anyLinkOrFileFilled.message'));
          return false;
        }
      }
    }
    return true;
  }
  async componentWillLoad() {
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    if (this._application) {
      this._appResourceID = await this._application.getResourceID();
    }
    await this.initAttach();
  }
  componentWillRender() {
    if (!this.fetcherType) {
      this.fetcherType = "AnexoSistema";
    }
    if (this._currentDataUnit == null) {
      this.loadAttachmentDataUnit();
    }
  }
  async handleOnDataStateChange({ detail }) {
    if (this.fetcherType !== 'Attach')
      return;
    if (!detail.insertionMode) {
      this._currentDataUnit.disableField('DESCRICAO');
    }
    else {
      this._currentDataUnit.enableField('DESCRICAO');
    }
    await this._currentDataUnit.loadMetadata();
  }
  ;
  isScreenVariation() {
    var _a;
    return !!((_a = this._appResourceID) === null || _a === void 0 ? void 0 : _a.includes('__'));
  }
  getGridLegacyConfigName() {
    if (this.isScreenVariation()) {
      return undefined;
    }
    if (this.gridLegacyConfigName)
      return this.gridLegacyConfigName;
    return this.entityName ? GRID_LEGACY_CONFIG_NAME + "." + this.entityName : this.entityName;
  }
  render() {
    var _a, _b;
    if (!this._currentDataUnit)
      return null;
    return (h("main", { class: "snk-attach__main" }, h("header", { class: "snk-attach__header" }, h("snk-simple-bar", { onExit: this.handleBack, messagesBuilder: this.messagesBuilder }, h("div", { slot: "rightSlot" }, h("ez-button", { class: "ez-button--primary", label: this.getMessage("snkAttach.finish"), onClick: this.handleFinish })))), h("div", { class: "snk-attach__crud-section ez-size-height--full ez-size-width--full ez-flex ez-flex--column" }, h("div", { class: "ez-box__container" }, h("snk-simple-crud", { ref: (el) => this._crudElement = el, dataUnit: this._currentDataUnit, taskbarManager: buildTaskBarManager(), gridConfig: (_a = this.crudConfig) === null || _a === void 0 ? void 0 : _a.grid, formConfig: (_b = this.crudConfig) === null || _b === void 0 ? void 0 : _b.form, useCancelConfirm: false, onActionClick: this.handleTaskbarClick, messagesBuilder: this.messagesBuilder, onDataStateChange: this.handleOnDataStateChange.bind(this), multipleSelection: true, configName: this.isScreenVariation() ? undefined : (this.entityName ? "AnexoSistema_" + this.entityName : undefined), gridLegacyConfigName: this.getGridLegacyConfigName(), ignoreReadOnlyFormFields: this.entityName ? true : false }, h("div", { slot: "snkSimpleCrudHeader" }, h("div", { class: "ez-flex ez-flex--column" }, h("span", { class: "ez-title--primary ez-text ez-text--large ez-text--bold ez-padding-bottom--medium" }, this.getMessage("snkAttach.title")), h("span", { class: "ez-text ez-text--medium ez-text--secondary ez-padding-bottom--medium" }, this.getMessage("snkAttach.description")))))))));
  }
  static get watchers() { return {
    "registerKey": ["registerKeyWatcher"]
  }; }
  static get style() { return snkAttachCss; }
}, [2, "snk-attach", {
    "gridLegacyConfigName": [1, "grid-legacy-config-name"],
    "fetcherType": [1025, "fetcher-type"],
    "fetcher": [16],
    "dataUnit": [16],
    "dataUnitBuilder": [16],
    "registerKey": [1, "register-key"],
    "entityName": [1, "entity-name"],
    "messagesBuilder": [1040],
    "_currentFetcher": [32],
    "_currentDataUnit": [32],
    "crudConfig": [32],
    "_appResourceID": [32]
  }]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-attach", "snk-actions-button", "snk-configurator", "snk-data-exporter", "snk-data-unit", "snk-exporter-email-sender", "snk-grid-config", "snk-layout-form-config", "snk-select-box", "snk-simple-bar", "snk-simple-crud", "snk-simple-form-config", "snk-taskbar", "snk-view-representation", "taskbar-actions-button", "taskbar-split-button"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-attach":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkAttach);
      }
      break;
    case "snk-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$f();
      }
      break;
    case "snk-configurator":
      if (!customElements.get(tagName)) {
        defineCustomElement$e();
      }
      break;
    case "snk-data-exporter":
      if (!customElements.get(tagName)) {
        defineCustomElement$d();
      }
      break;
    case "snk-data-unit":
      if (!customElements.get(tagName)) {
        defineCustomElement$c();
      }
      break;
    case "snk-exporter-email-sender":
      if (!customElements.get(tagName)) {
        defineCustomElement$b();
      }
      break;
    case "snk-grid-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "snk-layout-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "snk-select-box":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "snk-simple-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "snk-simple-crud":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "snk-simple-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "snk-taskbar":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "snk-view-representation":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "taskbar-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
    case "taskbar-split-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$1();
      }
      break;
  } });
}

export { SnkAttach as S, defineCustomElement as d };
