import { HttpClient, HttpEventType } from '@angular/common/http';
import * as i0 from '@angular/core';
import { inject, Injectable, Component, Input, NgModule } from '@angular/core';
import { ControlContainer, FormGroup, Validators, FormControl, FormArray, NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { TranslateService } from '@ngx-translate/core';
import BigNumber from 'bignumber.js';
import { Subject, of, forkJoin, throwError } from 'rxjs';
import { takeUntil, finalize, catchError } from 'rxjs/operators';
import { dynamicTypeToDynamicStructure, DynamicFormComponent } from '@seniorsistemas/angular-components/dynamic-form';
import { LocaleService } from '@seniorsistemas/angular-components/locale';
import moment from 'moment';

class CustomFieldsService {
    http = inject(HttpClient);
    getCustomFields(domain, service, entity, endpoint) {
        const entityDto = { entityId: { domain_: domain, service_: service, id: entity } };
        return this.http.post(endpoint, entityDto);
    }
    getFileLocationUrl(dto, endpoint) {
        return this.http.post(endpoint, dto);
    }
    uploadTempFile(location, file) {
        return this.http.put(location, file, {
            reportProgress: true,
            observe: 'events',
            headers: { 'Content-Type': file.type },
        });
    }
    requestAccess(objectId, endpoint) {
        return this.http.post(endpoint, { objectId });
    }
    getFile(permanentUrl) {
        return this.http.get(permanentUrl, { responseType: 'blob' });
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: CustomFieldsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: CustomFieldsService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: CustomFieldsService, decorators: [{
            type: Injectable
        }] });

var CustomFieldType;
(function (CustomFieldType) {
    CustomFieldType["String"] = "String";
    CustomFieldType["Boolean"] = "Boolean";
    CustomFieldType["Integer"] = "Integer";
    CustomFieldType["Double"] = "Double";
    CustomFieldType["Date"] = "Date";
    CustomFieldType["DateTime"] = "DateTime";
    CustomFieldType["LocalDateTime"] = "LocalDateTime";
    CustomFieldType["Time"] = "Time";
    CustomFieldType["Money"] = "Money";
    CustomFieldType["Blob"] = "Blob";
    CustomFieldType["Binary"] = "Binary";
    CustomFieldType["Any"] = "Any";
    CustomFieldType["Enum"] = "Enum";
})(CustomFieldType || (CustomFieldType = {}));
const apiTypesToDynamicFormType = (type) => {
    switch (type) {
        case 'String':
        case 'Any':
            return 'string';
        case 'Binary':
            return 'binary';
        case 'Blob':
            return 'blob';
        case 'DateTime':
        case 'Time':
        case 'Date':
        case 'LocalDateTime':
            return 'date';
        case 'Enumeration':
        case 'Enum':
            return 'enum';
        case 'Boolean':
            return 'boolean';
        case 'Money':
        case 'Double':
        case 'Integer':
            return 'legacyNumber';
    }
};

/**
 * @description Componente que carrega e renderiza campos customizados dinamicamente
 * a partir da API de customização de campos do Senior. Realiza chamadas HTTP para
 * obter a configuração dos campos, gera o formulário reativamente via {@link DynamicFormComponent}
 * e implementa {@link ControlValueAccessor} e {@link Validator} para integração completa
 * com formulários Angular.
 *
 * @example
 * ```html
 * <s-custom-fields
 *   formControlName="camposCustomizados"
 *   domain="plataforma"
 *   service="servico"
 *   entity="entidade" />
 * ```
 *
 * @category Inputs
 */
class CustomFieldsComponent {
    customFieldsService = inject(CustomFieldsService);
    localeService = inject(LocaleService);
    sanitizer = inject(DomSanitizer);
    translateService = inject(TranslateService);
    controlContainer = inject(ControlContainer, { optional: true });
    /** @description Domínio utilizado para buscar os campos customizados na API. Campo obrigatório. */
    domain;
    /** @description Nome do serviço utilizado para identificar os campos customizados. Campo obrigatório. */
    service;
    /** @description Nome da entidade para a qual os campos customizados são carregados. Campo obrigatório. */
    entity;
    /** @description Mensagem de erro exibida quando algum campo customizado está inválido. @default '' */
    invalidErrorLabel = '';
    /** @description Objeto com dados pré-carregados da entidade, evitando chamadas extras à API. */
    entityObject;
    /** @description Endpoint para buscar a configuração dos campos customizados. */
    customFieldsEndpoint = 'platform/field_customization/queries/getEntity';
    /** @description Endpoint para solicitar o upload de arquivos em campos do tipo blob. */
    fileLocationEndpoint = 'platform/field_customization/actions/requestUpload';
    /** @description Endpoint para solicitar acesso a arquivos já enviados. */
    requestAccessEndpoint = 'platform/field_customization/actions/requestAccess';
    /** @description Mensagem de erro exibida quando um campo obrigatório não está preenchido. @default '' */
    requiredErrorMessage = '';
    /** @description Tempo em ms após o qual o info-sign de campos do tipo data é exibido. @default 0 */
    displayTimeInfoSign = 0;
    /** @description Exibe a data de upload nos campos do tipo arquivo. @default false */
    showFileUploadDate = false;
    /** @description Observable que sinaliza quando o componente deve iniciar o carregamento dos campos. @default null */
    ready$ = null;
    /** @description Quando `true`, todos os campos customizados são desabilitados. */
    disableFields;
    rowType = 'row';
    fields = [];
    formGroup = new FormGroup({});
    dynamicStructure = [];
    ready = false;
    onChange;
    onTouched;
    value;
    ngUsubscribe = new Subject();
    uploadCanceled;
    hasBlob;
    hasUploaded;
    constructor() {
        this.invalidErrorLabel = this.translateService.instant('platform.angular_components.invalid_value');
    }
    get hasCustomFields() {
        return !!this.fields?.length;
    }
    get parentForm() {
        return this.controlContainer.control;
    }
    get parentControl() {
        return this.parentForm.get('custom');
    }
    ngOnInit() {
        this._validateInputs();
        this._createForm();
        this.addDisplayTimeInfoSignToFields();
    }
    ngAfterViewInit() {
        this.enableOrDisableFields(!!this.disableFields);
        this.formGroup.valueChanges.subscribe(() => this.onChange?.(this.parseFieldsValues()));
    }
    ngOnChanges(changes) {
        const _disableFields = changes['disableFields'];
        if (_disableFields) {
            this.enableOrDisableFields(_disableFields.currentValue);
        }
    }
    ngOnDestroy() {
        this.ngUsubscribe.next();
        this.ngUsubscribe.complete();
    }
    registerOnChange(fn) {
        this.onChange = fn;
    }
    registerOnTouched(fn) {
        this.onTouched = fn;
    }
    writeValue(value) {
        if (this.ready) {
            const newValue = this.parseValuesForFields(value);
            this.formGroup.patchValue(newValue);
            this.value = newValue;
            this.createFilesIfSetFormValuesAfterInit();
        }
        else {
            this.formGroup.patchValue(value || {});
            this.value = value;
        }
    }
    setDisabledState(isDisabled) {
        if (isDisabled) {
            this.formGroup.disable({ emitEvent: false });
        }
        else {
            this.formGroup.enable({ emitEvent: false });
        }
    }
    getCustomFields() {
        if (this.entityObject?.entity_) {
            return of(this.entityObject);
        }
        return this.customFieldsService.getCustomFields(this.domain, this.service, this.entity, this.customFieldsEndpoint);
    }
    validate() {
        const errors = {};
        Object.keys(this.formGroup.controls).forEach((field) => {
            const { errors: controlErrors } = this.formGroup.get(field);
            if (controlErrors) {
                errors[field] = controlErrors;
            }
        });
        return errors;
    }
    cleanFields() {
        this.formGroup.reset();
    }
    enableOrDisableFields(disabled) {
        if (!this.formGroup) {
            return;
        }
        for (const controlName of Object.keys(this.formGroup.value)) {
            disabled ? this.formGroup.get(controlName)?.disable() : this.formGroup.get(controlName)?.enable();
        }
    }
    _validateInputs() {
        if (!this.domain) {
            throw new Error('You need to specify the custom-fields domain!');
        }
        if (!this.service) {
            throw new Error('You need to specify the custom-fields service!');
        }
        if (!this.entity) {
            throw new Error('You need to specify the custom-fields entity!');
        }
    }
    _createForm() {
        this.formGroup = new FormGroup({});
        const observables = [this.getCustomFields(), this.localeService.get()];
        forkJoin(observables)
            .pipe(takeUntil(this.ngUsubscribe), finalize(() => {
            this.formGroup.markAsPristine();
            this.parentControl?.markAsPristine();
            if (this.ready$) {
                this.ready$.next(true);
            }
        }))
            .subscribe((response) => {
            const [customFieldsResponse, localeOptions] = response;
            const defaults = {};
            defaults[CustomFieldType.String] = {};
            defaults[CustomFieldType.Boolean] = { defaultValue: false };
            defaults[CustomFieldType.Integer] = {};
            defaults[CustomFieldType.Double] = { defaultMask: '' };
            defaults[CustomFieldType.Money] = {};
            defaults[CustomFieldType.Date] = {};
            defaults[CustomFieldType.DateTime] = {};
            defaults[CustomFieldType.LocalDateTime] = {};
            defaults[CustomFieldType.Time] = {};
            defaults[CustomFieldType.Blob] = {};
            defaults[CustomFieldType.Enum] = {};
            defaults[CustomFieldType.Binary] = {};
            defaults[CustomFieldType.Any] = {};
            if (!customFieldsResponse || !customFieldsResponse.entity_) {
                return;
            }
            const { active, fields } = customFieldsResponse.entity_;
            if (!active) {
                return;
            }
            fields
                .filter((field) => field.customizable && field.customization?.active)
                .forEach((field) => {
                const dynamicType = this.getDynamicType(field, localeOptions);
                const fieldType = field.type;
                if (field.type === CustomFieldType.Blob && this.value && this.value[dynamicType.name]) {
                    this.createBlobToFileUpload(dynamicType);
                }
                const { validationRegex } = field.customization;
                const asIsTypes = [
                    CustomFieldType.Boolean,
                    CustomFieldType.Money,
                    CustomFieldType.Date,
                    CustomFieldType.DateTime,
                    CustomFieldType.LocalDateTime,
                    CustomFieldType.Time,
                ];
                const validators = [];
                if (validationRegex && !asIsTypes.includes(fieldType)) {
                    validators.push(Validators.pattern(validationRegex));
                }
                if (fieldType === CustomFieldType.Integer && !dynamicType.mask) {
                    validators.push(Validators.pattern(/^\-?\d*$/));
                }
                if (dynamicType.required?.()) {
                    validators.push(Validators.required);
                }
                const control = new FormControl({ value: defaults[fieldType].defaultValue, disabled: this.formGroup.disabled }, validators);
                this.formGroup.addControl(dynamicType.name, control);
                this.fields.push(dynamicType);
            });
            this.dynamicStructure = dynamicTypeToDynamicStructure(this.fields);
            this.createFieldCustomization(fields);
            this.formGroup.patchValue(this.parseValuesForFields(this.value));
            this.ready = true;
        });
    }
    parseValuesForFields(values) {
        const parsedValues = { ...values };
        this.fields.forEach((field) => {
            const type = field.type;
            const name = field.name;
            const value = values?.[name];
            /**
             * Tratamento exclusivo para campos boolean que tem o status Empty
             * Essa condicional necessita estar antes do if (!value) return;
             * Pois ela tem um status que usa null no valor do campo radio boolean
             */
            if (type === 'boolean') {
                const isString = typeof value === 'string';
                const notValid = !isString && typeof value !== 'boolean';
                if (notValid) {
                    parsedValues[name] = null;
                }
                else {
                    // Condicional para campos que retornam string de boolen do backand
                    if (isString) {
                        parsedValues[name] = value === 'true' ? true : false;
                    }
                    else {
                        parsedValues[name] = value;
                    }
                }
            }
            if (!value) {
                return;
            }
            switch (type) {
                case 'date':
                    parsedValues[name] = moment(value).toDate();
                    break;
                case 'dateTime':
                    parsedValues[name] = moment(value).toDate();
                    break;
                case 'localDateTime':
                    parsedValues[name] = moment(value, 'YYYY-MM-DD[T]HH:mm:ss.SSS').toDate();
                    break;
                case 'time':
                    parsedValues[name] = moment(value, 'HH:mm:ss').toDate();
                    break;
                default:
                    break;
            }
        });
        return parsedValues;
    }
    /**
     * Algumas equipes só setam valor no formulário, após o carregamento da tela
     * Como é bem padrão isso, foi necessário criar esse método para gerar o file
     * após setar o valor no formulário
     */
    createFilesIfSetFormValuesAfterInit() {
        if (!this.hasUploaded) {
            this.fields
                .filter((field) => field.type === 'blob')
                .forEach((field) => {
                if (this.formGroup.get(field.name)?.value) {
                    this.createBlobToFileUpload(field);
                }
            });
        }
    }
    parseFieldsValues() {
        const parsedValues = {};
        this.fields.forEach((field) => {
            const { type } = field;
            const name = field.name;
            let value = this.formGroup.get(name)?.value;
            if (value) {
                switch (type) {
                    case 'number':
                        const { mask, scale } = field;
                        if (mask)
                            value = new BigNumber(value).toFixed(scale).toString();
                        break;
                    case 'date':
                        value = moment(value).format('YYYY-MM-DD');
                        break;
                    case 'dateTime':
                        value = moment(value).format();
                        break;
                    case 'localDateTime':
                        value = moment(value).format('YYYY-MM-DD[T]HH:mm:ss.SSS');
                        break;
                    case 'time':
                        value = moment(value).format('HH:mm:ss');
                        break;
                    default:
                        break;
                }
            }
            if ((value === null || value === undefined) && (type === 'number' || type === 'enum')) {
                const isMultiple = field.multiple;
                parsedValues[name] = isMultiple ? [] : null;
            }
            else {
                parsedValues[name] = value;
            }
        });
        if (this.hasBlob) {
            parsedValues['fieldCustomization'] = this.formGroup.get('fieldCustomization')?.value;
        }
        return parsedValues;
    }
    getDynamicType(field, localeOptions) {
        let parameters = {};
        switch (field.type) {
            case CustomFieldType.Blob:
                parameters = this.getBlobParameters();
                break;
            case CustomFieldType.Boolean:
                parameters = this.getBooleanParameters();
                break;
            case 'Enumeration':
            case CustomFieldType.Enum:
                field.type = 'Enum';
                parameters = this.getSelectParameters(field);
                break;
            case CustomFieldType.Money:
                parameters = {
                    type: 'legacyNumber',
                    precision: 15,
                    scale: 2,
                    leftAddon: {
                        label: localeOptions?.number?.currencySymbol ?? 'R$',
                    },
                };
                break;
            case CustomFieldType.Double:
                parameters = {
                    type: 'legacyNumber',
                    precision: 15,
                    scale: 2,
                    localizedNumber: true,
                };
                break;
            case CustomFieldType.Integer:
                parameters = {
                    type: 'legacyNumber',
                    precision: 15,
                    scale: 0,
                };
                break;
            case CustomFieldType.Any:
                field.type = 'String';
                parameters = {
                    type: 'string',
                };
                break;
        }
        const dynamicType = {
            ...parameters,
            name: field.id,
            label: field.customization.label,
            tooltip: field.customization.tooltip,
            infoSign: field.customization.infoSign,
            type: apiTypesToDynamicFormType(field.type),
            mask: field.customization.mask,
            required: () => field.customization.mandatory ?? false,
            calendarOptions: localeOptions.calendar,
            currencyOptions: localeOptions.number,
        };
        return dynamicType;
    }
    getSelectParameters(field) {
        return {
            type: 'enum',
            showClear: true,
            multiple: field.customization.customEnumeration.multiple,
            options: field.customization.customEnumeration.values.map((e) => ({ label: e.value, value: e.key })),
        };
    }
    getBooleanParameters() {
        return {
            type: 'boolean',
            optionsLabel: {
                true: this.getTranslateLabel(`true_label`),
                false: this.getTranslateLabel(`false_label`),
                empty: this.getTranslateLabel(`empty_label`),
            },
        };
    }
    getBlobParameters() {
        return {
            type: 'blob',
            size: {
                sm: 12,
                md: 12,
                lg: 12,
                xl: 12,
            }, // Como vai ser filho de Row, faz sentido habilitar o tipo expandido.
            accept: 'image/*, application/*, text/*',
            chooseLabel: this.getTranslateLabel(`choose_label`),
            removeLabel: this.getTranslateLabel(`remove_label`),
            cancelLabel: this.getTranslateLabel(`cancel_label`),
            successTooltip: this.getTranslateLabel(`success_tooltip`),
            multiple: false,
            onUploadFile: (event, blobField) => {
                this.hasUploaded = true;
                this.uploadFile(event, blobField);
            },
            onRemoveFile: (event, blobField) => {
                this.removeFile({ file: event }, blobField);
            },
            onCancelUpload: (event, blobField) => {
                this.cancelUpload(event, blobField);
            },
            onDownloadFile: (event, blobField) => {
                this.downloadFile(event, blobField);
            },
            showFileUploadDate: this.showFileUploadDate,
        };
    }
    /**
     * É necessário criar o fieldCustomization quando há um Blob na entidade para gerar o
     * com os fields inseridos e deletados.
     */
    createFieldCustomization(fields) {
        this.hasBlob = !!fields.filter((field) => field.type === CustomFieldType.Blob).length;
        if (this.hasBlob) {
            this.formGroup.addControl('fieldCustomization', new FormArray([
                new FormGroup({
                    domain: new FormControl(this.domain),
                    service: new FormControl(this.service),
                    entity: new FormControl(this.entity),
                    toDelete: new FormControl({ value: {}, disabled: false }),
                    toInsert: new FormControl({ value: {}, disabled: false }),
                }),
            ]));
        }
    }
    createBlobToFileUpload(field) {
        const _name = field.name;
        const objectId = this.value[_name] ? this.value[_name] : this.formGroup.get(_name)?.value;
        const fileName = objectId.substring(objectId.lastIndexOf('/') + 1);
        const file = { objectId, name: fileName, savedFile: true };
        field.files = [file];
    }
    downloadFile(event, field) {
        const { index, anchor } = event;
        const _files = field.files || [];
        if (!_files.length) {
            return;
        }
        const currentFile = _files[index];
        if (currentFile.objectURL) {
            anchor.nativeElement.click();
        }
        else {
            const _objectId = currentFile.objectId;
            this.customFieldsService
                .requestAccess(_objectId, this.requestAccessEndpoint)
                .pipe(takeUntil(this.ngUsubscribe))
                .subscribe((data) => {
                const { fileName, uri } = data;
                this.customFieldsService
                    .getFile(uri)
                    .pipe(takeUntil(this.ngUsubscribe))
                    .subscribe((blob) => {
                    const newFile = new File([blob], fileName);
                    newFile.objectURL = this.sanitizer.bypassSecurityTrustUrl(uri);
                    anchor.nativeElement.setAttribute('href', uri);
                    newFile.objectId = currentFile.objectId;
                    newFile.savedFile = true;
                    _files[index] = newFile;
                    field.files = [..._files];
                    anchor.nativeElement.click();
                });
            });
        }
    }
    uploadFile(event, formField) {
        const { files } = event;
        const field = this.fields.find((record) => record.name === formField.name);
        if (!field) {
            return;
        }
        // Se ocorrer um upload, já existindo um arquivo com upload feito. É necessário excluir o mesmo.
        if (field?.files?.length) {
            this.removeFile({ file: field.files[0] }, field);
        }
        field.files = files;
        const _name = field.name;
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            if (!file.savedFile && !file.progress) {
                file.isUploading = true;
                this.formGroup.get(_name)?.setValidators(isUploading(file));
                this.formGroup.get(_name)?.updateValueAndValidity();
                this.customFieldsService
                    .getFileLocationUrl({
                    domain: this.domain,
                    service: this.service,
                    entityName: this.entity,
                    field: _name,
                    fileName: file.name,
                }, this.fileLocationEndpoint)
                    .pipe(takeUntil(this.ngUsubscribe), catchError((err) => of(this.defaltCatchError(field, err, i))))
                    .subscribe((data) => {
                    const { location, version, objectId } = data;
                    file.version = version;
                    file.objectId = objectId;
                    file.uploadSubscribe = this.customFieldsService
                        .uploadTempFile(location, file)
                        .pipe(takeUntil(this.ngUsubscribe), catchError((err) => of(this.defaltCatchError(field, err, i))), finalize(() => {
                        file.isUploading = false;
                    }))
                        .subscribe((response) => {
                        const { type } = response;
                        if (!this.uploadCanceled) {
                            if (type === HttpEventType.UploadProgress) {
                                file.progress = Math.round(response.loaded / response.total) * 100;
                            }
                            else if (type === HttpEventType.Response) {
                                file.objectURL = this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(file));
                                const value = { objectId, name: file.name, version: file.version };
                                const toInsert = this.formGroup.get('fieldCustomization')?.value[0].toInsert;
                                const fieldCustomization = this.formGroup.get('fieldCustomization')?.value;
                                if (fieldCustomization?.value?.[0]) {
                                    fieldCustomization.value[0].toInsert = {
                                        ...toInsert,
                                        [_name]: value,
                                    };
                                }
                                this.formGroup.get(_name)?.setValue(`${file.objectId}/${file.name}`);
                                this.formGroup.get(_name)?.clearValidators();
                                this.formGroup.get(_name)?.updateValueAndValidity();
                                field.files = [file];
                            }
                        }
                        else if (this.uploadCanceled && type === HttpEventType.Response) {
                            this.uploadCanceled = false;
                        }
                    });
                    field.files = [file];
                });
            }
        }
    }
    removeFile(event, blobField) {
        const { file } = event;
        const field = this.fields.find((record) => record.name === blobField.name);
        field.files = [];
        if (file.objectId) {
            // Quando é um arquivo já salvo o objectId já é no formato "objectId/name"
            const value = file.savedFile ? `${file.objectId}` : `${file.objectId}/${file.name}`;
            const toDelete = this.formGroup.get('fieldCustomization').value[0].toDelete;
            delete this.formGroup.get('fieldCustomization').value[0].toInsert[field.name];
            this.formGroup.get('fieldCustomization').value[0].toDelete = {
                ...toDelete,
                [field.name]: [...(toDelete[field.name] || []), value],
            };
        }
        this.formGroup.get(field.name).clearValidators();
        this.formGroup.get(field.name).setValue('');
        this.formGroup.get(field.name).updateValueAndValidity();
    }
    cancelUpload(index, formField) {
        this.uploadCanceled = true;
        const field = this.fields.find((record) => record.name === formField.name);
        if (!field) {
            return;
        }
        const _name = field.name;
        const _files = field.files || [];
        _files[index]?.uploadSubscribe?.unsubscribe();
        field.files = [];
        const fieldCustomization = this.formGroup.get('fieldCustomization')?.value[0];
        delete fieldCustomization.toInsert[_name];
        this.formGroup.get(_name)?.clearValidators();
        this.formGroup.get(_name)?.setValue('');
        this.formGroup.get(_name)?.updateValueAndValidity();
    }
    defaltCatchError(field, err, index) {
        const { files } = field;
        if (files) {
            files[index].error = err;
            files[index].isUploading = false;
            field.files = [...files];
            const _name = field.name;
            this.formGroup.get(_name)?.setValidators([errorOnUpload(files[index])]);
            this.formGroup.get(_name)?.updateValueAndValidity();
            return throwError(() => new Error('error in upload file. Details: ' + err.message));
        }
        else {
            return throwError(() => new Error('error in upload file. Details: ' + err.message));
        }
    }
    getTranslateLabel(label) {
        return this.translateService.instant(`${this.domain}.${this.service}.${label}`);
    }
    addDisplayTimeInfoSignToFields() {
        this.fields.forEach((field) => {
            field.displayTimeInfoSign = this.displayTimeInfoSign;
        });
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: CustomFieldsComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.14", type: CustomFieldsComponent, isStandalone: true, selector: "s-custom-fields", inputs: { domain: "domain", service: "service", entity: "entity", invalidErrorLabel: "invalidErrorLabel", entityObject: "entityObject", customFieldsEndpoint: "customFieldsEndpoint", fileLocationEndpoint: "fileLocationEndpoint", requestAccessEndpoint: "requestAccessEndpoint", requiredErrorMessage: "requiredErrorMessage", displayTimeInfoSign: "displayTimeInfoSign", showFileUploadDate: "showFileUploadDate", ready$: "ready$", disableFields: "disableFields" }, providers: [
            {
                provide: NG_VALUE_ACCESSOR,
                useExisting: CustomFieldsComponent,
                multi: true,
            },
            {
                provide: NG_VALIDATORS,
                useExisting: CustomFieldsComponent,
                multi: true,
            },
        ], usesOnChanges: true, ngImport: i0, template: "@let errorMessages =\n    {\n        pattern: invalidErrorLabel,\n        required: requiredErrorMessage,\n    };\n\n<s-dynamic-form\n    [configs]=\"dynamicStructure\"\n    [form]=\"formGroup\"\n    [errorMessages]=\"errorMessages\"\n>\n</s-dynamic-form>\n\n", dependencies: [{ kind: "component", type: DynamicFormComponent, selector: "s-dynamic-form", inputs: ["id", "configs", "fields", "form", "errorMessages"] }] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: CustomFieldsComponent, decorators: [{
            type: Component,
            args: [{ selector: 's-custom-fields', providers: [
                        {
                            provide: NG_VALUE_ACCESSOR,
                            useExisting: CustomFieldsComponent,
                            multi: true,
                        },
                        {
                            provide: NG_VALIDATORS,
                            useExisting: CustomFieldsComponent,
                            multi: true,
                        },
                    ], standalone: true, imports: [DynamicFormComponent], template: "@let errorMessages =\n    {\n        pattern: invalidErrorLabel,\n        required: requiredErrorMessage,\n    };\n\n<s-dynamic-form\n    [configs]=\"dynamicStructure\"\n    [form]=\"formGroup\"\n    [errorMessages]=\"errorMessages\"\n>\n</s-dynamic-form>\n\n" }]
        }], ctorParameters: () => [], propDecorators: { domain: [{
                type: Input,
                args: [{ required: true }]
            }], service: [{
                type: Input,
                args: [{ required: true }]
            }], entity: [{
                type: Input,
                args: [{ required: true }]
            }], invalidErrorLabel: [{
                type: Input
            }], entityObject: [{
                type: Input
            }], customFieldsEndpoint: [{
                type: Input
            }], fileLocationEndpoint: [{
                type: Input
            }], requestAccessEndpoint: [{
                type: Input
            }], requiredErrorMessage: [{
                type: Input
            }], displayTimeInfoSign: [{
                type: Input
            }], showFileUploadDate: [{
                type: Input
            }], ready$: [{
                type: Input
            }], disableFields: [{
                type: Input
            }] } });
function isUploading(file) {
    return () => (file.isUploading ? { isUploading: true } : null);
}
function errorOnUpload(file) {
    return () => (file.error ? { uploadError: true } : null);
}

class CustomFieldsModule {
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: CustomFieldsModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
    static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: CustomFieldsModule, imports: [CustomFieldsComponent], exports: [CustomFieldsComponent] });
    static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: CustomFieldsModule, providers: [CustomFieldsService, TranslateService], imports: [CustomFieldsComponent] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: CustomFieldsModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [CustomFieldsComponent],
                    exports: [CustomFieldsComponent],
                    providers: [CustomFieldsService, TranslateService],
                }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { CustomFieldType, CustomFieldsComponent, CustomFieldsModule, CustomFieldsService, apiTypesToDynamicFormType };
//# sourceMappingURL=seniorsistemas-angular-components-custom-fields.mjs.map
