Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
270 kB
3
Indexable
Never
import { Component, OnInit, Output, EventEmitter, NgZone, ViewChild, ElementRef, OnDestroy, AfterViewInit, ChangeDetectorRef, Input } from '@angular/core';
import { ClientCenterTabs } from '../../../centers/models/ClientCenterTabs.model';
import { LoadManagerService } from 'src/app/common/loading-overlay/loadManager.service';
import { Subscription, forkJoin } from 'rxjs';
import { ClientCenterInterlocutorDetail } from '../../../centers/models/ClientCenterInterlocutorDetail.model';
import { OfficeSelectorService } from 'src/app/common/office-selector/office-selector.service';
import { isUndefined } from 'lodash';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { AccessManagerService } from 'src/app/auth/access-manager/access-manager.service';
import { CentersService } from '../../../centers/services/centers.service';
import { SharedService } from 'src/app/util/shared.service';
import { Title } from '@angular/platform-browser';
import { AccessManagerResourceActionType } from 'src/app/models/AccessManager.Model';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { ModalDialogComponent } from 'src/app/common/modal-dialog/modal-dialog.component';
import { ModalDialogService } from 'src/app/common/modal-dialog/modal-dialog.service';
import { ToastContainerDirective, ToastrService } from 'ngx-toastr';
import { BsLocaleService } from 'ngx-bootstrap/datepicker';
import { HeaderService } from 'src/app/common/header/header.service';
import { InterlocutorsService } from '../../services/interlocutors.services';
import { TableModalComponent } from 'src/app/shared/table-modal/table-modal.component';
import { ClientUrlEsolutions } from 'src/app/features/centers/models/ClientUrlEsolutions.model';
import { RaasService } from 'src/app/auth/raas/raas.service';
import { ToggleSwitchComponent } from 'src/app/shared/toggle-switch/toggle-switch.component';
import { GroupsService } from 'src/app/features/groups/services/groups.service';
import { ClientsService } from 'src/app/features/clients/services/clients.service';

@Component({
    selector: 'interlocutors-form',
    templateUrl: './interlocutors-form.component.html',
    styleUrls: ['./interlocutors-form.component.scss'],
    providers: [LoadManagerService]
})
export class InterlocutorsFormComponent implements OnInit, OnDestroy, AfterViewInit {
    @Output() public onChangeMode = new EventEmitter<boolean>();

    @ViewChild('modalDialogCancelInterlocutor') private dialog: ModalDialogComponent;

    @ViewChild('modalDialogZipCode') private dialogZipCode: ModalDialogComponent;

    @ViewChild('modalDialogInterlocutorSolData') private dialogInterlocutorSolData: ModalDialogComponent;

    @ViewChild('modalDialogInterlocutorData') private dialogInterlocutorData: ModalDialogComponent;

    @ViewChild('modalDialogInterlocutorTSM') private dialogInterlocutorTSM: ModalDialogComponent;

    @ViewChild('modalDialogDeleteEsolution') private dialogDeleteEsolution: ModalDialogComponent;

    @ViewChild(ToastContainerDirective) toastContainer: ToastContainerDirective;

    @ViewChild('listInterlocutorsExistModal') private listInterlocutorsExistModal: TableModalComponent;

    @ViewChild('panelInterlocutor') private panelInterlocutor: ElementRef;

    @ViewChild('listPanelHeaderEsolution') private listPanelHeaderEsolution: ElementRef;

    @ViewChild('listPanelContactForm') private panelContactForm: ElementRef;
    @ViewChild('listRelationRandstad') private relationRandstad: ElementRef;
    @ViewChild('listPanelPersonalInfo') private panelPersonalInfo: ElementRef;
    @ViewChild('listPanelBehaviour') private panelBehaviour: ElementRef;
    @ViewChild('listPanelInterlocutorPersonAddress') private panelInterlocutorPersonAddress: ElementRef;

    @ViewChild('principalChkSwitchToggles') public principalChkSwitchToggles: ToggleSwitchComponent;

    private mLoadStatusUpdatedSubscription: Subscription;
    public branchOnInit: any;
    private officeSelectorSubscription: Subscription;
    private okClickModalSubscritpion: Subscription;
    private cancelClickModalSubscritpion: Subscription;
    public isPpalOffice: boolean;
    public isSameOffice: boolean;
    messageTooltip: string = '';

    // Título de la cabecera
    public title: string;

    isNewStructure: boolean = false;
    // Controla el loading
    busy: boolean;
    previousBusy: boolean = true;
    // Permisos de Gestor
    permission: any;
    branchPermissions: any;
    permissionUser: any;
    interlocutor: ClientCenterInterlocutorDetail;
    clientCenterTabs: ClientCenterTabs;

    // Booleano que controla si la pantalla está en modo detalle
    isActionDetail: boolean = false;
    // Booleano que controla si la pantalla está en modo edición
    isEdit: boolean = false;
    // Booleano que controla si la pantalla está en modo alta
    isNew: boolean = false;

    // Booleano que controla si se bloquean los controles en alta o edición
    allowEnableControls: boolean = false;

    // Formulario
    interlocutorForm: FormGroup;
    isFocusing = false;

    isPortal: any;

    // Booleano que controla si ya se envio a Grabar Proceso
    isSave: boolean = false;

    //Query params
    clientId: number;
    clientCenterId: number;
    interlocutorId: number;
    contactPersonRelId: number;

    // Listados de los desplegables
    sexesList = [];
    languagesList = [];
    fiscalDocTypesList = [];
    functionsList = [];
    addressTypesList = [];
    addressCountriesList = [];
    addressProvincesList = [];
    addressCitiesList = [];
    positionsList = [];
    mailingTypesList = [];
    clientCenterList: any = [];
    branchList: any = [];
    interlocutorsOwners: any = [];
    hobbysList = [];
    statusList = [];
    otpTypesList = [];
    cecoList: any = [];
    contactTypesList = [];
    contactPersonsRelsTypesListData = [];
    contactPersonsRelsTypesList = [];
    valuesForRelationType = [];
    valuesForRelationRandstad: any = [];

    existContactPerson = false;

    // Variables JWT
    token: any;
    tokenInfo: any;

    // Ventana zip code
    dialogZipCodeTitle: string;
    dialogZipCodeMessage: string;
    currentDialog: string;

    cancelInterlocutorTitle: string = 'Inactivación de interlocutor';
    cancelInterlocutorText: string = '¿Deseas inactivar el interlocutor?';
    interlocutorDataTitle: string = 'Mantenimiento de interlocutores';
    interlocutorDataText1: string = 'El interlocutor ya existe, se procederá a la carga de sus datos.';
    interlocutorDataText2: string = '¿Deseas copiar los datos del interlocutor?';
    interlocutorTSMTitle: string = 'Interlocutor TSM';
    interlocutorTSMText: string = 'Si cambias el estado de este interlocutor no tendrás ningún TSM en este centro, ¿quieres que cambiemos el estado a mailing?';

    //Label
    newTitle: string = 'Nuevo interlocutor';
    editTitle: string = 'Modificar interlocutor';
    deleteTitle: string = 'Inactivar interlocutor';
    deleteLabel: string = 'Inactivar';
    panelTitle: string = 'Detalle interlocutor';
    inputLabel: string = 'Interlocutor';
    surveyChkLabel: string = 'Interlocutor válido para encuesta';

    // Validaciones
    validFiscalDocLenght: boolean = true;
    validFiscalDocLetter: boolean = true;
    validFiscalDocFormat: boolean = true;
    validFiscalDocFilled: boolean = true;
    validFiscalDocNotDuplicated: boolean = true;
    validSameHobby: boolean = true;
    validCheck: boolean = true;
    validCheckFiscNumber: boolean = true;
    requiredFiscalDocDecisor: boolean = false;
    validFiscalDocDecisor: boolean = true;
    validSurname2Decisor: boolean = true;
    requiredSurname2Decisor: boolean = false;
    blockFiscalDoc: boolean = false;
    blockDecisor: boolean = false;

    requiredFiscalDoc: string = '';

    validAddressZipCodeSpain: boolean = true;
    validAddressZipCodeSpainExist: boolean = true;

    validEmail: boolean = true;
    validPhone: boolean = true;

    validEmailSignerBChk: boolean = true;

    requiredProvince: boolean;
    requiredCity: boolean;

    isInGeneralParam: boolean = false;

    //Datepicker
    bsConfig: any;

    //Interlocutor Inactivo
    isInactive: boolean = false;

    mobileLabel: string = 'Móvil';
    mobileErrorLabel: string = 'móvil';
    phoneLabel: string = 'Teléfono';
    phoneErrorLabel: string = 'teléfono';

    defaultSearchType: string = '0';
    showBranch: boolean = false;

    clientCenterInterlocutor: ClientCenterInterlocutorDetail;

    disabledFirst: boolean = false;
    disabledPrincipalChk: boolean = true;

    // Grandes cuentas GGCC
    isKam: boolean = false;
    isGgcc: boolean = false;
    ggccBranchId: string = '3764';

    isSensitiveData: boolean = false;

    changeStatusCenter: boolean = false;

    //Validaciones telefono company params
    validatorsRegExPhones: any;
    validatorsRegExMobile: any;
    validatorsRegExMobileBegin: any;
    msgRegExMobile: string = '';

    existNif: any;

    //Validaciones email company params
    validatorsRegExEmail: any;

    isInCompanyParam: boolean = false;

    //Validaciones portal
    blockContrastData: boolean = false;
    blockContrastDataOther: boolean = false;
    isSupportCenter: boolean = false;
    blockCertificateData: boolean = false;
    dialogIntelocSolMsg: string;

    // Booleano que controla cuando es nuevo interlocutor
    isNewInterlocutor = false;
    interlocutorSearchDisable = true;

    titleModal = '';

    isPortalSigner = false;
    isProfessional = false;
    isEmployeeTeamLeader = false;
    isEmployeeSalesManager = false;

    // eSolution -
    showGridEsolution: boolean = false;
    //Lista
    clientEsolutionsList: ClientUrlEsolutions[] = [];
    //Paginacion Esolution
    esolutionPaginationList: any[] = [];
    paginationParamsEsolution: any;

    typeEsolutionList: any[] = [];
    isNewEsolution: boolean = false;
    isDeleteEsolution: boolean = false;
    esolutionForm: FormGroup;
    selectedEsolution: ClientUrlEsolutions;
    isDetailModeEsolution: boolean = false;
    msgOkEsolution: string = 'Se ha dado de alta la Solución Específica';
    msgOkDeleteEsolution: string = 'Solución específica borrada en relevate HR portal';

    //Ventana
    dialogDeleteEsolutionTitle = 'Borrado relevate HR portal';
    dialogDeleteEsolutionMsg = 'Este interlocutor ya no verá la información seleccionada en relevate HR portal, ¿deseas continuar?';

    //Mostrar campos por negocio
    isMailingTypeIdHidden: boolean;
    isCenterCostHidden: boolean;

    //Modularización
    @Input() iAction: string = null;
    @Input() iClientId: number = null;
    @Input() iClientCenterId: number = null;
    @Input() iInterlocutorId: number = null;
    @Input() iContactPersonRelId: number = null;
    @Input() iClientCenterInterlocutorList: any = null;
    @Input() iClientCenterTabs: ClientCenterTabs;
    @Input() iSelectedInterlocutorDetail: ClientCenterInterlocutorDetail;
    @Input() iToastContainer: ToastContainerDirective;

    @Output() oCancelEvent: EventEmitter<any> = new EventEmitter();
    @Output() oCallbackSaveEvent: EventEmitter<{ InterlocutorId: any; ContactPersonRelId: any }> = new EventEmitter();
    @Output() oCallbackChgModESolEvent: EventEmitter<any> = new EventEmitter();
    @Output() oParentBusyEvent: EventEmitter<any> = new EventEmitter();

    moreDialog: boolean = false;
    currentModel: any;
    validationsData: any;
    dialogDecisorMsg: string;
    isNewModeGGCC: boolean = false;
    interlocutorGGCCList: any = [];
    hideSaveGGCCSensitive: boolean = false;

    @ViewChild('modalDialogDecisor') private dialogInterlocDecisor: ModalDialogComponent;
    @ViewChild('modalDialogPrincipal') private dialogInterlocutorPpal: ModalDialogComponent;
    @ViewChild('modalDialogCex') private dialogInterlocutorCex: ModalDialogComponent;

    relationLabel: string = 'Centro';
    relationDefault: string = '3';
    currentEmployee: any;

    createRelation: boolean = false;

    dataDocRequired: any;

    constructor(
        private officeService: OfficeSelectorService,
        private zone: NgZone,
        private router: Router,
        private loadManagerService: LoadManagerService,
        private route: ActivatedRoute,
        private accessManagerService: AccessManagerService,
        private centersService: CentersService,
        private sharedService: SharedService,
        private titleService: Title,
        private formBuilder: FormBuilder,
        private modalService: ModalDialogService,
        private toastrService: ToastrService,
        private localeService: BsLocaleService,
        private headerService: HeaderService,
        private el: ElementRef,
        private ref: ChangeDetectorRef,
        private interlocutorsService: InterlocutorsService,
        private raasService: RaasService,
        private groupService: GroupsService,
        private clientService: ClientsService
    ) {
        this.centersService.isNavFromInterlocutor = false;
        this.allowEnableControls = false;

        // Suscripcion al servicio (si cambia la oficina llama aqui)
        this.officeSelectorSubscription = this.officeService.selectedOfficeUpdated.subscribe(
            async office => {
                this.isPpalOffice = office ? office.isPpalOffice : false;

                // Guardamos la oficina anterior
                let previousBranch = this.branchOnInit;

                // Obtenemos la oficina
                this.branchOnInit = JSON.parse(localStorage.getItem('branch'));
                if (!isUndefined(this.branchOnInit) && this.branchOnInit != null) {
                    this.isGgcc = this.branchOnInit.id == this.ggccBranchId;
                }
                this.isKam = this.getEditableUser('ff_user_kam_rws');

                if (
                    ((isUndefined(previousBranch) || previousBranch == null) && !isUndefined(this.branchOnInit) && this.branchOnInit != null) ||
                    (!isUndefined(previousBranch) && previousBranch != null && office != null && previousBranch.id !== office.id)
                ) {
                    this.zone.run(() => this.router.navigate(['interlocutors']));
                }
            },
            msg => {
                console.log('Error al subscribirse al servicio del selector de oficinas: ', msg);
            }
        );

        this.mLoadStatusUpdatedSubscription = this.loadManagerService.loadStatusUpdated.subscribe(value => {
            if (this.previousBusy) {
                this.previousBusy = this.busy;
            }

            this.busy = this.previousBusy;
            this.zone.run(() => (this.busy = this.busy || value));
        });

        // Busca los identificadores de cliente y centro en la Url
        this.route.params.subscribe(
            (params: Params) => {
                this.clientId = params.clientId;
                this.clientCenterId = params.clientCenterId;
                this.interlocutorId = params.interlocutorId;
            },
            error => {
                console.log(error);
            }
        );

        this.route.queryParams.subscribe(params => {
            this.contactPersonRelId = params.contactPersonRelId;
            if (params.contactPersonId) {
                this.interlocutorId = params.contactPersonId;
                this.createRelation = true;
            }
        });

        this.okClickModalSubscritpion = this.modalService.okClick.subscribe(x => {
            if (this.currentDialog == 'modalDialogInterlocutorTSM') {
                if (!this.iAction) {
                    this.cancelInterlocutor();
                }
                this.changeStatusCenter = true;
            } else if (this.currentDialog == 'modalDialogZipCode') {
                let provinceId = this.interlocutorForm.get('addressZipCode').value.substr(0, 2);
                let existProvince = this.addressProvincesList.filter(x => x.value == provinceId).length > 0;

                if (!existProvince) {
                    this.validAddressZipCodeSpainExist = false;
                } else {
                    this.interlocutorForm.get('addressProvinceId').setValue(provinceId);
                    this.checkCity(provinceId);
                }
            } else if (this.currentDialog == 'modalDialogInterlocutorData' || this.currentDialog == 'modalDialogInterlocutorSolData') {
                this.loadDialogDataInterlocutor();
            } else if (this.currentDialog == 'modalDialogDeleteEsolution') {
                let modelo = {
                    idAplicacion: this.selectedEsolution.IdAplicacion,
                    knResp: this.interlocutor.PortalElement
                };
                this.deleteEsolution(modelo);
            } else if (this.currentDialog == 'modalDialogDecisor') {
                if (!(this.isSupportCenter || this.isGgcc)) {
                    this.currentModel.NacsDecisorChk = 1;
                    this.currentModel.decisorChk = 0;
                }
                this.saveDataAfterValidations(this.currentModel);
            } else if (this.currentDialog == 'modalDialogCex') {
                this.currentModel.cexChk = 1;
                this.checkPpalInterloc(this.currentModel);
            } else if (this.currentDialog == 'modalDialogPrincipal') {
                this.currentModel.PpalChk = 1;
                this.checkDecisor(this.currentModel);
            } else if (this.currentDialog == 'modalDialogCancelInterlocutor') {
                this.cancelInterlocutor();
            }

            if (!this.moreDialog) {
                this.currentDialog = '';
            }
        });

        this.cancelClickModalSubscritpion = this.modalService.cancelClick.subscribe(x => {
            if (this.currentDialog == 'modalDialogZipCode') {
                this.interlocutorForm.get('addressZipCode').reset();
            } else if (this.currentDialog == 'modalDialogInterlocutorTSM') {
                this.changeStatusCenter = false;
            } else if (this.currentDialog == 'modalDialogDeleteEsolution') {
                this.isDeleteEsolution = false;
            } else if (this.currentDialog == 'modalDialogCex') {
                this.currentModel.cexChk = 0;
                this.checkPpalInterloc(this.currentModel);
            } else if (this.currentDialog == 'modalDialogPrincipal') {
                this.currentModel.PpalChk = 0;
                this.checkDecisor(this.currentModel);
            } else if (this.currentDialog == 'modalDialogDecisor') {
                this.setSpinner(false);
                this.interlocutorForm.get('decisorChk').setValue(false);
            }
            if (!this.moreDialog) {
                this.currentDialog = '';
            }
        });

        //Datepicker
        this.bsConfig = {
            date: 'DD/MM/YYYY',
            containerClass: 'theme-randstad-blue',
            dateInputFormat: 'DD/MM/YYYY',
            minDate: new Date(1900, 0, 1),
            maxDate: new Date(9999, 11, 31),
            showWeekNumbers: false,
            adaptivePosition: true
        };

        this.localeService.use('es');

        this.paginationParamsEsolution = { pageMaxSize: 5, currentPage: 1, currentIndex: 0 };
    }

    async ngOnDestroy(): Promise<void> {
        this.officeSelectorSubscription.unsubscribe();
        this.mLoadStatusUpdatedSubscription.unsubscribe();
        this.okClickModalSubscritpion.unsubscribe();
        this.cancelClickModalSubscritpion.unsubscribe();
    }

    async ngOnInit(): Promise<void> {
        try {
            this.setSpinner(true);

            // Obtenemos la oficina
            this.branchOnInit = JSON.parse(localStorage.getItem('branch'));

            if (this.branchOnInit != null && !isUndefined(this.branchOnInit)) {
                if (
                    (this.branchOnInit.companyId == 'RCO' && this.branchOnInit.productId == '0007') ||
                    (this.branchOnInit.companyId == 'EXP' && this.branchOnInit.productId == '0007') ||
                    (this.branchOnInit.companyId == 'EXP' && this.branchOnInit.productId == '0009')
                ) {
                    this.mobileLabel = 'Móvil Personal';
                    this.mobileErrorLabel = 'móvil personal';
                    this.phoneLabel = 'Teléfono Trabajo';
                    this.phoneErrorLabel = 'teléfono trabajo';
                    if (this.branchOnInit.productId == '0007') {
                        this.isProfessional = true;
                    }
                }
            }

            this.clientId ||= this.iClientId;
            this.clientCenterId ||= this.iClientCenterId;
            this.interlocutorId ||= this.iInterlocutorId;
            this.contactPersonRelId ||= this.iContactPersonRelId;

            if (!isUndefined(this.branchOnInit) && this.branchOnInit != null) {
                this.isGgcc = this.branchOnInit.id == this.ggccBranchId;
            }

            // Captura la acción de la Url para habilitar los campos del formulario
            switch (this.iAction || this.sharedService.getActionUrl()) {
                case 'add': {
                    this.isNew = true;
                    this.isSave = false;
                    if (this.iAction) {
                        this.interlocutorId = null;
                    }
                    break;
                }
                case 'edit': {
                    this.isEdit = true;
                    this.allowEnableControls = true;
                    break;
                }
                case 'detail': {
                    this.isActionDetail = true;
                    this.allowEnableControls = true;
                    break;
                }
                case 'relation': {
                    this.isNew = true;
                    this.interlocutorId = this.interlocutorId;
                    this.createRelation = true;
                    break;
                }
                default: {
                    break;
                }
            }

            // Obtenemos los permisos de Gestor
            await this.getAllPermissions()
                .then(async data => {
                    this.permission = data[0];
                    this.permissionUser = data[1];

                    this.isNewStructure = this.getVisible('ff_interlocutorClientCenter_interlocutorBranchPanel');

                    this.isSameOffice = false;

                    this.isSupportCenter = this.getEditableUser('ff_user_supportCenter');
                    this.isKam = this.getEditableUser('ff_user_kam_rws');

                    if (this.isNewStructure) {
                        this.interlocutorDataTitle = 'Mantenimiento de personas de contacto';
                        this.interlocutorDataText1 = 'La persona de contacto ya existe, se procederá a la carga de sus datos.';
                        this.interlocutorDataText2 = '¿Deseas copiar los datos de la persona de contacto?';
                        this.interlocutorTSMTitle = 'Persona de contacto TSM';
                        this.interlocutorTSMText =
                            'Si cambias el estado de esta persona de contacto no tendrás ningún TSM en este centro, ¿quieres que cambiemos el estado a mailing?';

                        this.newTitle = 'Nueva persona de contacto';
                        this.editTitle = 'Modificar persona de contacto';
                        this.panelTitle = 'Persona de contacto';
                        this.inputLabel = 'Persona de contacto';
                        this.surveyChkLabel = 'Válida para encuesta';
                    }

                    this.controlsCompaniesContactPersonRels();

                    await this.getInitData()
                        .then(async data => {
                            if (this.isActionDetail) {
                                this.clientCenterTabs = data.clientCenterTabs;

                                if (
                                    this.clientCenterTabs.CompanyId == 'VEX' ||
                                    this.clientCenterTabs.CompanyId == 'RPS' ||
                                    this.clientCenterTabs.CompanyId == 'RWS' ||
                                    this.clientCenterTabs.CompanyId == 'FUN' ||
                                    this.isNewStructure
                                ) {
                                    this.deleteLabel = 'Borrar';

                                    this.cancelInterlocutorTitle = this.isNewStructure ? 'Borrado de persona de contacto' : 'Borrado de interlocutor';
                                    this.cancelInterlocutorText = this.isNewStructure
                                        ? '¿Deseas borrar la persona de contacto?'
                                        : '¿Deseas borrar el interlocutor?';
                                    this.deleteTitle = this.isNewStructure ? 'Borrar persona de contacto' : 'Borrar interlocutor';
                                }

                                this.interlocutor = data.interlocutor;

                                if (this.iAction) Object.assign(this.iSelectedInterlocutorDetail, data.interlocutor);

                                this.isSensitiveData = this.interlocutor ? this.interlocutor.HideSensitiveDataChk == 1 && !this.isGgcc : false;
                                this.isSameOffice = this.clientCenterTabs.BranchId == this.branchOnInit.id;

                                if (!this.isNewStructure) {
                                    switch (this.interlocutor.MailingTypeId) {
                                        case '2':
                                        case '3':
                                            this.isInactive = false;
                                            break;
                                        case '4':
                                            this.isInactive = true;
                                            break;
                                    }
                                }

                                this.sexesList = [{ value: this.interlocutor.SexoId, label: this.interlocutor.SexDescription }];
                                this.languagesList = [{ value: this.interlocutor.LanguageId, label: this.interlocutor.LanguageDescription }];
                                this.fiscalDocTypesList = [{ value: this.interlocutor.FiscalDocId, label: this.interlocutor.FiscalDocDescription }];
                                this.functionsList = [{ value: this.interlocutor.FunctionId, label: this.interlocutor.FunctionDescription }];
                                this.addressTypesList = [{ value: this.interlocutor.AddressId, label: this.interlocutor.AddressDescription }];
                                this.addressCountriesList = [{ value: this.interlocutor.AddressCountryId, label: this.interlocutor.AddressCountryName }];
                                this.addressProvincesList = [{ value: this.interlocutor.AddressProvinceId, label: this.interlocutor.AddressProvinceName }];
                                this.addressCitiesList = [{ value: this.interlocutor.AddressCityId, label: this.interlocutor.AddressCityName }];

                                if (this.branchOnInit.companyId == 'RWS' && this.isNewStructure) {
                                    this.positionsList = [];
                                    if (this.interlocutor && this.interlocutor.PositionInterlocFBIIdList) {
                                        this.interlocutor.PositionInterlocFBIIdList.forEach(pos => {
                                            let value = pos.m_Item1 ? pos.m_Item1 : pos.Item1;
                                            let label = pos.m_Item2 ? pos.m_Item2 : pos.Item2;
                                            this.positionsList.push({ value: value, label: label });
                                        });
                                    }
                                } else {
                                    this.positionsList = [{ value: this.interlocutor.PositionInterlocFBIId, label: this.interlocutor.PositionDescription }];
                                }

                                this.mailingTypesList = [{ value: this.interlocutor.MailingTypeId, label: this.interlocutor.MailingTypeDescription }];
                                this.interlocutorsOwners = [{ value: this.interlocutor.PUserId, label: this.interlocutor.PUserDesc }];
                                this.otpTypesList = [{ value: this.interlocutor.OtpTypeId, label: this.interlocutor.OtpTypeDesc }];
                                if (this.iAction)
                                    this.cecoList = [{ value: this.interlocutor.CenterCostSeq, label: this.interlocutor.CenterCostSeqDescription }];

                                if (this.interlocutor.CenterCostSeq > 0) {
                                    this.cecoList = [
                                        {
                                            value: this.interlocutor.CenterCostSeq.toString(),
                                            label: this.interlocutor.CenterCostSeq + ' - ' + this.interlocutor.CenterCostSeqDescription
                                        }
                                    ];
                                }

                                let label = this.interlocutor.ContactTypeDescription;

                                this.contactTypesList = [{ value: this.interlocutor.ContactTypeId.toString(), label: label }];

                                this.hobbysList.push({ value: this.interlocutor.Hobby1Id, label: this.interlocutor.Hobby1Description });
                                this.hobbysList.push({ value: this.interlocutor.Hobby2Id, label: this.interlocutor.Hobby2Description });

                                this.validatorsRegExPhones = data.companyParams.filter(x => x.ParamId == 'REGEXPNUMBERPHONES')[0];
                                this.validatorsRegExEmail = data.companyParams.filter(x => x.ParamId == 'REGEXEMAIL')[0];
                                this.validatorsRegExMobile = data.companyParams.filter(x => x.ParamId == 'REGEXPNUMBERMOBILES')[0];
                                this.validatorsRegExMobileBegin = data.companyParams.filter(x => x.ParamId == 'REGEXMOBILEBEGIN')[0];

                                this.isPortal = data.companyParams.filter(x => x.ParamId == 'INTERLOCSPORTALPERM')[0];

                                this.token = JSON.parse(localStorage.getItem('apiToken'));
                                this.tokenInfo = this.sharedService.getTokenInfo(this.token.access_token);

                                let roleString = this.tokenInfo.role.replace(/\[/gi, '', 'gi').replace(/\]/gi, '', 'gi');
                                let roles = roleString.split(',');
                                this.isInGeneralParam = false;

                                roles.forEach(element => {
                                    if (this.isPortal.MinValue.split(',').indexOf(element) > -1) {
                                        this.isInGeneralParam = true;
                                    }
                                });

                                this.initForm(this.interlocutor);
                                if (this.isNewStructure) {
                                    this.setInterlocutorHeader('Detalle persona de contacto');
                                } else {
                                    this.setInterlocutorHeader('Detalle interlocutor');
                                }

                                this.typeEsolutionList = data.specificSolutionsESolType;
                            } else if (this.isEdit) {
                                this.clientCenterTabs = data.clientCenterTabs;
                                this.interlocutor = data.interlocutor;
                                this.isSensitiveData = this.interlocutor ? this.interlocutor.HideSensitiveDataChk == 1 && !this.isGgcc : false;
                                this.isSameOffice = this.clientCenterTabs ? this.clientCenterTabs.BranchId == this.branchOnInit.id : true;

                                if (this.isSensitiveData) {
                                    if (this.iAction)
                                        this.sharedService.toastError('Este interlocutor pertenece a la oficina de Coordinación GGCC. No se puede modificar');
                                    else this.zone.run(() => this.router.navigate(['interlocutors']));
                                }

                                this.sexesList = data.sexes;
                                this.languagesList = data.languages;
                                this.fiscalDocTypesList = data.fiscalDocs;
                                this.functionsList = data.interlocutorsFunctions;
                                this.addressTypesList = data.addressesTypes;
                                this.addressCountriesList = data.countries;
                                this.addressProvincesList = data.provinces;
                                this.positionsList = data.positionsInterlocutorsFbi;
                                this.hobbysList = data.hobbys;
                                this.otpTypesList = data.otpTypes;
                                this.interlocutorsOwners = data.interlocutorsOwners;
                                this.mailingTypesList = data.mailingTypes;
                                this.cecoList = data.centerCost;

                                this.validatorsRegExPhones = data.companyParams.filter(x => x.ParamId == 'REGEXPNUMBERPHONES')[0];
                                this.validatorsRegExMobile = data.companyParams.filter(x => x.ParamId == 'REGEXPNUMBERMOBILES')[0];
                                this.validatorsRegExMobileBegin = data.companyParams.filter(x => x.ParamId == 'REGEXMOBILEBEGIN')[0];
                                this.validatorsRegExEmail = data.companyParams.filter(x => x.ParamId == 'REGEXEMAIL')[0];

                                if (
                                    this.branchOnInit.companyId == 'RPS' ||
                                    this.branchOnInit.companyId == 'VEX' ||
                                    this.branchOnInit.companyId == 'RWS' ||
                                    this.branchOnInit.companyId == 'FUN'
                                ) {
                                    this.contactTypesList = data.contactTypes.filter(
                                        x => x.value != (this.interlocutor.ContactTypeId == '1' || this.interlocutor.ContactTypeId == '9' ? '2' : '1')
                                    );
                                } else {
                                    this.contactTypesList = data.contactTypes;
                                }

                                let branchId = this.clientCenterTabs ? this.clientCenterTabs.CompanyId : this.branchOnInit.companyId;
                                if (branchId == 'RWS' || this.isProfessional) {
                                    let warningMsg = '';
                                    if (this.isSupportCenter) {
                                        if (this.interlocutor.IsPreregistered && !this.interlocutor.SignerChk) {
                                            warningMsg +=
                                                'Si modificas los datos de contraste, se va volver a imprimir el certificado para su firma por el cliente<br>';
                                        }
                                        if ([null, '0', '7'].indexOf(this.interlocutor.CertificateStatusId) < 0) {
                                            warningMsg += 'Tienes que inhabilitar primero el certificado para poder modificar los datos de contraste.<br>';
                                        }
                                        if (['0', '1', '2', '3', '4', '5', '6', '7', '8'].indexOf(this.interlocutor.CertificateStatusId) > 0) {
                                            if (
                                                this.interlocutor.SignerChk &&
                                                (this.interlocutor.CertificateStatusId == '1' || this.interlocutor.CertificateStatusId == '7')
                                            ) {
                                                this.blockContrastData = false;
                                                this.blockContrastDataOther = false;
                                            } else if (
                                                this.interlocutor.SignerChk &&
                                                ['0', '2', '3', '4', '5', '6', '8'].indexOf(this.interlocutor.CertificateStatusId) > 0
                                            ) {
                                                this.blockContrastData = true;
                                                this.blockContrastDataOther = false;
                                            } else if (!this.interlocutor.SignerChk && this.interlocutor.PortalElement) {
                                                this.blockContrastData = true;
                                                this.blockContrastDataOther = false;
                                            } else {
                                                this.blockContrastData = true;
                                                this.blockContrastDataOther = true;
                                            }
                                        }
                                    } else if (this.interlocutor.IsPreregistered) {
                                        warningMsg +=
                                            'Los campos de contraste no pueden modificarse debido al estado del certificado. Si necesitas cambiar los datos, abre una incidencia en el NACS a relevate HR portal<br>';
                                        if (
                                            this.interlocutor.SignerChk &&
                                            (this.interlocutor.CertificateStatusId == '1' || this.interlocutor.CertificateStatusId == '7')
                                        ) {
                                            this.blockContrastData = false;
                                            this.blockContrastDataOther = false;
                                        } else if (
                                            this.interlocutor.SignerChk &&
                                            ['0', '2', '3', '4', '5', '6', '8'].indexOf(this.interlocutor.CertificateStatusId) > 0
                                        ) {
                                            this.blockContrastData = true;
                                            this.blockContrastDataOther = false;
                                        } else if (!this.interlocutor.SignerChk && this.interlocutor.PortalElement) {
                                            this.blockContrastData = true;
                                            this.blockContrastDataOther = false;
                                        } else {
                                            this.blockContrastData = true;
                                            this.blockContrastDataOther = true;
                                        }
                                    }
                                    if (!this.isProfessional) {
                                        if (
                                            this.interlocutor.PortalElement != null &&
                                            this.interlocutor.PortalElement == '0' &&
                                            (!this.isSupportCenter || (this.isSupportCenter && this.interlocutor.SignerChk))
                                        ) {
                                            warningMsg += 'El interlocutor es de portal, no se puede modificar el documento<br>';
                                            this.blockFiscalDoc = true;
                                        }

                                        if (!this.interlocutor.IsValidContracts && !this.isNewStructure) {
                                            warningMsg += 'El interlocutor tiene contratos firmados, no se puede modificar el documento<br>';
                                            this.blockFiscalDoc = true;
                                        }
                                    }
                                    if (warningMsg != '') {
                                        this.sharedService.toastWarning(warningMsg);
                                    }

                                    if (this.interlocutor.PortalElement != null && this.interlocutor.PortalElement == '0') {
                                        this.blockDecisor = true;
                                    }
                                }
                                if (!this.isNewStructure) {
                                    this.clientCenterList.push({
                                        value: `${this.clientId.toString()} - ${this.clientCenterId.toString()}`,
                                        label: `${this.clientId.toString()}.${this.clientCenterId.toString()} - ${this.clientCenterTabs.ClientCenterName}`,
                                        statusId: this.clientCenterTabs.StatusId,
                                        branchId: this.clientCenterTabs.BranchId,
                                        centerName: this.clientCenterTabs.ClientCenterName,
                                        addressId: this.clientCenterTabs.AddressId,
                                        addressStreet: this.clientCenterTabs.AddressStreet,
                                        addressNumber: this.clientCenterTabs.AddressNumber,
                                        addressAditional: this.clientCenterTabs.AddressAditional,
                                        addressCountryId: this.clientCenterTabs.AddressCountryId,
                                        addressProvinceId: this.clientCenterTabs.AddressProvinceId,
                                        addressCityId: this.clientCenterTabs.AddressCityId,
                                        addressZipCode: this.clientCenterTabs.AddressZipCode
                                    });
                                }

                                if (this.getVisible('ff_interlocutorClientCenter_panelDataCenter') && this.isEdit && !this.isActionDetail) {
                                    this.clientCenterList = data.clientsBySearchType;
                                }
                                if (this.isNewStructure) {
                                    this.contactPersonsRelsTypesListData = data.relsTypes;
                                    if (this.branchOnInit.companyId == 'RWS') {
                                        this.contactPersonsRelsTypesList = this.interlocutor.SignerChk
                                            ? data.relsTypes.filter(x => x.value != '3')
                                            : data.relsTypes;
                                    } else {
                                        this.contactPersonsRelsTypesList = data.relsTypes.filter(x => x.value == this.interlocutor.RelationTypeId);
                                    }
                                }

                                let functionId = data.employee.FunctionId;
                                this.isEmployeeTeamLeader = functionId == 71 || functionId == 81 || functionId == 83;
                                this.isEmployeeSalesManager = functionId == 70;

                                this.initForm(this.interlocutor);

                                if (this.isNewStructure) {
                                    this.valuesForRelationType = [];
                                    this.interlocutorForm.get('relationTypeId').setValue(this.interlocutor.RelationTypeId);
                                    let relationTypeValue = '';
                                    let relationTypeLabel = '';
                                    if (this.interlocutor.RelationTypeId == '3') {
                                        this.relationLabel = 'Centro';
                                        await this.centersService
                                            .getClientCenterTabs(Number(this.interlocutor.ClientId), Number(this.interlocutor.ClientCenterId))
                                            .then(data => {
                                                relationTypeValue = `${this.interlocutor.ClientId} - ${this.interlocutor.ClientCenterId}`;
                                                relationTypeLabel = `${data.ClientCenterName} (${this.interlocutor.ClientId}.${this.interlocutor.ClientCenterId})`;
                                            });
                                    } else if (this.interlocutor.RelationTypeId == '2') {
                                        this.relationLabel = 'Cliente';
                                        await this.clientService.getClientDetail(Number(this.interlocutor.ClientId), '').then(data => {
                                            relationTypeValue = `${data.ClientId}`;
                                            relationTypeLabel = `${data.FiscalName} (${data.ClientId})`;
                                        });
                                    } else if (this.interlocutor.RelationTypeId == '1') {
                                        this.relationLabel = 'Grupo';
                                        await this.groupService.getClientGroup(Number(this.interlocutor.GroupId)).then(data => {
                                            relationTypeValue = `${data.GroupId}`;
                                            relationTypeLabel = `${data.GroupName} (${data.GroupId})`;
                                        });
                                    }
                                    this.valuesForRelationType = [
                                        {
                                            value: relationTypeValue,
                                            label: relationTypeLabel
                                        }
                                    ];
                                    this.interlocutorForm.get('relationTypeValue').setValue(relationTypeValue);

                                    this.valuesForRelationRandstad = [{ value: this.interlocutor.UserId, label: this.interlocutor.PEmployeeName }];
                                    this.interlocutorForm.get('relationRandstadValue').setValue(this.interlocutor.UserId);
                                }

                                if (this.interlocutorForm.get('addressCountryId').value != '11') {
                                    this.requiredProvince = false;
                                    this.clearFormField('addressProvinceId');

                                    this.requiredCity = false;
                                    this.clearFormField('addressCityId');
                                } else {
                                    this.checkCity(this.interlocutorForm.get('addressProvinceId').value);
                                }

                                if (this.isNewStructure) {
                                    if (this.interlocutor.PUserId == null || this.interlocutor.PUserId == '') {
                                        // se asigna 1 por defecto por asignacion de null en backend
                                        this.interlocutorForm.get('pUserId').setValue(1);
                                    }
                                    this.setInterlocutorHeader('Modificar persona de contacto');
                                } else {
                                    this.setInterlocutorHeader('Modificar interlocutor');
                                }
                            } else if (this.isNew) {
                                this.clientCenterTabs = data.clientCenterTabs;
                                this.interlocutorSearchDisable = false;
                                this.sexesList = data.sexes;
                                this.languagesList = data.languages;
                                this.fiscalDocTypesList = data.fiscalDocs;
                                this.functionsList = data.interlocutorsFunctions;
                                this.addressTypesList = data.addressesTypes;
                                this.addressCountriesList = data.countries;
                                this.addressProvincesList = data.provinces;
                                this.positionsList = data.positionsInterlocutorsFbi;
                                this.hobbysList = data.hobbys;
                                this.otpTypesList = data.otpTypes;
                                this.cecoList = data.centerCost;

                                this.interlocutorsOwners = data.interlocutorsOwners;
                                this.mailingTypesList = [];

                                if (
                                    this.branchOnInit.companyId == 'RPS' ||
                                    this.branchOnInit.companyId == 'VEX' ||
                                    this.branchOnInit.companyId == 'RWS' ||
                                    this.branchOnInit.companyId == 'FUN'
                                ) {
                                    this.contactTypesList = data.contactTypes.filter(x => x.value != '2');
                                } else {
                                    this.contactTypesList = data.contactTypes;
                                }

                                if (this.isNewStructure) {
                                    this.mailingTypesList = data.mailingTypes.filter(x => x.value != '4');
                                } else {
                                    if (this.getVisible('ff_interlocutorClientCenter_panelDataCenter') && this.isNew && !this.isActionDetail) {
                                        this.clientCenterList = data.clientsBySearchType;
                                    } else {
                                        if (this.clientCenterTabs) {
                                            this.clientCenterList.push({
                                                value: `${this.clientId.toString()} - ${this.clientCenterId.toString()}`,
                                                label: `${this.clientId.toString()}.${this.clientCenterId.toString()} - ${
                                                    this.clientCenterTabs.ClientCenterName
                                                }`,
                                                statusId: this.clientCenterTabs.StatusId,
                                                branchId: this.clientCenterTabs.BranchId,
                                                centerName: this.clientCenterTabs.ClientCenterName,
                                                addressId: this.clientCenterTabs.AddressId,
                                                addressStreet: this.clientCenterTabs.AddressStreet,
                                                addressNumber: this.clientCenterTabs.AddressNumber,
                                                addressAditional: this.clientCenterTabs.AddressAditional,
                                                addressCountryId: this.clientCenterTabs.AddressCountryId,
                                                addressProvinceId: this.clientCenterTabs.AddressProvinceId,
                                                addressCityId: this.clientCenterTabs.AddressCityId,
                                                addressZipCode: this.clientCenterTabs.AddressZipCode
                                            });
                                        }
                                    }

                                    this.mailingTypesList = data.mailingTypes;
                                }

                                if (this.isNewStructure && !this.iAction && this.isNew) {
                                    let functionId = data.employee.FunctionId;
                                    let structureLevelId = data.employee.StructureLevelId;

                                    let officeLevelExcep =
                                        functionId == 3 ||
                                        functionId == 63 ||
                                        functionId == 71 ||
                                        functionId == 81 ||
                                        functionId == 83 ||
                                        functionId == 85 ||
                                        functionId == 88;

                                    let groupLevel =
                                        functionId == 1 ||
                                        functionId == 4 ||
                                        functionId == 13 ||
                                        functionId == 17 ||
                                        functionId == 27 ||
                                        functionId == 44 ||
                                        functionId == 45 ||
                                        functionId == 62 ||
                                        functionId == 64 ||
                                        functionId == 65 ||
                                        functionId == 68 ||
                                        functionId == 69 ||
                                        functionId == 70 ||
                                        functionId == 84 ||
                                        functionId == 90;

                                    if (structureLevelId == '1' && !(officeLevelExcep || groupLevel)) {
                                        this.contactPersonsRelsTypesList = data.relsTypes.filter(x => x.value == this.relationDefault);
                                        await this.getValuesForRelationType(this.relationDefault);
                                    } else if (officeLevelExcep) {
                                        this.contactPersonsRelsTypesList = data.relsTypes.filter(x => x.value != '1');
                                        await this.getValuesForRelationType(this.relationDefault);
                                    } else {
                                        this.contactPersonsRelsTypesList = data.relsTypes.filter(x => x.value != this.relationDefault);
                                        this.relationDefault = null;
                                        this.relationLabel = 'Grupo/Cliente';
                                    }
                                    this.contactPersonsRelsTypesListData = this.contactPersonsRelsTypesList;
                                    await this.getCurrentEmployee();
                                    this.valuesForRelationRandstad.push({ value: this.currentEmployee.value, label: this.currentEmployee.label });
                                }

                                this.validatorsRegExPhones = data.companyParams.filter(x => x.ParamId == 'REGEXPNUMBERPHONES')[0];
                                this.validatorsRegExMobile = data.companyParams.filter(x => x.ParamId == 'REGEXPNUMBERMOBILES')[0];
                                this.validatorsRegExMobileBegin = data.companyParams.filter(x => x.ParamId == 'REGEXMOBILEBEGIN')[0];
                                this.validatorsRegExEmail = data.companyParams.filter(x => x.ParamId == 'REGEXEMAIL')[0];

                                let functionId = data.employee.FunctionId;
                                this.isEmployeeTeamLeader = functionId == 71 || functionId == 81 || functionId == 83;
                                this.isEmployeeSalesManager = functionId == 70;

                                this.initForm(this.interlocutor);
                                this.setDefaultValues();

                                this.interlocutorForm.get('contactTypeId').setValue('1');
                                this.interlocutorSearchDisable = false;

                                if (this.iAction && this.isNewStructure) this.setClientCenterOnInit();

                                if (this.isNewStructure && this.isNew && this.interlocutorId) {
                                    await this.loadDataInterlocutor({
                                        ContactPersonId: this.interlocutorId,
                                        contactPersonRelId: 0
                                    });
                                }

                                if (this.isNewStructure && this.createRelation) {
                                    this.setInterlocutorHeader('Crear relación persona de contacto');
                                } else if (this.isNewStructure) {
                                    this.setInterlocutorHeader('Nueva persona de contacto', true);
                                } else {
                                    this.setInterlocutorHeader('Nuevo interlocutor');
                                }
                            }
                            if (
                                this.interlocutorForm.getRawValue().otpTypeId == null ||
                                this.interlocutorForm.getRawValue().otpTypeId == '' ||
                                this.interlocutorForm.getRawValue().otpTypeId == '-1' ||
                                this.interlocutorForm.getRawValue().otpTypeId == '0'
                            ) {
                                this.interlocutorForm.get('otpTypeId').setValue('1');
                            }

                            if (this.iAction) {
                                this.clientCenterTabs = this.iClientCenterTabs;

                                if (this.isNew || this.isNewInterlocutor) {
                                    this.setDefaultAddress();
                                }
                            }
                        })
                        .catch(error => {
                            this.sharedService.showError(error);
                        });
                })
                .catch(error => {
                    this.sharedService.showError(error);
                });

            if (!this.isSameOffice && this.iAction) await this.getBranchPermission(this.clientCenterTabs.BranchId);
            if (this.isSupportCenter && this.isEdit) {
                if (this.interlocutor.SignerChk && ['0', '2', '3', '4', '5', '6', '8'].indexOf(this.interlocutor.CertificateStatusId) > 0) {
                    this.blockContrastData = true;
                    this.blockContrastDataOther = false;
                    this.enabledOther(1);
                } else if (!this.interlocutor.SignerChk && this.interlocutor.PortalElement) {
                    this.blockContrastData = true;
                    this.blockContrastDataOther = false;
                    this.enabledOther(2);
                }
            }
        } catch (error) {
            this.zone.run(() => this.router.navigate(['login']));
        } finally {
            this.setSpinner(false);
            this.sharedService.checkToasts(this.toastrService.toasts);
        }
    }

    ngAfterViewInit(): void {
        this.toastrService.overlayContainer = this.iAction ? this.iToastContainer : this.toastContainer;
    }

    loadDialogDataInterlocutor() {
        this.initForm(this.interlocutor);
        this.validateSaveForm();
        if (this.isNewStructure || this.iAction) {
            if (this.blockCertificateData) {
                this.interlocutorForm.get('firstName').disable();
                this.interlocutorForm.get('surname1').disable();
                this.interlocutorForm.get('surname2').disable();
                this.interlocutorForm.get('birthDate').disable();
                this.interlocutorForm.get('fiscalDocId').disable();
                this.interlocutorForm.get('fiscalDocNumber').disable();
                this.interlocutorForm.get('sexId').disable();
                this.interlocutorForm.get('phone2').disable();
                this.interlocutorForm.get('email').disable();
                this.interlocutorForm.get('signerChk').disable();
                this.interlocutorForm.get('decisorChk').disable();
                this.interlocutorForm.get('otpTypeId').disable();
            }
        }
    }

    async getInitData(): Promise<any> {
        let modelRegNums = [
            {
                ParamId: 'REGEXPNUMBERMOBILES',
                CompanyId: 'ALL'
            },
            {
                ParamId: 'REGEXPNUMBERPHONES',
                CompanyId: 'ALL'
            },
            {
                ParamId: 'REGEXMOBILEBEGIN',
                CompanyId: 'ALL'
            },
            {
                ParamId: 'REGEXEMAIL',
                CompanyId: 'ALL'
            },
            {
                ParamId: 'INTERLOCSPORTALPERM',
                CompanyId: 'ALL'
            }
        ];
        let promiseList: any = {};
        promiseList.companyParams = this.headerService.getCompanyParamsMulti(modelRegNums);

        if (this.clientId && this.clientCenterId) {
            promiseList.clientCenterTabs = this.centersService.getClientCenterTabs(this.clientId, this.clientCenterId);
        }

        if (this.isActionDetail) {
            promiseList.specificSolutionsESolType = this.centersService.getSpecificSolutionsESolType();
            if (this.isNewStructure) {
                promiseList.interlocutor = this.centersService.getContactPersonDetails(this.interlocutorId, this.contactPersonRelId);
            } else {
                promiseList.interlocutor = this.centersService.getClientCenterInterlocutorDetails(this.clientId, this.clientCenterId, this.interlocutorId);
            }
        }

        if (this.isNew || this.isEdit) {
            promiseList.sexes = this.centersService.getCommonsList('sexes', 'SexId', 'Description');
            promiseList.languages = this.centersService.getCommonsList('languages', 'LanguageId', 'Description');
            promiseList.fiscalDocs = this.centersService.getCommonsList('workersfiscaldocs', 'FiscalDocId', 'Description');
            promiseList.interlocutorsFunctions = this.centersService.getCommonsList('clientsinterlocutorsfunctions', 'FunctionId', 'Description');
            promiseList.addressesTypes = this.centersService.getCommonsList('addressestypes', 'AddressId', 'Description');
            promiseList.countries = this.centersService.getCommonsList('countries', 'CountryId', 'Description');
            promiseList.provinces = this.centersService.getCommonsList('provinces', 'ProvinceId', 'Name');
            promiseList.positionsInterlocutorsFbi = this.centersService.getPositionsInterlocutorsFbi(this.branchOnInit.id);
            promiseList.hobbys = this.centersService.getCommonsList('clientsinterlocutorshobbys', 'HobbyId', 'Description');
            promiseList.otpTypes = this.centersService.getCommonsList('otptypes', 'OtpTypeId', 'Description');
            promiseList.interlocutorsOwners = this.centersService.getInterlocutorsOwners();

            if (this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP') {
                promiseList.mailingTypes = this.centersService.getCommonsList('mailingtypes', 'MailingTypeId', 'Description');
            } else {
                promiseList.mailingTypes = this.centersService.getCommonsList('clientsinterlocutorsmailings', 'MailingTypeId', 'Description');
            }

            if (
                this.branchOnInit.companyId == 'RPS' ||
                this.branchOnInit.companyId == 'VEX' ||
                this.branchOnInit.companyId == 'RWS' ||
                this.branchOnInit.companyId == 'FUN'
            ) {
                promiseList.contactTypes = this.centersService.getCommonsList('contacttypes', 'ContactTypeId', 'Description');
            } else {
                promiseList.contactTypes = this.centersService.getCommonsList('clientsinterlocutorscontacts', 'ContactTypeId', 'Description');
            }

            this.token = JSON.parse(localStorage.getItem('apiToken'));
            this.tokenInfo = this.sharedService.getTokenInfo(this.token.access_token);
            promiseList.employee = this.centersService.getEmployee(this.tokenInfo.nameid, this.branchOnInit.id);

            if (this.isNewStructure) {
                promiseList.relsTypes = this.centersService.getCommonsList('contactpersonsrelstypes', 'TypeId', 'Description');
                if (this.isEdit) {
                    promiseList.interlocutor = this.centersService.getContactPersonDetails(this.interlocutorId, this.contactPersonRelId);
                }
            } else {
                if (this.isEdit) {
                    promiseList.interlocutor = this.centersService.getClientCenterInterlocutorDetails(this.clientId, this.clientCenterId, this.interlocutorId);
                    promiseList.clientBranches = this.centersService.getClientBranches(this.clientId);
                }
                if (this.isNew) {
                    if (this.getVisible('ff_interlocutorClientCenter_panelDataCenter')) {
                        promiseList.clientsBySearchType = this.centersService.getCenterClientsBySearchType(this.branchOnInit.id, this.defaultSearchType);
                    }
                }
            }
            if (this.clientId && this.clientCenterId) {
                promiseList.centerCost = this.centersService.getCentersCosts(this.clientId, this.clientCenterId, true);
            }
        }
        return await forkJoin(promiseList).toPromise();
    }

    initForm(clientCenterInterlocutorDetail: ClientCenterInterlocutorDetail) {
        let interlocutorGGCC = '';
        if (this.iAction && !this.isNewStructure) {
            if (this.isNewModeGGCC && clientCenterInterlocutorDetail && clientCenterInterlocutorDetail != null) {
                interlocutorGGCC =
                    clientCenterInterlocutorDetail.GGCCClientId +
                    '-' +
                    clientCenterInterlocutorDetail.GGCCClientCenterId +
                    '-' +
                    clientCenterInterlocutorDetail.GGCCInterlocutorId;
            }
        }

        //Formatear fecha
        let birthDate = null;

        if (clientCenterInterlocutorDetail && clientCenterInterlocutorDetail.BirthDate) {
            let dtSplit = clientCenterInterlocutorDetail.BirthDate.split('/');
            birthDate = new Date(parseInt(dtSplit[2]), parseInt(dtSplit[1]) - 1, parseInt(dtSplit[0]));
        }

        // Para el componente ng-select
        let functionIdValidator = [];
        let fiscalDocIdValidator = [];
        let sexIdValidator = [];
        let languageIdValidator = [];
        let addressIdValidator = [];
        let addressCountryIdValidator = [];
        let addressProvinceIdValidator = [];
        let addressCityIdValidator = [];
        let positionIdValidator = [];
        let mailingTypeIdValidator = [];
        let pUserIdValidator = [];
        let contactTypeIdValidator = [];
        let otpTypeIdValidator = [];
        let cliBranchValidator = [];

        if (this.getMandatory('ff_interlocutorClientCenter_functionId')) {
            functionIdValidator.push(Validators.required);
        }

        if (this.getMandatory('ff_interlocutorClientCenter_fiscalDocId')) {
            fiscalDocIdValidator.push(Validators.required);
        }

        if (this.getMandatory('ff_interlocutorClientCenter_sexId')) {
            sexIdValidator.push(Validators.required);
        }

        if (this.getMandatory('ff_interlocutorClientCenter_languageId')) {
            languageIdValidator.push(Validators.required);
        }

        if (this.getMandatory('ff_interlocutorClientCenter_addressId')) {
            addressIdValidator.push(Validators.required);
        }

        if (this.getMandatory('ff_interlocutorClientCenter_addressCountryId')) {
            addressCountryIdValidator.push(Validators.required);
        }

        if (this.getMandatory('ff_interlocutorClientCenter_addressProvinceId')) {
            this.requiredProvince = true;
            addressProvinceIdValidator.push(Validators.required);
        }

        if (this.getMandatory('ff_interlocutorClientCenter_addressCityId')) {
            this.requiredCity = true;
            addressCityIdValidator.push(Validators.required);
        }

        if (this.iAction && !this.isNewStructure) {
            if (
                this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                    ? this.getMandatory('ff_interlocutorClientCenter_positionId_rpsvex')
                    : this.getMandatory('ff_interlocutorClientCenter_positionId')
            ) {
                positionIdValidator.push(Validators.required);
            }

            if (this.getMandatory('ff_interlocutorClientCenter_mailingTypeId') || this.getMandatory('ff_interlocutorClientCenter_mailingTypeId_out')) {
                mailingTypeIdValidator.push(Validators.required);
            }

            if (this.getMandatory('ff_interlocutorClientCenter_contactTypeId')) {
                contactTypeIdValidator.push(Validators.required);
            }
        } else {
            if (this.getMandatory('ff_interlocutorClientCenter_positionId')) {
                positionIdValidator.push(Validators.required);
            }
            if (this.getMandatory('ff_interlocutorClientCenter_mailingTypeId')) {
                mailingTypeIdValidator.push(Validators.required);
            }

            if (this.getMandatory('ff_interlocutorClientCenter_status') && this.isNewStructure) {
                contactTypeIdValidator.push(Validators.required);
            }
        }

        if (this.getMandatory('ff_interlocutorClientCenter_owner')) {
            pUserIdValidator.push(Validators.required);
        }

        if (this.getMandatory('ff_interlocutorClientCenter_otpTypeId')) {
            otpTypeIdValidator.push(Validators.required);
        }

        if (this.getVisible('ff_interlocutorClientCenter_interlocutorbranch') && this.isNewStructure) {
            cliBranchValidator.push(Validators.required);
        }

        let disabledAll = true;
        if (
            clientCenterInterlocutorDetail &&
            ((clientCenterInterlocutorDetail.Phone1 != null && clientCenterInterlocutorDetail.Phone1 != '') ||
                (clientCenterInterlocutorDetail.Phone2 != null && clientCenterInterlocutorDetail.Phone2 != '') ||
                (clientCenterInterlocutorDetail.Email != null && clientCenterInterlocutorDetail.Email != ''))
        ) {
            disabledAll = false;
        }

        let client = this.clientId && this.clientCenterId ? `${this.clientId.toString()} - ${this.clientCenterId.toString()}` : '';
        let isTeamLeader = this.getEditableUser('ff_user_teamLeader_prof');
        let userId = clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.PUserId : '';
        let exist = true;

        if (!this.isActionDetail) {
            userId = !userId || userId == null || userId == '' ? this.branchOnInit.userId : userId;
            exist = this.interlocutorsOwners.filter(x => x.value == userId).length > 0;
        }

        let isDisabledShouldReceiveSurveyChk = !this.getEditable('ff_interlocutorClientCenter_surveyChk');

        let isKeyAccount =
            this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                ? this.getEditableUser('ff_user_ka_out')
                : this.branchOnInit.companyId == 'RWS' || this.branchOnInit.companyId == 'FUN'
                ? this.getEditableUser('ff_user_ka_rws')
                : this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP'
                ? this.isProfessional
                : false;

        let isDistrictManager =
            this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                ? this.getEditableUser('ff_user_dz_out')
                : this.branchOnInit.companyId == 'RWS' || this.branchOnInit.companyId == 'FUN'
                ? this.getEditableUser('ff_user_dz_rws')
                : this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP'
                ? this.isProfessional
                : false;

        let isRegionManager =
            this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                ? this.getEditableUser('ff_user_dr_out')
                : this.branchOnInit.companyId == 'RWS' || this.branchOnInit.companyId == 'FUN'
                ? this.getEditableUser('ff_user_dr_rws')
                : this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP'
                ? this.isProfessional
                : false;

        if (
            !this.isNew &&
            clientCenterInterlocutorDetail.ShouldReceiveSurveyChk == '0' &&
            (this.branchOnInit.companyId == 'RPS' ||
                this.branchOnInit.companyId == 'VEX' ||
                this.branchOnInit.companyId == 'RWS' ||
                this.branchOnInit.companyId == 'FUN' ||
                this.branchOnInit.companyId == 'RCO' ||
                this.branchOnInit.companyId == 'EXP'
            )
        ) {
            if (this.clientCenterTabs && this.clientCenterTabs.KeyAccountChk == 1) {
                isDisabledShouldReceiveSurveyChk = !this.getEditable('ff_interlocutorClientCenter_surveyChk') || !isKeyAccount;
            } else {
                isDisabledShouldReceiveSurveyChk =
                    !this.getEditable('ff_interlocutorClientCenter_surveyChk') ||
                    (this.branchOnInit.userId != clientCenterInterlocutorDetail.PUserId && !isDistrictManager && !isRegionManager);
            }
        }
        let phone1Validator = [Validators.pattern(this.validatorsRegExPhones.MinValue)];
        let regExMobile = this.validatorsRegExMobile.MinValue;
        regExMobile = regExMobile.replace('{0}', this.validatorsRegExMobileBegin.MinValue);
        regExMobile = regExMobile.replace('{1}', this.validatorsRegExMobileBegin.MaxValue);
        regExMobile = regExMobile.replaceAll('{{', '{');
        regExMobile = regExMobile.replaceAll('}}', '}');
        let phone2MobileValidator = [Validators.pattern(regExMobile)];
        this.msgRegExMobile = this.validatorsRegExMobile.MaxValue;
        this.msgRegExMobile = this.msgRegExMobile.replace('{0}', this.validatorsRegExMobileBegin.MinValue);
        this.msgRegExMobile = this.msgRegExMobile.replace('{1}', this.validatorsRegExMobileBegin.MaxValue);
        let emailValidator = [Validators.maxLength(60), Validators.pattern(this.validatorsRegExEmail.MinValue)];

        let interlocPortalPerm =
            this.isNew ||
            (clientCenterInterlocutorDetail && (!clientCenterInterlocutorDetail.PortalElement || clientCenterInterlocutorDetail.PortalElement == '0')) ||
            this.isSupportCenter ||
            this.isInGeneralParam;
        if (
            clientCenterInterlocutorDetail &&
            clientCenterInterlocutorDetail.PortalElement != null &&
            clientCenterInterlocutorDetail.PortalElement == '0' &&
            this.isActionDetail
        ) {
            let knResp = 0;
            let splitknResp = [];
            let stringknResp = clientCenterInterlocutorDetail.PortalElement;
            if (stringknResp != null && stringknResp != '' && stringknResp != '0') {
                if (stringknResp.includes(',')) {
                    splitknResp = stringknResp.split(',');
                } else {
                    splitknResp.push(stringknResp);
                }
            }
            knResp = parseInt(splitknResp[0]);
            this.showGridEsolution = true;
            this.loadEsolution(knResp);
        } else {
            this.showGridEsolution = false;
        }

        let disabledFiscalDocId = false;
        let disabledfiscalDocNumber = false;
        let disabledDecisor = false;

        if (this.isNewStructure) {
            disabledFiscalDocId =
                !this.getEditable('ff_interlocutorClientCenter_fiscalDocId') ||
                this.isActionDetail ||
                this.blockContrastData ||
                this.blockFiscalDoc ||
                this.isSensitiveData ||
                this.blockCertificateData ||
                !interlocPortalPerm;

            disabledfiscalDocNumber =
                !this.getEditable('ff_interlocutorClientCenter_fiscalDocNumber') ||
                this.isActionDetail ||
                this.blockContrastData ||
                this.blockFiscalDoc ||
                this.isSensitiveData ||
                this.blockCertificateData ||
                !interlocPortalPerm;

            disabledDecisor = this.blockCertificateData || this.blockDecisor;
        } else {
            disabledFiscalDocId = !this.getEditable('ff_interlocutorClientCenter_fiscalDocId') || this.isActionDetail || disabledAll || this.isSensitiveData;
            disabledfiscalDocNumber =
                !this.getEditable('ff_interlocutorClientCenter_fiscalDocNumber') || this.isActionDetail || disabledAll || this.isSensitiveData;
            disabledDecisor =
                this.blockCertificateData ||
                (this.interlocutor != null && this.interlocutor.PortalElement != null && this.interlocutor.PortalElement == '0') ||
                !interlocPortalPerm ||
                this.blockDecisor;
        }

        // Si está en proceso nadie lo podrá tocar
        this.disabledPrincipalChk =
            (!this.isEmployeeTeamLeader && !this.isEmployeeSalesManager) ||
            !this.getEditable('ff_interlocutorClientCenter_principalChk') ||
            this.isActionDetail;

        if (this.iAction && !this.isNewStructure) {
            this.interlocutorForm = this.formBuilder.group({
                interlocutorId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.InterlocutorId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_interlocutorId') || this.isActionDetail || disabledAll
                    }
                ],
                firstName: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.FirstName : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_firstName') ||
                            this.isActionDetail ||
                            disabledAll ||
                            this.blockContrastData ||
                            this.blockContrastDataOther ||
                            this.blockCertificateData ||
                            !interlocPortalPerm
                    },
                    [Validators.maxLength(20)]
                ],
                surname1: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Surname1 : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_surname1') ||
                            this.isActionDetail ||
                            disabledAll ||
                            this.blockContrastData ||
                            this.blockContrastDataOther ||
                            this.blockCertificateData ||
                            !interlocPortalPerm
                    },
                    [Validators.maxLength(25)]
                ],
                surname2: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Surname2 : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_surname2') ||
                            this.isActionDetail ||
                            disabledAll ||
                            this.blockContrastData ||
                            this.blockContrastDataOther ||
                            this.blockCertificateData ||
                            !interlocPortalPerm
                    },
                    [Validators.maxLength(25)]
                ],
                birthDate: [
                    {
                        value: birthDate,
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_birthDate') ||
                            this.isActionDetail ||
                            disabledAll ||
                            this.blockContrastData ||
                            this.blockCertificateData
                    }
                ],
                functionId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.FunctionId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_functionId') || this.isActionDetail || disabledAll
                    },
                    functionIdValidator
                ],
                detailFunction: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.DetailFunction : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_detailFunction') || this.isActionDetail || disabledAll
                    },
                    [Validators.maxLength(70)]
                ],
                fiscalDocId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.FiscalDocId : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_fiscalDocId') ||
                            this.isActionDetail ||
                            disabledAll ||
                            this.blockContrastData ||
                            this.blockFiscalDoc ||
                            this.isSensitiveData ||
                            this.blockCertificateData ||
                            !interlocPortalPerm
                    },
                    fiscalDocIdValidator
                ],
                fiscalDocNumber: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.FiscalDocNumber : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_fiscalDocNumber') ||
                            this.isActionDetail ||
                            disabledAll ||
                            this.blockContrastData ||
                            this.blockFiscalDoc ||
                            this.isSensitiveData ||
                            this.blockCertificateData ||
                            !interlocPortalPerm
                    },
                    [Validators.maxLength(10)]
                ],
                sexId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.SexoId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_sexId') || this.isActionDetail || disabledAll || this.blockCertificateData
                    },
                    sexIdValidator
                ],
                languageId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.LanguageId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_languageId') || this.isActionDetail || disabledAll
                    },
                    languageIdValidator
                ],
                addressId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressId') || this.isActionDetail || disabledAll
                    },
                    addressIdValidator
                ],
                addressStreet: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressStreet : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressStreet') || this.isActionDetail || disabledAll
                    },
                    [Validators.maxLength(30)]
                ],
                addressNumber: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressNumber : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressNumber') || this.isActionDetail || disabledAll
                    },
                    [Validators.maxLength(5)]
                ],
                addressAditional: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressAditional : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressAditional') || this.isActionDetail || disabledAll
                    },
                    [Validators.maxLength(19)]
                ],
                portalElement: [
                    {
                        value:
                            clientCenterInterlocutorDetail && clientCenterInterlocutorDetail.PortalElement != '0'
                                ? clientCenterInterlocutorDetail.PortalElement
                                : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_portalElement') || this.isActionDetail || disabledAll || this.blockCertificateData
                    },
                    [Validators.pattern('^([0-9]{1,9})?$'), Validators.min(1)]
                ],
                addressCountryId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressCountryId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressCountryId') || this.isActionDetail || disabledAll
                    },
                    addressCountryIdValidator
                ],
                addressProvinceId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressProvinceId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressProvinceId') || this.isActionDetail || disabledAll
                    },
                    addressProvinceIdValidator
                ],
                addressCityId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressCityId : '',
                        disabled: true || !this.getEditable('ff_interlocutorClientCenter_addressCityId') || this.isActionDetail || disabledAll
                    },
                    addressCityIdValidator
                ],
                addressZipCode: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressZipCode : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressZipCode') || this.isActionDetail || disabledAll
                    },
                    [Validators.maxLength(10)]
                ],
                phone1: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Phone1 : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_phone1') || this.isActionDetail || this.blockContrastData || this.isSensitiveData
                    },
                    phone1Validator
                ],
                phone2: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Phone2 : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_phone2') ||
                            this.isActionDetail ||
                            this.blockContrastData ||
                            this.isSensitiveData ||
                            this.blockCertificateData ||
                            !interlocPortalPerm
                    },
                    phone2MobileValidator
                ],
                extPhone1: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.ExtPhone1 : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_extPhone1') ||
                            this.isActionDetail ||
                            disabledAll ||
                            this.blockContrastData ||
                            this.isSensitiveData
                    },
                    [Validators.maxLength(6)]
                ],
                email: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Email : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_email') ||
                            this.isActionDetail ||
                            this.blockContrastData ||
                            this.isSensitiveData ||
                            this.blockCertificateData ||
                            !interlocPortalPerm
                    },
                    emailValidator
                ],
                positionId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.PositionInterlocFBIId : '',
                        disabled:
                            (this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                                ? !this.getEditable('ff_interlocutorClientCenter_positionId_rpsvex')
                                : !this.getEditable('ff_interlocutorClientCenter_positionId')) ||
                            this.isActionDetail ||
                            disabledAll
                    },
                    positionIdValidator
                ],
                mailingTypeId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.MailingTypeId : '',
                        disabled:
                            (this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP'
                                ? !this.getEditable('ff_interlocutorClientCenter_mailingTypeId')
                                : this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                                ? !this.getEditable('ff_interlocutorClientCenter_mailingTypeId_out')
                                : this.getEditable('ff_interlocutorClientCenter_mailingTypeId') &&
                                  this.getEditable('ff_interlocutorClientCenter_mailingTypeId_out')) ||
                            this.isActionDetail ||
                            disabledAll
                    },
                    mailingTypeIdValidator
                ],
                contactTypeId: [
                    {
                        value: clientCenterInterlocutorDetail
                            ? clientCenterInterlocutorDetail.ContactTypeId != null
                                ? clientCenterInterlocutorDetail.ContactTypeId.toString()
                                : ''
                            : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_contactTypeId') || this.isActionDetail || disabledAll || !interlocPortalPerm
                    },
                    contactTypeIdValidator
                ],
                hobby1Id: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Hobby1Id : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_hobby1Id') || this.isActionDetail || disabledAll
                    }
                ],
                hobby2Id: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Hobby2Id : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_hobby2Id') || this.isActionDetail || disabledAll
                    }
                ],
                mailingChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.MailingChk : true,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_mailingChk') || this.isActionDetail || disabledAll
                    }
                ],
                comments: [
                    {
                        value:
                            clientCenterInterlocutorDetail && clientCenterInterlocutorDetail.Comments && clientCenterInterlocutorDetail.Comments != null
                                ? clientCenterInterlocutorDetail.Comments
                                : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_comments') || this.isActionDetail || disabledAll
                    },
                    [Validators.maxLength(400)]
                ],
                clientSearchType: [
                    { value: this.defaultSearchType, disabled: !this.getEditable('ff_interlocutorClientCenter_clientSearchType') || this.isActionDetail },
                    [Validators.required]
                ],
                branchId: [
                    { value: this.branchOnInit.id, disabled: !this.getEditable('ff_interlocutorClientCenter_branchId') || !this.isNew },
                    [Validators.required]
                ],
                client: [
                    { value: client, disabled: !this.getEditable('ff_interlocutorClientCenter_client') || !this.isNew || this.isActionDetail },
                    [Validators.required]
                ],
                pUserId: [
                    {
                        value: userId,
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_owner') ||
                            this.isActionDetail ||
                            disabledAll ||
                            (!isTeamLeader && (!this.clientCenterTabs || (this.branchOnInit.userId != this.clientCenterTabs.PUserId && exist)))
                    },
                    pUserIdValidator
                ],
                shouldReceiveSurveyChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.ShouldReceiveSurveyChk : false,
                        disabled: isDisabledShouldReceiveSurveyChk || this.isActionDetail || disabledAll
                    }
                ],
                wantToReceiveASurveyChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.WantToReceiveASurveyChk : false,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_wantToReceiveASurveyChk') || this.isActionDetail || disabledAll
                    }
                ],
                signerChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.SignerChk : false,
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_signerChk') ||
                            this.isActionDetail ||
                            disabledAll ||
                            this.blockContrastData ||
                            this.blockCertificateData ||
                            !this.isSupportCenter ||
                            !interlocPortalPerm
                    }
                ],
                signerBChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.SignerBChk : false,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_signerBChk') || this.isActionDetail || disabledAll
                    }
                ],
                centerCostSeq: [
                    {
                        value:
                            clientCenterInterlocutorDetail && clientCenterInterlocutorDetail.CenterCostSeq != null
                                ? clientCenterInterlocutorDetail.CenterCostSeq.toString()
                                : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_centerCost_ceco') || this.isActionDetail || disabledAll
                    }
                ],
                decisorChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.DecisorChk : false,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_decisorChk') || this.isActionDetail || disabledAll || disabledDecisor
                    }
                ],
                prlChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.PRLChk : false,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_prlChk') || this.isActionDetail || disabledAll
                    }
                ],
                otpTypeId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.OtpTypeId : '',
                        disabled:
                            true ||
                            !this.getEditable('ff_interlocutorClientCenter_otpTypeId') ||
                            this.isActionDetail ||
                            disabledAll ||
                            this.blockContrastData ||
                            this.blockCertificateData
                    },
                    otpTypeIdValidator
                ],
                cexChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.CexChk : false,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_cexChk') || this.isActionDetail || disabledAll
                    }
                ],
                hideSensitiveDataChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.HideSensitiveDataChk : false,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_hideSensitiveDataChk') || this.isActionDetail || disabledAll
                    }
                ],
                typePost: [{ value: this.isNewModeGGCC ? '1' : '0', disabled: !this.getEditable('ff_interlocutorClientCenter_typePostNormal') }],
                interlocutorGGCC: [
                    { value: interlocutorGGCC, disabled: !this.getEditable('ff_interlocutorClientCenter_interlocutorGGCC') || !this.isNewModeGGCC }
                ],
                principalChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.PrincipalChk : false,
                        disabled: this.disabledPrincipalChk
                    }
                ]
            });
        } else {
            let positionId = null;
            if (this.branchOnInit.companyId == 'RWS' && this.isNewStructure) {
                if (clientCenterInterlocutorDetail) {
                    if (clientCenterInterlocutorDetail.PositionInterlocFBIIdList) {
                        positionId = [];
                        clientCenterInterlocutorDetail.PositionInterlocFBIIdList.forEach(pos => {
                            let value = pos.m_Item1 ? pos.m_Item1 : pos.Item1;
                            positionId.push(value);
                        });
                    } else if (clientCenterInterlocutorDetail.PositionInterlocFBIId) {
                        positionId = [];
                        positionId.push(clientCenterInterlocutorDetail.PositionInterlocFBIId);
                    }
                }
            } else {
                positionId = clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.PositionInterlocFBIId : '';
            }

            this.interlocutorForm = this.formBuilder.group({
                interlocutorId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.InterlocutorId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_interlocutorId') || this.isActionDetail || disabledAll
                    }
                ],
                firstName: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.FirstName : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_firstName') ||
                            this.isActionDetail ||
                            this.blockContrastData ||
                            this.blockContrastDataOther ||
                            disabledAll
                    },
                    [Validators.maxLength(20)]
                ],
                surname1: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Surname1 : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_surname1') ||
                            this.isActionDetail ||
                            this.blockContrastData ||
                            this.blockContrastDataOther ||
                            disabledAll
                    },
                    [Validators.maxLength(25)]
                ],
                surname2: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Surname2 : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_surname2') ||
                            this.isActionDetail ||
                            this.blockContrastData ||
                            this.blockContrastDataOther ||
                            disabledAll
                    },
                    [Validators.maxLength(25)]
                ],
                birthDate: [
                    {
                        value: birthDate,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_birthDate') || this.isActionDetail || this.blockContrastData || disabledAll
                    }
                ],
                functionId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.FunctionId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_functionId') || this.isActionDetail || disabledAll
                    },
                    functionIdValidator
                ],
                detailFunction: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.DetailFunction : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_detailFunction') || this.isActionDetail || disabledAll
                    },
                    [Validators.maxLength(70)]
                ],
                fiscalDocId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.FiscalDocId : '',
                        disabled: disabledFiscalDocId || this.blockContrastData
                    },
                    fiscalDocIdValidator
                ],
                fiscalDocNumber: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.FiscalDocNumber : '',
                        disabled: disabledfiscalDocNumber || this.blockContrastData
                    },
                    [Validators.maxLength(10)]
                ],
                sexId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.SexoId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_sexId') || this.isActionDetail || disabledAll
                    },
                    sexIdValidator
                ],
                languageId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.LanguageId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_languageId') || this.isActionDetail || disabledAll
                    },
                    languageIdValidator
                ],
                addressId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressId') || this.isActionDetail
                    },
                    addressIdValidator
                ],
                addressStreet: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressStreet : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressStreet') || this.isActionDetail
                    },
                    [Validators.maxLength(30)]
                ],
                addressNumber: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressNumber : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressNumber') || this.isActionDetail
                    },
                    [Validators.maxLength(5)]
                ],
                addressAditional: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressAditional : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressAditional') || this.isActionDetail
                    },
                    [Validators.maxLength(19)]
                ],
                portalElement: [
                    {
                        value:
                            clientCenterInterlocutorDetail && clientCenterInterlocutorDetail.PortalElement != '0'
                                ? clientCenterInterlocutorDetail.PortalElement
                                : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_portalElement') || this.isActionDetail || disabledAll || this.blockCertificateData
                    },
                    [Validators.pattern('^([0-9]{1,9})?$'), Validators.min(1)]
                ],
                addressCountryId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressCountryId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressCountryId') || this.isActionDetail
                    },
                    addressCountryIdValidator
                ],
                addressProvinceId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressProvinceId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressProvinceId') || this.isActionDetail
                    },
                    addressProvinceIdValidator
                ],
                addressCityId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressCityId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressCityId') || this.isActionDetail
                    },
                    addressCityIdValidator
                ],
                addressZipCode: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressZipCode : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressZipCode') || this.isActionDetail
                    },
                    [Validators.maxLength(10)]
                ],
                phone1: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Phone1 : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_phone1') || this.isActionDetail || this.blockContrastData || this.isSensitiveData
                    },
                    phone1Validator
                ],
                phone2: [
                    {
                        value: clientCenterInterlocutorDetail
                            ? this.isNewStructure
                                ? clientCenterInterlocutorDetail.MobilePhone
                                : clientCenterInterlocutorDetail.Phone2
                            : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_phone2') || this.isActionDetail || this.blockContrastData || this.isSensitiveData
                    },
                    phone2MobileValidator
                ],
                extPhone1: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.ExtPhone1 : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_extPhone1') ||
                            this.isActionDetail ||
                            disabledAll ||
                            this.blockContrastData ||
                            this.isSensitiveData
                    },
                    [Validators.maxLength(6)]
                ],
                email: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Email : '',
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_email') || this.isActionDetail || this.blockContrastData || this.isSensitiveData
                    },
                    emailValidator
                ],
                positionId: [
                    {
                        value: positionId,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_positionId') || this.isActionDetail || disabledAll || this.isEdit
                    },
                    positionIdValidator
                ],
                mailingTypeId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.MailingTypeId : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_mailingTypeId') || this.isActionDetail || disabledAll
                    },
                    mailingTypeIdValidator
                ],
                mailingChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.MailingChk : true,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_mailingChk') || this.isActionDetail || disabledAll
                    }
                ],
                comments: [
                    {
                        value:
                            clientCenterInterlocutorDetail && clientCenterInterlocutorDetail.Comments && clientCenterInterlocutorDetail.Comments != null
                                ? clientCenterInterlocutorDetail.Comments
                                : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_comments') || this.isActionDetail || disabledAll
                    },
                    [Validators.maxLength(400)]
                ],
                clientSearchType: [
                    { value: this.defaultSearchType, disabled: !this.getEditable('ff_interlocutorClientCenter_clientSearchType') || this.isActionDetail },
                    [Validators.required]
                ],
                branchId: [
                    { value: this.branchOnInit.id, disabled: !this.getEditable('ff_interlocutorClientCenter_branchId') || !this.isNew },
                    [Validators.required]
                ],
                pUserId: [
                    {
                        value: userId,
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_owner') ||
                            this.isActionDetail ||
                            disabledAll ||
                            (!isTeamLeader && (!this.clientCenterTabs || (this.branchOnInit.userId != this.clientCenterTabs.PUserId && exist)))
                    },
                    pUserIdValidator
                ],
                shouldReceiveSurveyChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.ShouldReceiveSurveyChk : false,
                        disabled: this.clientCenterTabs == null || isDisabledShouldReceiveSurveyChk || this.isActionDetail || disabledAll
                    }
                ],
                contactTypeId: [
                    {
                        value: clientCenterInterlocutorDetail
                            ? clientCenterInterlocutorDetail.ContactTypeId != null
                                ? clientCenterInterlocutorDetail.ContactTypeId.toString()
                                : ''
                            : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_status') || !this.isActionDetail || disabledAll || !interlocPortalPerm
                    },
                    contactTypeIdValidator
                ],
                hobby1Id: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Hobby1Id : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_hobby1Id') || this.isActionDetail || disabledAll
                    }
                ],
                hobby2Id: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.Hobby2Id : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_hobby2Id') || this.isActionDetail || disabledAll
                    }
                ],
                addressBlock: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressBlock : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressBlock') || this.isActionDetail
                    },
                    Validators.maxLength(10)
                ],
                addressStair: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressStair : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressStair') || this.isActionDetail
                    },
                    Validators.maxLength(10)
                ],
                addressFloor: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressFloor : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_addressFloor') || this.isActionDetail
                    },
                    Validators.maxLength(10)
                ],
                letter: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.AddressDoor : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_letter') || this.isActionDetail
                    },
                    Validators.maxLength(3)
                ],
                signerChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.SignerChk : false,
                        disabled:
                            !this.getEditable('ff_interlocutorClientCenter_signerChk') ||
                            this.isActionDetail ||
                            disabledAll ||
                            this.blockContrastData ||
                            this.blockCertificateData ||
                            (!this.isSupportCenter && !interlocPortalPerm)
                    }
                ],
                prlChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.PRLChk : false,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_prlChk') || this.isActionDetail || disabledAll
                    }
                ],
                cexChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.CexChk : false,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_cexChk') || this.isActionDetail || disabledAll
                    }
                ],
                signerBChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.SignerBChk : false,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_signerBChk') || this.isActionDetail || disabledAll
                    }
                ],
                otpTypeId: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.OtpTypeId : '',
                        disabled:
                            true ||
                            !this.getEditable('ff_interlocutorClientCenter_otpTypeId') ||
                            this.isActionDetail ||
                            disabledAll ||
                            this.blockContrastData ||
                            this.blockCertificateData
                    },
                    otpTypeIdValidator
                ],
                centerCostSeq: [
                    {
                        value:
                            clientCenterInterlocutorDetail && clientCenterInterlocutorDetail.CenterCostSeq != null
                                ? clientCenterInterlocutorDetail.CenterCostSeq.toString()
                                : '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_centerCost_ceco') || this.isActionDetail || disabledAll
                    }
                ],
                decisorChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.DecisorChk : false,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_decisorChk') || this.isActionDetail || disabledAll || disabledDecisor
                    }
                ],
                wantToReceiveASurveyChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.WantToReceiveASurveyChk : false,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_wantToReceiveASurveyChk') || this.isActionDetail || disabledAll
                    }
                ],
                client: [{ value: client, disabled: !this.getEditable('ff_interlocutorClientCenter_client') || this.isActionDetail }],
                clientId: [
                    {
                        value: '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_clientIdSearch')
                    }
                ],
                relationTypeId: [
                    {
                        value: this.relationDefault,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_relationTypeId') || this.isActionDetail
                    }
                ],
                relationTypeValue: [
                    {
                        value: '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_relationTypeValue') || this.isActionDetail || this.isEdit
                    }
                ],
                relationRandstadValue: [
                    {
                        value: '',
                        disabled: !this.getEditable('ff_interlocutorClientCenter_relationRandstadValue') || this.isActionDetail || disabledAll
                    }
                ],
                hideSensitiveDataChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.HideSensitiveDataChk : false,
                        disabled: !this.getEditable('ff_interlocutorClientCenter_hideSensitiveDataChk') || this.isActionDetail || disabledAll
                    }
                ],
                typePost: [{ value: this.isNewModeGGCC ? '1' : '0', disabled: !this.getEditable('ff_interlocutorClientCenter_typePostNormal') }],
                interlocutorGGCC: [
                    { value: interlocutorGGCC, disabled: !this.getEditable('ff_interlocutorClientCenter_interlocutorGGCC') || !this.isNewModeGGCC }
                ],
                principalChk: [
                    {
                        value: clientCenterInterlocutorDetail ? clientCenterInterlocutorDetail.PrincipalChk : false,
                        disabled: this.disabledPrincipalChk
                    }
                ]
            });

            if (this.isNewStructure && (this.isNew || this.isEdit)) {
                this.token = JSON.parse(localStorage.getItem('apiToken'));
                this.tokenInfo = this.sharedService.getTokenInfo(this.token.access_token);

                let disabled = this.contactPersonsRelsTypesList.length == 1;
                if (disabled) {
                    this.interlocutorForm.get('relationTypeId').disable();
                }

                let value = this.valuesForRelationRandstad.length == 1 ? this.valuesForRelationRandstad[0].value.toString() : '';
                let exists = this.valuesForRelationRandstad.filter(x => x.key == this.tokenInfo.nameid)[0];

                if (value == '' && exists) {
                    value = exists.value.toString();
                }

                this.interlocutorForm.get('relationRandstadValue').setValue(value);
                this.interlocutorForm.get('relationRandstadValue').updateValueAndValidity();

                disabled = this.contactPersonsRelsTypesList.length == 1;
                if (disabled) {
                    this.interlocutorForm.get('relationRandstadValue').disable();
                }
            }
        }

        this.validPhone = true;

        if (
            !this.isActionDetail &&
            ((this.interlocutorForm.get('phone1').value != '' && this.interlocutorForm.get('phone1').value != null) ||
                (this.interlocutorForm.get('phone2').value != '' && this.interlocutorForm.get('phone2').value != null) ||
                (this.interlocutorForm.get('email').value != '' && this.interlocutorForm.get('email').value != null))
        ) {
            this.enabledAll();
        }

        if (this.iAction && !this.isNewStructure) {
            if (!this.isActionDetail && this.disabledFirst) {
                if (this.interlocutorForm.get('hobby1Id').value == null || this.interlocutorForm.get('hobby1Id').value == '') {
                    this.interlocutorForm.get('hobby2Id').disable();
                } else {
                    this.interlocutorForm.get('hobby2Id').enable();
                }
            }

            if ((this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX') && this.interlocutorForm.get('functionId').value == '74') {
                this.interlocutorForm.get('signerChk').setValue(true);
                this.interlocutorForm.get('signerChk').disable();
            }
        }

        if (
            (this.branchOnInit.companyId == 'RPS' ||
                this.branchOnInit.companyId == 'VEX' ||
                this.branchOnInit.companyId == 'RWS' ||
                this.branchOnInit.companyId == 'FUN') &&
            (this.interlocutorForm.get('signerChk').value == true || this.interlocutorForm.get('functionId').value == '74') &&
            !this.isActionDetail
        ) {
            this.requiredFiscalDoc = '*';
        }

        this.isPortalSigner =
            this.interlocutorForm.get('signerChk').value == true &&
            clientCenterInterlocutorDetail.PortalElement != '0' &&
            clientCenterInterlocutorDetail.PortalElement != null;

        setTimeout(() => {
            if (this.isGgcc && this.isKam) {
                this.interlocutorForm.get('hideSensitiveDataChk').enable();
            } else {
                this.interlocutorForm.get('hideSensitiveDataChk').disable();
            }

            if (this.principalChkSwitchToggles) {
                this.principalChkSwitchToggles.toggleElement.nativeElement.checked = this.interlocutorForm.get('principalChk').value;
                this.principalChkSwitchToggles.toggleElement.nativeElement.disabled = this.disabledPrincipalChk;
                this.principalChkSwitchToggles.toggleText = this.interlocutorForm.get('principalChk').value ? 'Usuario Principal' : 'Usuario Proceso';
            }
        });
    }

    resetForm() {
        if (this.interlocutorForm) {
            for (const key in this.interlocutorForm.controls) {
                this.interlocutorForm.controls[key].disable();
            }

            this.interlocutorForm = undefined;
        }
    }

    public setSpinner(busy: boolean) {
        if (this.iAction) this.oParentBusyEvent.emit(busy);
        else this.busy = busy;
    }

    private setInterlocutorHeader(title: string, isNewTitle: boolean = false) {
        if (isNewTitle) {
            if (this.clientId && this.clientCenterId && this.clientCenterTabs) {
                this.title = `${title}: ${this.clientId}.${this.clientCenterId} ${this.clientCenterTabs.ClientCenterName}`;
            } else {
                this.title = title;
            }
        } else if (this?.interlocutor?.AllName) {
            this.title = `${title}: ${this.interlocutor.AllName}`;
        } else {
            this.title = title;
        }
        this.titleService.setTitle(this.title);
    }

    ggccChkStatusClick(event: Event) {
        let isDistrictManager =
            this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                ? this.getEditableUser('ff_user_dz_out')
                : this.branchOnInit.companyId == 'RWS' || this.branchOnInit.companyId == 'FUN'
                ? this.getEditableUser('ff_user_dz_rws')
                : this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP'
                ? this.isProfessional
                : false;

        let isRegionManager =
            this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                ? this.getEditableUser('ff_user_dr_out')
                : this.branchOnInit.companyId == 'RWS' || this.branchOnInit.companyId == 'FUN'
                ? this.getEditableUser('ff_user_dr_rws')
                : this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP'
                ? this.isProfessional
                : false;

        let isKeyAccount =
            this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                ? this.getEditableUser('ff_user_ka_out')
                : this.branchOnInit.companyId == 'RWS' || this.branchOnInit.companyId == 'FUN'
                ? this.getEditableUser('ff_user_ka_rws')
                : this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP'
                ? this.isProfessional
                : false;

        if (this.clientCenterTabs && this.interlocutorForm.get('shouldReceiveSurveyChk').value == 1) {
            if (this.clientCenterTabs.KeyAccountChk == 1 && !this.isGgcc && !isKeyAccount) {
                this.sharedService.toastError('Este centro es GGCC. El check sólo lo puede desmarcar Coordinación GGCC');
                event.preventDefault();
            } else if (this.clientCenterTabs.KeyAccountChk == 0 && (!isDistrictManager && !isRegionManager) && this.interlocutor) {
                let changeOriginal = this.interlocutor.ShouldReceiveSurveyChk == '1';
                if (changeOriginal && !isDistrictManager) {
                    this.sharedService.toastError('Este check solo lo puede desmarcar el DZ');
                    event.preventDefault();
                } else if (changeOriginal && !isRegionManager) {
                    this.sharedService.toastError('Este check solo lo puede desmarcar el DR');
                    event.preventDefault();
                }
            }
        }
    }

    async setClientCenter(client: string): Promise<void> {
        this.setSpinner(true);

        this.interlocutorForm.get('client').reset();
        this.interlocutorForm.get('client').disable();
        this.interlocutorForm.get('client').setValue('');
        this.clientCenterClearControls();
        if (client != '') {
            let existClient = false;
            let splitClient = client.split(' - ');

            this.clientId = parseInt(splitClient[0]);
            this.clientCenterId = parseInt(splitClient[1]);

            await this.centersService
                .getClientCenterTabs(parseInt(splitClient[0]), parseInt(splitClient[1]))
                .then(async data => {
                    this.clientCenterTabs = data;

                    let isTeamLeader = this.getEditableUser('ff_user_teamLeader_prof');
                    let userId = this.isNewStructure ? data.PUserId : this.interlocutor ? this.interlocutor.PUserId : '';
                    let exist = true;

                    if (!this.isActionDetail) {
                        userId = !userId || userId == null || userId == '' ? this.branchOnInit.userId : userId;
                        exist = this.interlocutorsOwners.filter(x => x.value == userId).length > 0;
                    }

                    if (
                        this.getEditable('ff_interlocutorClientCenter_owner') &&
                        !this.isNewStructure &&
                        (isTeamLeader || (this.clientCenterTabs && (this.branchOnInit.userId == this.clientCenterTabs.PUserId || !exist)))
                    ) {
                        this.interlocutorForm.get('pUserId').enable();
                    } else {
                        this.interlocutorForm.get('pUserId').reset();
                        this.interlocutorForm.get('pUserId').disable();
                        this.interlocutorForm.get('pUserId').setValue(userId);
                    }

                    if (this.isNewStructure) {
                        existClient = true;
                        this.interlocutorForm.get('addressId').setValue(this.clientCenterTabs.AddressId);
                        this.interlocutorForm.get('addressStreet').setValue(this.clientCenterTabs.AddressStreet);
                        this.interlocutorForm.get('addressNumber').setValue(this.clientCenterTabs.AddressNumber);
                        this.interlocutorForm.get('addressAditional').setValue(this.clientCenterTabs.AddressAditional);
                        this.interlocutorForm.get('addressCountryId').setValue(this.clientCenterTabs.AddressCountryId);
                        this.checkProvince(this.clientCenterTabs.AddressCountryId);
                        this.interlocutorForm.get('addressProvinceId').setValue(this.clientCenterTabs.AddressProvinceId);
                        this.checkCity(this.clientCenterTabs.AddressProvinceId);
                        this.interlocutorForm.get('addressCityId').setValue(this.clientCenterTabs.AddressCityId);
                        this.interlocutorForm.get('addressZipCode').setValue(this.clientCenterTabs.AddressZipCode);
                    } else {
                        this.clientCenterList.forEach(client => {
                            let splitValue = client.value.split(' - ');
                            if (splitClient[0] == splitValue[0] && splitClient[1] == splitValue[1]) {
                                existClient = true;
                                this.interlocutorForm.get('addressId').setValue(client.addressId);
                                this.interlocutorForm.get('addressStreet').setValue(client.addressStreet);
                                this.interlocutorForm.get('addressNumber').setValue(client.addressNumber);
                                this.interlocutorForm.get('addressAditional').setValue(client.addressAditional);
                                this.interlocutorForm.get('addressCountryId').setValue(client.addressCountryId);
                                this.checkProvince(client.addressCountryId);
                                this.interlocutorForm.get('addressProvinceId').setValue(client.addressProvinceId);
                                this.checkCity(client.addressProvinceId);
                                this.interlocutorForm.get('addressCityId').setValue(client.addressCityId);
                                this.interlocutorForm.get('addressZipCode').setValue(client.addressZipCode);
                            }
                        });
                    }

                    if (existClient) {
                        this.interlocutorForm.get('client').setValue(client);
                        if (this.branchOnInit.companyId == 'RWS' || this.branchOnInit.companyId == 'FUN') {
                            await this.centersService
                                .getCentersCosts(this.clientId, this.clientCenterId, true)
                                .then(data => {
                                    this.cecoList = data;
                                })
                                .catch(error => {
                                    this.sharedService.showError(error);
                                    this.setSpinner(false);
                                });
                        }
                    }
                })
                .catch(error => {
                    this.setSpinner(false);
                    this.sharedService.showError(error);
                });
        } else {
            this.clientCenterTabs = undefined;
        }

        if (this.isNew) {
            this.interlocutorForm.get('client').enable();
        }
        this.interlocutorForm.get('client').updateValueAndValidity();

        this.setSpinner(false);
    }

    async getClientCenter(searchType: string, branchId: string, showBranch: boolean): Promise<any> {
        this.setSpinner(true);
        this.showBranch = showBranch;

        if (!showBranch) {
            branchId = this.branchOnInit.id;
            this.interlocutorForm.get('branchId').setValue(branchId);
        }

        if (searchType == '2') {
            await this.setClientCenter('');

            let params = [];

            if ((this.branchOnInit.companyId == 'RCO' && this.branchOnInit.productId == '0007') || this.branchOnInit.companyId == 'EXP') {
                params.push({ companyId: 'RCO', brandId: 'PRO' });
                params.push({ companyId: 'EXP', brandId: 'EXP' });
            } else {
                params.push({ companyId: this.branchOnInit.companyId, brandId: this.branchOnInit.brandId });
            }

            await this.getMultiBranches(params)
                .then(async data => {
                    this.branchList = [];
                    data.forEach((response: any) => {
                        response.forEach(branch => {
                            this.branchList.push(branch);
                        });
                    });
                    await this.getClientCenter('0', this.interlocutorForm.get('branchId').value, true);
                })
                .catch(error => {
                    this.setSpinner(false);
                    this.sharedService.showError(error);
                });
        } else {
            if (this.getVisible('ff_interlocutorClientCenter_panelDataCenter') && this.isNew && !this.isActionDetail) {
                this.clientCenterList = [];

                this.centersService
                    .getCenterClientsBySearchType(branchId, searchType)
                    .then(async data => {
                        this.clientCenterList = data;

                        if (this.iAction) {
                            await this.setClientCenter(`${this.clientId.toString()} - ${this.clientCenterId.toString()}`);
                        }

                        this.setSpinner(false);
                    })
                    .catch(error => {
                        this.setSpinner(false);
                        this.sharedService.showError(error);
                    });
            }
        }
    }

    async getMultiBranches(params: any) {
        let promiseList = [];

        params.forEach(param => {
            promiseList.push(this.centersService.getBranches(param.companyId, param.brandId));
        });

        return await forkJoin(promiseList).toPromise();
    }

    checkDecisor(model: any) {
        if (
            (this.clientCenterTabs.CompanyId == 'RWS' || this.clientCenterTabs.CompanyId == 'FUN') &&
            model.decisorChk &&
            this.validationsData &&
            this.validationsData.OtherDecisorName != null &&
            this.validationsData.OtherDecisorName != ''
        ) {
            this.currentModel = model;
            this.moreDialog = true;
            this.currentDialog = 'modalDialogDecisor';
            this.dialogDecisorMsg = 'Este cliente ya tiene un Decisor HR Portal seleccionado (' + this.validationsData.OtherDecisorName + ')';

            this.dialogInterlocDecisor.open();
        } else {
            this.moreDialog = false;
            this.saveDataAfterValidations(model);
        }
    }

    resetVariables() {
        this.validEmailSignerBChk = true;
        this.validCheck = true;
        this.validCheckFiscNumber = true;
        this.validSameHobby = true;
        this.disabledFirst = false;
        this.requiredFiscalDoc = '';
        this.validFiscalDocFilled = true;
        this.validFiscalDocDecisor = true;
        this.validSurname2Decisor = true;
        this.requiredFiscalDocDecisor = false;
        this.requiredSurname2Decisor = false;
        this.blockContrastData = false;
        this.blockFiscalDoc = false;
        this.blockCertificateData = false;
        this.isNewModeGGCC = false;
        this.validFiscalDocLenght = true;
        this.validFiscalDocLetter = true;
        this.validFiscalDocFormat = true;
        this.validAddressZipCodeSpain = true;
        this.validAddressZipCodeSpainExist = true;
        this.validEmail = true;
        this.validPhone = true;
        this.requiredProvince = false;
        this.requiredCity = false;
    }

    setDefaultValues() {
        // Valores por defecto en el alta de interlocutor
        this.interlocutorForm.get('mailingTypeId').setValue('2');
        this.interlocutorForm.get('shouldReceiveSurveyChk').setValue(1);
        this.interlocutorForm.get('otpTypeId').setValue('1');

        if (
            this.branchOnInit.companyId == 'RPS' ||
            this.branchOnInit.companyId == 'VEX' ||
            this.branchOnInit.companyId == 'RWS' ||
            this.branchOnInit.companyId == 'FUN'
        ) {
            this.interlocutorForm.get('wantToReceiveASurveyChk').setValue(1);
            this.interlocutorForm.get('contactTypeId').setValue('1');
            if (this.isNewStructure) {
                this.interlocutorForm.get('relationTypeId').setValue(this.relationDefault);
            }
        }

        if (this.branchOnInit.companyId != 'RWS') {
            this.interlocutorForm.get('languageId').setValue('S');
        }
    }

    setDefaultAddress() {
        this.interlocutorForm.get('addressId').setValue(this.clientCenterTabs.AddressId);
        this.interlocutorForm.get('addressStreet').setValue(this.clientCenterTabs.AddressStreet);
        this.interlocutorForm.get('addressNumber').setValue(this.clientCenterTabs.AddressNumber);
        this.interlocutorForm.get('addressAditional').setValue(this.clientCenterTabs.AddressAditional);
        this.interlocutorForm.get('addressCountryId').setValue(this.clientCenterTabs.AddressCountryId);
        this.interlocutorForm.get('addressProvinceId').setValue(this.clientCenterTabs.AddressProvinceId);
        this.interlocutorForm.get('addressCityId').setValue(this.clientCenterTabs.AddressCityId);
        this.interlocutorForm.get('addressZipCode').setValue(this.clientCenterTabs.AddressZipCode);

        if (this.interlocutorForm.get('addressCountryId').value != '11') {
            this.requiredProvince = false;
            this.clearFormField('addressProvinceId');

            this.requiredCity = false;
            this.clearFormField('addressCityId');
        } else {
            this.checkCity(this.interlocutorForm.get('addressProvinceId').value);
        }
    }

    async getClientCenterInterlocsGGCC(showInterlocsGGCC: boolean): Promise<void> {
        this.setSpinner(true);

        this.resetVariables();
        this.ref.detectChanges();

        this.isNewModeGGCC = showInterlocsGGCC;

        if (showInterlocsGGCC) {
            if (!this.isNewStructure) {
                await this.centersService
                    .getClientsCentersInterlocutorsBranch(this.ggccBranchId, 1)
                    .then(data => {
                        this.interlocutorGGCCList = data;
                    })
                    .catch(error => {
                        this.sharedService.showError(error);
                    });
            } else {
                await this.centersService
                    .getClientsCentersContactPersonsBranch(this.ggccBranchId, 1)
                    .then(data => {
                        this.interlocutorGGCCList = data;
                    })
                    .catch(error => {
                        this.sharedService.showError(error);
                    });
            }
        }

        this.resetForm();
        this.ref.detectChanges();
        this.interlocutor = undefined;
        this.initForm(this.interlocutor);
        this.ref.detectChanges();

        if (this.isNewModeGGCC) {
            this.interlocutorForm.get('interlocutorGGCC').enable();
            this.interlocutorForm.get('typePost').enable();
            this.interlocutorForm.get('typePost').setValue('1');
            this.interlocutorForm.get('phone1').disable();
            this.interlocutorForm.get('phone2').disable();
            this.interlocutorForm.get('email').disable();
            this.hideSaveGGCCSensitive = true;
        } else {
            this.interlocutorForm.get('interlocutorGGCC').disable();
            this.interlocutorForm.get('interlocutorGGCC').setValue('');
            this.interlocutorForm.get('typePost').enable();
            this.interlocutorForm.get('typePost').setValue('0');
            this.hideSaveGGCCSensitive = false;
            this.setDefaultAddress();
        }

        this.setSpinner(false);
    }

    async changeGetInterlocutorGGCC(interlocutorGGCC?: any): Promise<any> {
        this.setSpinner(true);

        // Extraemos los parametros del combo para enviar al api de detalle de interlocutor
        let interlocutorIdGGCC = this.interlocutorGGCCList.find(x => x.value == this.interlocutorForm.get('interlocutorGGCC').value).interlocutorId;
        let clientIdGGCC = this.interlocutorGGCCList.find(x => x.value == this.interlocutorForm.get('interlocutorGGCC').value).clientId;
        let clientCenterIdGGCC = this.interlocutorGGCCList.find(x => x.value == this.interlocutorForm.get('interlocutorGGCC').value).clientcenterid;

        await this.centersService
            .getClientCenterInterlocutorDetails(clientIdGGCC, clientCenterIdGGCC, interlocutorIdGGCC)
            .then(async data => {
                this.interlocutor = data;
                this.interlocutor.GGCCInterlocutorId = interlocutorIdGGCC;
                this.interlocutor.GGCCClientId = clientIdGGCC;
                this.interlocutor.GGCCClientCenterId = clientCenterIdGGCC;

                this.resetForm();
                this.ref.detectChanges();
                this.initForm(this.interlocutor);
                this.ref.detectChanges();
                this.ref.detectChanges();

                if (this.interlocutor.AddressProvinceId && this.interlocutor.AddressProvinceId != null && this.interlocutor.AddressProvinceId != '') {
                    await this.checkCity(this.interlocutor.AddressProvinceId);
                }

                if (this.interlocutor.HideSensitiveDataChk) {
                    for (const key in this.interlocutorForm.controls) {
                        this.interlocutorForm.get(key).clearValidators();
                        this.interlocutorForm.get(key).disable();
                        this.interlocutorForm.get(key).updateValueAndValidity();
                    }

                    this.interlocutorForm.get('interlocutorGGCC').enable();
                    this.interlocutorForm.get('typePost').enable();
                }

                this.hideSaveGGCCSensitive = false;
                this.setSpinner(false);
            })
            .catch(error => {
                this.setSpinner(false);
                this.sharedService.showError(error);
            });
    }

    saveDataAfterValidations(model: any) {
        if (this.isNew) {
            // Si estamos en modo alta interlocutor GGCC con datos sensibles parseamos los datos necesarios
            if (this.isNewModeGGCC) {
                // Cargamos los datos necesarios para diferenciar en el alta en back que es de GGCC
                model.GGCCInterlocutorId = this.interlocutorGGCCList.find(x => x.value == this.interlocutorForm.get('interlocutorGGCC').value).interlocutorId;
                model.GGCCClientId = this.interlocutorGGCCList.find(x => x.value == this.interlocutorForm.get('interlocutorGGCC').value).clientId;
                model.GGCCClientCenterId = this.interlocutorGGCCList.find(x => x.value == this.interlocutorForm.get('interlocutorGGCC').value).clientcenterid;
                // Cargamos si es datos sensibles el interlocutor
                model.HideSensitiveDataChk = this.interlocutor.HideSensitiveDataChk;
                // Para evitar la validación de modelo en back (por los datos sensibles)
                model.FiscalDocId = '';
            } else {
                model.GGCCInterlocutorId = 0;
                model.GGCCClientId = '0';
                model.GGCCClientCenterId = '0';
            }
            this.centersService
                .postClientCenterInterlocutor(model, this.branchOnInit.id)
                .then(data => {
                    this.sharedService.toastSuccess(data.MessageOK);
                    let lastInterlocutorId = data.DataId.split('/')[2];
                    this.clientId = this.iClientId;
                    this.clientCenterId = this.iClientCenterId;
                    this.oCallbackSaveEvent.emit({ InterlocutorId: lastInterlocutorId, ContactPersonRelId: '' });
                })
                .catch(error => {
                    this.sharedService.showError(error);
                    this.setSpinner(false);
                });
        } else {
            this.centersService
                .putClientCenterInterlocutor(model, this.branchOnInit.id, this.changeStatusCenter)
                .then(async data => {
                    this.sharedService.toastSuccess(data.MessageOK);
                    let lastInterlocutorId = data.DataId.split('/')[2];
                    this.oCallbackSaveEvent.emit({ InterlocutorId: lastInterlocutorId, ContactPersonRelId: '' });
                })
                .catch(error => {
                    this.sharedService.showError(error);
                    this.setSpinner(false);
                });
        }
    }

    cancelInterlocutor() {
        this.setSpinner(true);

        if (this.isNewStructure) {
            this.centersService
                .cancelClientCenterContactPerson(this.interlocutor.InterlocutorId, this.interlocutor.UserId)
                .then(dataCancelContactPerson => {
                    this.sharedService.toastSuccess(dataCancelContactPerson.MessageOK);

                    setTimeout(() => {
                        window.location.reload();
                    }, 500);
                })
                .catch(error => {
                    //Ocultar spinner
                    this.setSpinner(false);

                    this.sharedService.showError(error);
                    this.busy = false;
                });
        } else {
            this.centersService
                .cancelClientCenterInterlocutor(this.clientId, this.clientCenterId, this.interlocutorId, this.changeStatusCenter)
                .then(async data => {
                    let message = data.MessageOK;

                    this.sharedService.toastSuccess(message);

                    setTimeout(() => {
                        this.zone.run(() => this.router.navigate(['interlocutors']));
                    }, 500);
                })
                .catch(error => {
                    this.setSpinner(false);
                    this.sharedService.showError(error);
                });
        }
    }

    backToSearch() {
        if (this.iAction) {
            this.oCancelEvent.emit();
        } else {
            this.zone.run(() =>
                this.isActionDetail || this.isNew
                    ? this.router.navigate(['interlocutors'])
                    : this.router.navigate(
                          ['clients/' + this.clientId + '/centers/' + this.clientCenterId + '/interlocutors/' + this.interlocutorId + '/detail'],
                          {
                              queryParams: {
                                  contactPersonRelId: this.contactPersonRelId
                              }
                          }
                      )
            );
        }
    }

    checkPpalInterloc(model: any) {
        if (this.isNew && this.iClientCenterInterlocutorList.length >= 1) {
            this.currentModel = model;
            this.moreDialog = true;
            this.currentDialog = 'modalDialogPrincipal';
            this.dialogInterlocutorPpal.open();
        } else {
            this.moreDialog = false;
            this.checkDecisor(model);
        }
    }

    saveData(model: any) {
        this.setSpinner(true);
        let isSelectedGGCC = false;

        if (!this.isNewStructure) {
            isSelectedGGCC =
                this.interlocutorForm.get('interlocutorGGCC').value != undefined &&
                this.interlocutorForm.get('interlocutorGGCC').value != null &&
                this.interlocutorForm.get('interlocutorGGCC').value != '';
        } else {
            model.MobilePhone = model.phone2;
            model.phone2 = null;
            if (this.iAction == 'relation') {
                model.branchId = this.clientCenterTabs.BranchId;
            }
        }

        // Si estamos en modo alta GGCC no validamos el formulario (por los datos sensibles)
        let valForm = this.iAction && this.isNewModeGGCC && isSelectedGGCC ? true : this.validateSaveForm();
        if (valForm) {
            if (model.client.indexOf('-') > 0) {
                let clientCenter = model.client.split('-');

                model.clientId = clientCenter[0].trim();
                model.clientCenterId = clientCenter[1].trim();
            }

            if (this.iAction && !this.isNewStructure) {
                if (this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP') {
                    model.contactTypeId = model.mailingTypeId == 4 ? 9 : 1;
                    model.contactTypeChk = model.mailingTypeId == 4 ? 0 : 1;
                }
            } else {
                if (!this.isNewStructure) {
                    model.contactTypeId = model.mailingTypeId == 4 ? 9 : 1;
                }
                model.contactTypeChk = model.mailingTypeId == 4 ? 0 : 1;
            }

            if (this.branchOnInit.companyId == 'RWS' && this.isNewStructure) {
                model.positionInterlocFBIIdList = [];
                model.positionId.forEach(pos => {
                    /********************
                     ***** .NET4.5 *****
                     ********************/
                    //model.positionInterlocFBIIdList.push({ m_Item1: pos, m_Item2: '' });

                    /********************
                     ****** .NET5 ******
                     ********************/
                    model.positionInterlocFBIIdList.push({ Item1: pos, Item2: '', m_Item1: pos, m_Item2: '' });
                });
            } else {
                model.positionInterlocFBIId = model.positionId;
            }

            model.sexoId = model.sexId;
            model.birthDate = model.birthDate != null ? this.sharedService.dateToString(model.birthDate) : '';
            model.firstName = model.firstName != null ? model.firstName.trim() : '';
            model.surname1 = model.surname1 != null ? model.surname1.trim() : '';
            model.surname2 = model.surname2 != null ? model.surname2.trim() : '';

            if (this.iAction && !this.isNewStructure) {
                if (this.isNew) {
                    model.interlocutorId = 0;
                } else {
                    model.interlocutorId = this.interlocutor.InterlocutorId;
                }

                if (this.clientCenterTabs.CompanyId == 'RWS' || this.clientCenterTabs.CompanyId == 'FUN') {
                    if (!this.isNewStructure) {
                        this.centersService
                            .getInterlocutorValidations(model)
                            .then(data => {
                                this.validationsData = data;
                                if (!model.cexChk && data.CexChk) {
                                    this.currentModel = model;
                                    this.currentDialog = 'modalDialogCex';
                                    this.dialogInterlocutorCex.open();
                                } else {
                                    this.checkPpalInterloc(model);
                                }
                            })
                            .catch(error => {
                                this.sharedService.showError(error);
                                this.setSpinner(false);
                            });
                    } else {
                        this.centersService
                            .getContactPersonValidations(model)
                            .then(data => {
                                this.validationsData = data;
                                if (!model.cexChk && data.CexChk) {
                                    this.currentModel = model;
                                    this.currentDialog = 'modalDialogCex';
                                    this.dialogInterlocutorCex.open();
                                } else {
                                    this.checkPpalInterloc(model);
                                }
                            })
                            .catch(error => {
                                this.sharedService.showError(error);
                                this.setSpinner(false);
                            });
                    }
                } else {
                    this.checkPpalInterloc(model);
                }
            } else {
                if (this.isNew) {
                    if (this.isNewStructure) {
                        model.AddressDoor = model.letter;
                        if (model.OtpTypeId == null || model.OtpTypeId == '' || model.OtpTypeId == '-1' || model.OtpTypeId == '0') {
                            this.interlocutorForm.get('otpTypeId').setValue('1');
                        }
                    } else {
                        if (!this.iAction) model.otpTypeId = '1';
                        model.interlocutorId = 0;
                    }
                    if (this.isNewStructure) {
                        model.clientId = null;
                        model.clientCenterId = null;
                        model.groupId = null;
                        if (this.iAction) {
                            model.clientId = this.iClientId;
                            if (model.signerChk) {
                                model.clientCenterId = null;
                                model.relationTypeId = '2';
                            } else {
                                model.clientCenterId = this.iClientCenterId;
                                model.relationTypeId = '3';
                            }
                            model.relationRandstadValue = model.pUserId;
                        } else {
                            if (model.relationTypeId == '1') {
                                model.groupId = model.relationTypeValue;
                            } else if (model.relationTypeId == '2') {
                                model.clientId = model.relationTypeValue;
                            } else if (model.relationTypeId == '3') {
                                let relationClientCenter = model.relationTypeValue.split('-');
                                model.clientId = relationClientCenter[0].trim();
                                model.clientCenterId = relationClientCenter[1].trim();
                                if (model.signerChk) {
                                    model.clientCenterId = null;
                                    model.relationTypeId = '2';
                                }
                            }
                        }

                        if (this.isNewInterlocutor) {
                            model.interlocutorId = 0;
                        }

                        if (this.isSave == false) {
                            this.isSave = true;
                            this.centersService
                                .postContactPerson(model, this.branchOnInit.id)
                                .then(data => {
                                    this.sharedService.toastSuccess(data.MessageOK);
                                    let lastInterlocutorId = data.DataId.split('/')[1];
                                    let lastContactPersonRelId = data.DataId.split('/')[3];
                                    if (this.iAction) {
                                        this.oCallbackSaveEvent.emit({ InterlocutorId: lastInterlocutorId, ContactPersonRelId: lastContactPersonRelId });
                                    } else {
                                        this.isSave = true;
                                        this.zone.run(() => this.router.navigate(['interlocutors/' + lastInterlocutorId + '/summary']));
                                    }
                                })
                                .catch(error => {
                                    this.isSave = false;
                                    this.sharedService.showError(error);
                                    this.setSpinner(false);
                                });
                        }
                    } else {
                        let clientCenter = model.client.split('-');
                        model.clientId = clientCenter[0].trim();
                        model.clientCenterId = clientCenter[1].trim();
                        model.interlocutorId = 0;
                        if (this.isSave == false) {
                            this.isSave = true;
                            this.centersService
                                .postClientCenterInterlocutor(model, this.branchOnInit.id)
                                .then(data => {
                                    this.sharedService.toastSuccess(data.MessageOK);
                                    let interlocutorId = data.DataId.split('/')[2];
                                    if (this.iAction) {
                                        this.oCallbackSaveEvent.emit({ InterlocutorId: interlocutorId, ContactPersonRelId: '' });
                                    } else {
                                        this.isSave = true;
                                        this.zone.run(() =>
                                            this.router.navigate([
                                                'clients/' +
                                                    model.clientId +
                                                    '/centers/' +
                                                    model.clientCenterId +
                                                    '/interlocutors/' +
                                                    interlocutorId +
                                                    '/detail'
                                            ])
                                        );
                                    }
                                })
                                .catch(error => {
                                    this.isSave = false;
                                    this.sharedService.showError(error);
                                    this.setSpinner(false);
                                });
                        }
                    }
                } else {
                    if (!this.iAction) {
                        model.interlocutorId = this.interlocutor.InterlocutorId;
                        model.otpTypeId = this.interlocutor.OtpTypeId;

                        model.clientId = this.interlocutor.ClientId;
                        model.clientCenterId = this.interlocutor.ClientCenterId;
                        model.groupId = this.interlocutor.GroupId;
                        model.relationTypeId = this.interlocutor.RelationTypeId;
                    }
                    if (this.isNewStructure) {
                        model.AddressDoor = model.letter;
                        model.ContactPersonRelId = this.contactPersonRelId;
                        model.UserId = model.relationRandstadValue;
                        if (model.signerChk) {
                            model.relationTypeId = '2';
                            model.groupId = null;
                        } else {
                            model.relationTypeId = this.iAction ? '3' : this.interlocutorForm.get('relationTypeId').value;
                            model.clientId = this.iAction ? model.clientId : null;
                            model.clientCenterId = this.iAction ? model.clientCenterId : null;
                        }

                        if (model.decisorChk) {
                            model.clientCenterId = this.iAction ? model.clientCenterId : null;
                        }
                        let relationClientCenter = model.relationTypeValue.split('-');
                        if (model.relationTypeId == '1') {
                            model.groupId = relationClientCenter[0].trim();
                        } else if (model.relationTypeId == '2') {
                            model.clientId = relationClientCenter[0].trim();
                        } else if (model.relationTypeId == '3' && !this.iAction) {
                            model.clientId = relationClientCenter[0].trim();
                            model.clientCenterId = relationClientCenter[1].trim();
                        }

                        this.centersService
                            .putContactPerson(model, this.branchOnInit.id)
                            .then(async data => {
                                this.sharedService.toastSuccess(data.MessageOK);
                                if (this.iAction) {
                                    this.oCallbackSaveEvent.emit({
                                        InterlocutorId: this.interlocutor.InterlocutorId,
                                        ContactPersonRelId: this.interlocutor.ContactPersonRelId
                                    });
                                } else {
                                    this.zone.run(() =>
                                        this.router.navigate(
                                            [
                                                'clients/' +
                                                    this.interlocutor.ClientId +
                                                    '/centers/' +
                                                    this.interlocutor.ClientCenterId +
                                                    '/interlocutors/' +
                                                    this.interlocutor.InterlocutorId +
                                                    '/detail'
                                            ],
                                            {
                                                queryParams: {
                                                    contactPersonRelId: this.interlocutor.ContactPersonRelId
                                                }
                                            }
                                        )
                                    );
                                }
                            })
                            .catch(error => {
                                this.sharedService.showError(error);
                                this.setSpinner(false);
                            });
                    } else {
                        let clientCenter = model.client.split('-');
                        model.clientId = clientCenter[0].trim();
                        model.clientCenterId = clientCenter[1].trim();
                        this.centersService
                            .putClientCenterInterlocutor(model, this.branchOnInit.id, this.changeStatusCenter)
                            .then(async data => {
                                this.sharedService.toastSuccess(data.MessageOK);
                                if (this.iAction) {
                                    this.oCallbackSaveEvent.emit({ InterlocutorId: this.interlocutor.InterlocutorId, ContactPersonRelId: '' });
                                } else {
                                    this.zone.run(() =>
                                        this.router.navigate([
                                            'clients/' +
                                                this.interlocutor.ClientId +
                                                '/centers/' +
                                                this.interlocutor.ClientCenterId +
                                                '/interlocutors/' +
                                                this.interlocutor.InterlocutorId +
                                                '/detail'
                                        ])
                                    );
                                }
                            })
                            .catch(error => {
                                this.sharedService.showError(error);
                                this.setSpinner(false);
                            });
                    }
                }
            }
        } else {
            this.sharedService.scrollToError(this.interlocutorForm, this.el);
            this.setSpinner(false);
            setTimeout(() => {
                this.expandedPanel(this.panelContactForm);
                this.expandedPanel(this.relationRandstad);
                this.expandedPanel(this.panelPersonalInfo);
                this.expandedPanel(this.panelBehaviour);
                this.expandedPanel(this.panelInterlocutorPersonAddress);
            });
        }
    }

    ////////////////////////////////////////////////////////////////////
    // Codigo del menu acciones

    openDialogCancelInterlocutor() {
        if (this.iAction && (this.clientCenterTabs.CompanyId == 'RWS' || this.clientCenterTabs.CompanyId == 'FUN') && this.interlocutor.SignerChk) {
            if (this.interlocutor.ContactTypeId != '9') {
                this.sharedService.toastError('No se puede borrar un interlocutor firmante. Solo puedes pasarlo a inactivo.');
            } else {
                this.sharedService.toastError('No se puede borrar un interlocutor firmante.');
            }
        } else {
            this.currentDialog = 'modalDialogCancelInterlocutor';
            this.dialog.open();
        }
    }

    validateSaveForm() {
        let fiscalDocNumber = this.interlocutorForm.getRawValue().fiscalDocNumber;

        if (fiscalDocNumber && fiscalDocNumber != '') {
            fiscalDocNumber.toUpperCase();
        }

        this.validateZipCode(
            0,
            this.interlocutorForm.getRawValue().addressZipCode,
            this.interlocutorForm.getRawValue().addressCountryId,
            this.interlocutorForm.getRawValue().addressProvinceId,
            this.interlocutorForm.getRawValue().addressCityId
        );
        this.validateEmail(this.interlocutorForm.getRawValue().email);
        this.validatePhones(this.interlocutorForm.getRawValue().phone1, this.interlocutorForm.getRawValue().phone2);
        let isValidFormFields = false;

        if (this.isNewStructure) {
            this.validateFiscalDochigh(
                this.interlocutorForm.getRawValue().fiscalDocId,
                fiscalDocNumber,
                this.interlocutorForm.getRawValue().signerChk,
                this.interlocutorForm.getRawValue().functionId
            );
            this.validateHobby(this.interlocutorForm.getRawValue().hobby1Id, this.interlocutorForm.getRawValue().hobby2Id);
            this.validateRequiredFiscalDoc(
                this.interlocutorForm.getRawValue().fiscalDocId,
                this.interlocutorForm.getRawValue().fiscalDocNumber,
                this.interlocutorForm.getRawValue().signerChk,
                this.interlocutorForm.getRawValue().functionId
            );

            this.validateEmailSignerBChk(this.interlocutorForm.getRawValue().email, this.interlocutorForm.getRawValue().signerBChk);
            isValidFormFields =
                this.validFiscalDocLenght &&
                this.validFiscalDocLetter &&
                this.validFiscalDocFormat &&
                this.validFiscalDocFilled &&
                this.validAddressZipCodeSpain &&
                this.validAddressZipCodeSpainExist &&
                this.validCheck &&
                this.validCheckFiscNumber &&
                this.validEmail &&
                this.validEmailSignerBChk &&
                this.validSameHobby &&
                this.validPhone &&
                this.validateDecisor(false);
        } else {
            if (this.iAction) {
                this.validateFiscalDoc(
                    this.interlocutorForm.getRawValue().fiscalDocId,
                    fiscalDocNumber,
                    this.interlocutorForm.getRawValue().signerChk,
                    this.interlocutorForm.getRawValue().functionId
                );

                isValidFormFields =
                    this.validFiscalDocLenght &&
                    this.validFiscalDocLetter &&
                    this.validFiscalDocFormat &&
                    this.validFiscalDocFilled &&
                    this.validAddressZipCodeSpain &&
                    this.validAddressZipCodeSpainExist &&
                    this.validEmail &&
                    this.validEmailSignerBChk &&
                    this.validCheck &&
                    this.validCheckFiscNumber &&
                    this.validPhone &&
                    this.validSameHobby &&
                    this.validateDecisor(false);
            } else {
                this.validateFiscalDoc(this.interlocutorForm.getRawValue().fiscalDocId, fiscalDocNumber);

                isValidFormFields =
                    this.validFiscalDocLenght &&
                    this.validFiscalDocLetter &&
                    this.validFiscalDocFormat &&
                    this.validFiscalDocFilled &&
                    this.validAddressZipCodeSpain &&
                    this.validAddressZipCodeSpainExist &&
                    this.validEmail &&
                    this.validPhone;
            }
        }
        return this.interlocutorForm.valid && isValidFormFields;
    }

    validateSigner(functionId: number) {
        if (this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX') {
            if (functionId == 74) {
                this.interlocutorForm.get('signerChk').setValue(true);
                this.interlocutorForm.get('signerChk').disable();
            } else {
                this.interlocutorForm.get('signerChk').enable();
                this.interlocutorForm.get('signerChk').setValue(false);
            }
        }
    }

    validateDecisor(isChange?: boolean) {
        if (this.clientCenterTabs) {
            if (this.clientCenterTabs.CompanyId == 'RWS' || this.clientCenterTabs.CompanyId == 'FUN') {
                this.validFiscalDocDecisor = true;
                this.requiredFiscalDocDecisor = false;

                let decisorChk = this.interlocutorForm.getRawValue().decisorChk;
                let fiscalDocNumber = this.interlocutorForm.getRawValue().fiscalDocNumber;

                if (decisorChk) {
                    this.requiredFiscalDocDecisor = true;
                }

                if (this.requiredFiscalDocDecisor && (!fiscalDocNumber || fiscalDocNumber == null || fiscalDocNumber == '')) {
                    this.validFiscalDocDecisor = false;
                }
            }
        }

        return this.validFiscalDocDecisor;
    }

    validateSensitiveData() {
        if (this.isSensitiveData) {
            if (this.isNewStructure) {
                this.sharedService.toastError('Esta persona de contacto pertenece a la oficina de Coordinación GGCC. No se puede modificar');
            } else {
                this.sharedService.toastError('Este interlocutor pertenece a la oficina de Coordinación GGCC. No se puede modificar');
            }
        } else {
            this.zone.run(() =>
                this.router.navigate(
                    [
                        'clients/' +
                            this.interlocutor.ClientId +
                            '/centers/' +
                            this.interlocutor.ClientCenterId +
                            '/interlocutors/' +
                            this.interlocutor.InterlocutorId,
                        'edit'
                    ],
                    {
                        queryParams: {
                            userId: this.interlocutor.UserId
                        }
                    }
                )
            );
        }
    }

    ////////////////////////////////////////////////////////////////////
    // Funciones para los combos

    validateZipCode(typeControl: number, addressZipCode: string, addressCountryId: string, addressProvinceId: string, addressCityId: string) {
        this.validAddressZipCodeSpain = true;
        this.validAddressZipCodeSpainExist = true;

        this.dialogZipCodeTitle = '';
        this.dialogZipCodeMessage = '';

        if (addressCountryId == '11' && addressZipCode != '' && addressZipCode != null) {
            if (addressZipCode.length != 5) {
                this.validAddressZipCodeSpain = false;
                this.dialogZipCode.visible = false;
            } else {
                if (addressProvinceId != null && addressProvinceId != '' && addressZipCode.substr(0, 2) != addressProvinceId) {
                    if (typeControl == 1) {
                        this.dialogZipCodeTitle = 'Cambio Provincia';
                        this.dialogZipCodeMessage = 'La Provincia no coincide con el Código Postal introducido. ¿Que información desea mantener?';
                    } else if (addressCityId != '') {
                        this.dialogZipCodeTitle = 'Cambio Código Postal';
                        this.dialogZipCodeMessage =
                            'El Código Postal no coincide con la Provincia ni el Municipio introducidos. ¿Que información desea mantener?';
                    } else {
                        this.dialogZipCodeTitle = 'Cambio Código Postal';
                        this.dialogZipCodeMessage = 'El Código Postal no coincide con la Provincia introducida. ¿Que información desea mantener?';
                    }

                    this.currentDialog = 'modalDialogZipCode';
                    this.dialogZipCode.open();
                }
            }
        }
    }

    checkProvince(addressCountryId: string, disabledFirstChange = true) {
        this.setSpinner(true);

        if (addressCountryId == '11') {
            this.centersService
                .getCommonsList('provinces', 'ProvinceId', 'Name')
                .then(data => {
                    this.addressProvincesList = data;

                    this.requiredProvince = true;
                    this.interlocutorForm.get('addressProvinceId').clearValidators();
                    this.interlocutorForm.get('addressProvinceId').setValidators(Validators.required);
                    this.interlocutorForm.get('addressProvinceId').updateValueAndValidity();

                    this.requiredCity = true;
                    this.interlocutorForm.get('addressCityId').clearValidators();
                    this.interlocutorForm.get('addressCityId').setValidators(Validators.required);
                    this.interlocutorForm.get('addressCityId').updateValueAndValidity();

                    if ((this.disabledFirst || disabledFirstChange) && !this.existContactPerson) {
                        this.interlocutorForm.get('addressProvinceId').enable();
                        this.interlocutorForm.get('addressCityId').enable();
                    }

                    this.setSpinner(false);
                })
                .catch(error => {
                    this.sharedService.showError(error);
                    this.setSpinner(false);
                });
        } else {
            this.addressProvincesList = [];
            this.addressCitiesList = [];

            this.requiredProvince = false;
            this.clearFormField('addressProvinceId');

            this.requiredCity = false;
            this.clearFormField('addressCityId');

            this.setSpinner(false);
        }

        this.validateZipCode(
            0,
            this.interlocutorForm.getRawValue().addressZipCode,
            this.interlocutorForm.getRawValue().addressCountryId,
            this.interlocutorForm.getRawValue().addressProvinceId,
            this.interlocutorForm.getRawValue().addressCityId
        );
    }

    checkCity(addressProvinceId: string, disabledFirstChange = true) {
        this.setSpinner(true);

        this.centersService
            .getCities(addressProvinceId)
            .then(data => {
                this.addressCitiesList = data.sort((a, b) => {
                    if (a.label < b.label) {
                        return -1;
                    }
                    if (a.label > b.label) {
                        return 1;
                    }
                    return 0;
                });

                this.validateZipCode(
                    1,
                    this.interlocutorForm.getRawValue().addressZipCode,
                    this.interlocutorForm.getRawValue().addressCountryId,
                    this.interlocutorForm.getRawValue().addressProvinceId,
                    this.interlocutorForm.getRawValue().addressCityId
                );

                if (this.disabledFirst && disabledFirstChange && !this.existContactPerson) {
                    this.interlocutorForm.get('addressCityId').enable();
                }

                this.setSpinner(false);
            })
            .catch(error => {
                this.sharedService.showError(error);
                this.setSpinner(false);
            });
    }

    validateFiscalDoc(fiscalDocId: string, fiscalDocNumber: string, signerChk: string = '', functionId: string = '') {
        let isValidFiscalDoc = true;
        this.validFiscalDocLenght = true;
        this.validFiscalDocLetter = true;
        this.validFiscalDocFormat = true;
        this.validFiscalDocFilled = true;

        fiscalDocNumber = fiscalDocNumber?.toUpperCase().trim();
        this.interlocutorForm.get('fiscalDocNumber')?.setValue(fiscalDocNumber);

        let isSensitiveData = this.interlocutorForm.get('hideSensitiveDataChk').value == 1 && !this.isGgcc;

        if (!isSensitiveData) {
            let letters = 'TRWAGMYFPDXBNJZSQVHLCKE';
            let nieLetters = 'XYZ';
            let regexNums = new RegExp('^[0-9]+$');
            let regexLetters = new RegExp('^[a-zA-Z]+$');

            if (fiscalDocId != null && fiscalDocId != '' && fiscalDocNumber != null && fiscalDocNumber != '') {
                switch (fiscalDocId) {
                    case '1': //NIF
                        if (fiscalDocNumber.length != 9) {
                            this.validFiscalDocLenght = false;
                            isValidFiscalDoc = false;
                        } else {
                            // El último caracter debe ser una letra
                            let lastLetter = fiscalDocNumber.substr(fiscalDocNumber.length - 1, 1).toUpperCase();
                            isValidFiscalDoc = regexLetters.test(lastLetter);

                            // Los primeros 8 caracteres deben ser numericos
                            let numericPartNif = fiscalDocNumber.substr(0, fiscalDocNumber.length - 1);
                            let numericResultNif = parseInt(numericPartNif);
                            isValidFiscalDoc = regexNums.test(numericPartNif) && isValidFiscalDoc;

                            if (isValidFiscalDoc) {
                                // Comprobamos que la letra indicada es la que corresponde
                                let calculatedLetter = letters.charAt(numericResultNif % 23);

                                if (calculatedLetter != lastLetter) {
                                    this.validFiscalDocLetter = false;
                                    isValidFiscalDoc = false;
                                }
                            } else {
                                this.validFiscalDocFormat = false;
                                isValidFiscalDoc = false;
                            }
                        }

                        break;
                    case '3': //NIE
                        if (fiscalDocNumber.length != 9) {
                            this.validFiscalDocLenght = false;
                            isValidFiscalDoc = false;
                        } else {
                            // El último caracter debe ser una letra
                            let lastLetter = fiscalDocNumber.substr(fiscalDocNumber.length - 1, 1).toUpperCase();
                            isValidFiscalDoc = regexLetters.test(lastLetter);

                            // El primer caracter debe ser X, Y o Z
                            let firstLetter = fiscalDocNumber.substr(0, 1);
                            isValidFiscalDoc = nieLetters.indexOf(firstLetter) != -1 && isValidFiscalDoc;

                            // Los 7 caracteres centrales deben ser numericos
                            let numericPartNie = fiscalDocNumber.substr(1, fiscalDocNumber.length - 2);
                            isValidFiscalDoc = regexNums.test(numericPartNie) && isValidFiscalDoc;

                            if (isValidFiscalDoc) {
                                let firstAscii = firstLetter.charCodeAt(0);
                                let xAscii = 'X'.charCodeAt(0);

                                // Comprobamos que la letra indicada es la que corresponde
                                let aux = (firstAscii - xAscii).toString().concat(numericPartNie);
                                let calculatedLetter = letters.charAt(parseInt(aux) % 23);

                                if (calculatedLetter != lastLetter) {
                                    this.validFiscalDocLetter = false;
                                    isValidFiscalDoc = false;
                                }
                            } else {
                                this.validFiscalDocFormat = false;
                                isValidFiscalDoc = false;
                            }
                        }

                        break;
                }
            } else if (
                ((fiscalDocId != null && fiscalDocId != '' && (fiscalDocNumber == null || fiscalDocNumber == '')) ||
                    ((fiscalDocId == null || fiscalDocId == '') && fiscalDocNumber != null && fiscalDocNumber != '')) &&
                ((this.iAction && !signerChk && functionId != '74') || !this.iAction)
            ) {
                this.validFiscalDocFilled = false;
                isValidFiscalDoc = false;
            }
        }
    }

    validateFiscalDochigh(fiscalDocId: string, fiscalDocNumber: string, signerChk: string, functionId: string) {
        let isValidFiscalDoc = true;
        this.validFiscalDocLenght = true;
        this.validFiscalDocLetter = true;
        this.validFiscalDocFormat = true;
        this.validFiscalDocFilled = true;
        this.validFiscalDocNotDuplicated = true;

        fiscalDocNumber = !fiscalDocNumber || fiscalDocNumber == null ? '' : fiscalDocNumber;
        fiscalDocNumber = fiscalDocNumber.toUpperCase().trim();
        this.interlocutorForm.get('fiscalDocNumber')?.setValue(fiscalDocNumber);

        let isSensitiveData = this.interlocutorForm.get('hideSensitiveDataChk').value == 1 && !this.isGgcc;

        if (!isSensitiveData) {
            let letters = 'TRWAGMYFPDXBNJZSQVHLCKE';
            let nieLetters = 'XYZ';
            let regexNums = new RegExp('^[0-9]+$');
            let regexLetters = new RegExp('^[a-zA-Z]+$');

            if (fiscalDocId != null && fiscalDocId != '' && fiscalDocNumber != null && fiscalDocNumber != '') {
                switch (fiscalDocId) {
                    case '1': //NIF
                        if (fiscalDocNumber.length != 9) {
                            this.validFiscalDocLenght = false;
                            isValidFiscalDoc = false;
                        } else {
                            // El último caracter debe ser una letra
                            let lastLetter = fiscalDocNumber.substr(fiscalDocNumber.length - 1, 1).toUpperCase();
                            isValidFiscalDoc = regexLetters.test(lastLetter);

                            // Los primeros 8 caracteres deben ser numericos
                            let numericPartNif = fiscalDocNumber.substr(0, fiscalDocNumber.length - 1);
                            let numericResultNif = parseInt(numericPartNif);
                            isValidFiscalDoc = regexNums.test(numericPartNif) && isValidFiscalDoc;

                            if (isValidFiscalDoc) {
                                // Comprobamos que la letra indicada es la que corresponde
                                let calculatedLetter = letters.charAt(numericResultNif % 23);

                                if (calculatedLetter != lastLetter) {
                                    this.validFiscalDocLetter = false;
                                    isValidFiscalDoc = false;
                                }
                            } else {
                                this.validFiscalDocFormat = false;
                                isValidFiscalDoc = false;
                            }
                        }

                        break;
                    case '3': //NIE
                        if (fiscalDocNumber.length != 9) {
                            this.validFiscalDocLenght = false;
                            isValidFiscalDoc = false;
                        } else {
                            // El último caracter debe ser una letra
                            let lastLetter = fiscalDocNumber.substr(fiscalDocNumber.length - 1, 1).toUpperCase();
                            isValidFiscalDoc = regexLetters.test(lastLetter);

                            // El primer caracter debe ser X, Y o Z
                            let firstLetter = fiscalDocNumber.substr(0, 1);
                            isValidFiscalDoc = nieLetters.indexOf(firstLetter) != -1 && isValidFiscalDoc;

                            // Los 7 caracteres centrales deben ser numericos
                            let numericPartNie = fiscalDocNumber.substr(1, fiscalDocNumber.length - 2);
                            isValidFiscalDoc = regexNums.test(numericPartNie) && isValidFiscalDoc;

                            if (isValidFiscalDoc) {
                                let firstAscii = firstLetter.charCodeAt(0);
                                let xAscii = 'X'.charCodeAt(0);

                                // Comprobamos que la letra indicada es la que corresponde
                                let aux = (firstAscii - xAscii).toString().concat(numericPartNie);
                                let calculatedLetter = letters.charAt(parseInt(aux) % 23);

                                if (calculatedLetter != lastLetter) {
                                    this.validFiscalDocLetter = false;
                                    isValidFiscalDoc = false;
                                }
                            } else {
                                this.validFiscalDocFormat = false;
                                isValidFiscalDoc = false;
                            }
                        }

                        break;
                }
            } else if (
                ((fiscalDocId != null && fiscalDocId != '' && (fiscalDocNumber == null || fiscalDocNumber == '')) ||
                    ((fiscalDocId == null || fiscalDocId == '') && fiscalDocNumber != null && fiscalDocNumber != '')) &&
                !signerChk &&
                functionId != '74'
            ) {
                this.validFiscalDocFilled = false;
                isValidFiscalDoc = false;
            }

            if (!this.interlocutorSearchDisable) this.validFiscalDocFilled = true;
        }
    }

    tooltip() {
        if (
            this.isEdit &&
            (this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP') &&
            !this.isActionDetail &&
            this.interlocutor.PUserId != this.branchOnInit.userId &&
            this.interlocutorForm.get('pUserId').disabled
        ) {
            this.messageTooltip = 'Sólo el propietario del centro o team leader puede modificar este dato';
        } else {
            this.messageTooltip = '';
        }
    }

    async onFocus(fiscalDocNumber: string) {
        this.isFocusing = true;
        await this.validateFiscalDocDuplicate(fiscalDocNumber);
        this.isFocusing = false;
    }

    /**
     * Método para validar si un documento fiscal ya pertenece a otra persona de contacto
     * @param fiscalDocNumber
     */
    async validateFiscalDocDuplicate(fiscalDocNumber: string) {
        if (this.isNew && !this.isNewInterlocutor) {
            return;
        }
        if (
            fiscalDocNumber != '' &&
            fiscalDocNumber != null &&
            this.validFiscalDocLenght &&
            this.validFiscalDocLetter &&
            this.validFiscalDocFormat &&
            this.validFiscalDocFilled &&
            !this.isNewStructure
        ) {
            this.setSpinner(true);
            this.blockCertificateData = false;

            await this.centersService
                .getInterlocutorByFiscalNumber(fiscalDocNumber)
                .then(data => {
                    this.interlocutor = new ClientCenterInterlocutorDetail();
                    data.InterlocutorId = this.interlocutorForm.get('interlocutorId').value;
                    data.PUserId = this.interlocutorForm.get('pUserId').value;
                    data.FunctionId = this.interlocutorForm.get('functionId').value;
                    data.DetailFunction = this.interlocutorForm.get('detailFunction').value;
                    data.PositionInterlocFBIId = this.interlocutorForm.get('positionId').value;
                    data.LanguageId = this.interlocutorForm.get('languageId').value;
                    data.AddressId = this.interlocutorForm.get('addressId').value;
                    data.AddressStreet = this.interlocutorForm.get('addressStreet').value;
                    data.AddressNumber = this.interlocutorForm.get('addressNumber').value;
                    data.AddressAditional = this.interlocutorForm.get('addressAditional').value;
                    data.AddressZipCode = this.interlocutorForm.get('addressZipCode').value;
                    data.AddressCountryId = this.interlocutorForm.get('addressCountryId').value;
                    data.AddressProvinceId = this.interlocutorForm.get('addressProvinceId').value;
                    data.AddressCityId = this.interlocutorForm.get('addressCityId').value;
                    data.MailingChk = this.interlocutorForm.get('mailingChk').value;
                    data.ShouldReceiveSurveyChk = this.interlocutorForm.get('shouldReceiveSurveyChk').value;
                    data.Comments = this.interlocutorForm.get('comments').value;
                    if (this.iAction) {
                        data.WantToReceiveASurveyChk = this.interlocutorForm.get('wantToReceiveASurveyChk').value;
                        data.Hobby1Id = this.interlocutorForm.get('hobby1Id').value;
                        data.Hobby2Id = this.interlocutorForm.get('hobby2Id').value;
                        data.PortalElement = this.interlocutorForm.get('portalElement').value;
                        data.ContactTypeId = data.ContactTypeId == 0 ? this.interlocutorForm.get('contactTypeId').value : data.ContactTypeId;
                        data.MailingTypeId = data.MailingTypeId == null || data.MailingTypeId == '' ? '2' : data.MailingTypeId;
                    }

                    this.interlocutor = data;

                    if (data != null) {
                        if (this.isNewStructure || this.iAction) {
                            if (this.clientCenterTabs) {
                                if (
                                    (this.clientCenterTabs.CompanyId == 'RWS' || this.clientCenterTabs.CompanyId == 'FUN') &&
                                    data.CertificateStatusId != null &&
                                    data.CertificateStatusId != ''
                                ) {
                                    if (data.CertificateStatusId == '7') {
                                        this.dialogIntelocSolMsg = this.isNewStructure
                                            ? 'Esta persona de contacto ya tiene certificado y vamos a recuperar sus datos.'
                                            : 'Este interlocutor ya tiene certificado y vamos a recuperar sus datos.';
                                    } else {
                                        this.blockCertificateData = true;
                                        this.dialogIntelocSolMsg = this.isNewStructure
                                            ? 'Esta persona de contacto ya tiene certificado y vamos a recuperar sus datos. Si quieres modificarlos ponte en contacto con el Centro de Soporte.'
                                            : 'Este interlocutor ya tiene certificado y vamos a recuperar sus datos. Si quieres modificarlos ponte en contacto con el Centro de Soporte.';
                                    }

                                    this.currentDialog = 'modalDialogInterlocutorSolData';
                                    this.dialogInterlocutorSolData.open();
                                } else {
                                    this.currentDialog = 'modalDialogInterlocutorData';
                                    this.dialogInterlocutorData.open();
                                }
                            } else {
                                this.currentDialog = 'modalDialogInterlocutorData';
                                this.dialogInterlocutorData.open();
                            }
                        } else {
                            this.currentDialog = 'modalDialogInterlocutorData';
                            this.dialogInterlocutorData.open();
                        }
                    }
                    this.setSpinner(false);
                })
                .catch(() => {
                    this.setSpinner(false);
                });
        }
    }

    validateEmail(email: string) {
        this.validEmail = true;

        let isSensitiveData = this.interlocutorForm.get('hideSensitiveDataChk').value == 1 && !this.isGgcc;

        if (!isSensitiveData) {
            if (email != '' && email != null) {
                if (!email.includes('..')) {
                    let regex = new RegExp(this.validatorsRegExEmail.MinValue);
                    this.validEmail = regex.test(email.toLowerCase());
                    if (this.validEmail) {
                        this.enabledAll();
                    }
                } else {
                    this.validEmail = false;
                }
            }
        }
    }

    validatePhones(ph1: string, ph2: string) {
        if (this.isNew && !this.isNewInterlocutor && !(this.iAction && !this.isNewStructure)) {
            return;
        }

        this.validPhone = true;

        let isSensitiveData = this.interlocutorForm.get('hideSensitiveDataChk').value == 1 && !this.isGgcc;

        if (!isSensitiveData) {
            if ((!isUndefined(ph1) && ph1 != null && ph1 != '') || (!isUndefined(ph2) && ph2 != null && ph2 != '')) {
                this.validPhone = true;
                this.enabledAll();
            } else {
                this.validPhone = false;
            }
        }
    }

    validateChangePhones(ph1: string, ph2: string) {
        let regExMobile = this.validatorsRegExMobile.MinValue;
        regExMobile = regExMobile.replace('{0}', this.validatorsRegExMobileBegin.MinValue);
        regExMobile = regExMobile.replace('{1}', this.validatorsRegExMobileBegin.MaxValue);
        regExMobile = regExMobile.replaceAll('{{', '{');
        regExMobile = regExMobile.replaceAll('}}', '}');

        let regexNums = new RegExp(regExMobile);
        let validNumPhone1 = regexNums.test(ph1);

        // Si cumple con las validaciones de móvil, y este está vacío, movemos teléfono a móvil
        if (this.interlocutorSearchDisable && validNumPhone1 && (ph2 == undefined || ph2 == null || ph2 == '')) {
            this.interlocutorForm.get('phone2').setValue(this.interlocutorForm.get('phone1').value);
            this.interlocutorForm.get('phone1').setValue('');
        }
    }

    validateEmailSignerBChk(email?: string, signerChk?: boolean) {
        email = this.interlocutorForm.getRawValue().email;
        signerChk = this.interlocutorForm.getRawValue().signerBChk;

        if (this.branchOnInit.companyId == 'RWS' || this.branchOnInit.companyId == 'FUN') {
            //email informado
            if (email != null && email != '') {
                this.validEmailSignerBChk = true;
            }
            //Marcado check y Email no informado
            else if (signerChk && (email == null || email == '')) {
                this.validEmailSignerBChk = false;
            } else {
                this.validEmailSignerBChk = true;
            }
        }
    }

    enabledAll() {
        let isTeamLeader = this.getEditableUser('ff_user_teamLeader_prof');
        let userId = this.interlocutor ? this.interlocutor.PUserId : '';
        let exist = true;
        let interlocPortalPerm =
            this.isNew ||
            (this.interlocutor && (this.interlocutor.PortalElement == null || this.interlocutor.PortalElement == '0')) ||
            this.isSupportCenter ||
            this.isInGeneralParam;

        if (!this.isActionDetail) {
            userId = !userId || userId == null || userId == '' ? this.branchOnInit.userId : userId;
            exist = this.interlocutorsOwners.filter(x => x.value == userId).length > 0;
        }

        let isDisabledShouldReceiveSurveyChk = !this.getEditable('ff_interlocutorClientCenter_surveyChk');

        let isKeyAccount =
            this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                ? this.getEditableUser('ff_user_ka_out')
                : this.branchOnInit.companyId == 'RWS' || this.branchOnInit.companyId == 'FUN'
                ? this.getEditableUser('ff_user_ka_rws')
                : this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP'
                ? this.isProfessional
                : false;

        let isDistrictManager =
            this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                ? this.getEditableUser('ff_user_dz_out')
                : this.branchOnInit.companyId == 'RWS' || this.branchOnInit.companyId == 'FUN'
                ? this.getEditableUser('ff_user_dz_rws')
                : this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP'
                ? this.isProfessional
                : false;

        let isRegionManager =
            this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                ? this.getEditableUser('ff_user_dr_out')
                : this.branchOnInit.companyId == 'RWS' || this.branchOnInit.companyId == 'FUN'
                ? this.getEditableUser('ff_user_dr_rws')
                : this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP'
                ? this.isProfessional
                : false;

        if (
            !this.isNew &&
            this.interlocutor.ShouldReceiveSurveyChk == '0' &&
            (this.branchOnInit.companyId == 'RPS' ||
                this.branchOnInit.companyId == 'VEX' ||
                this.branchOnInit.companyId == 'RWS' ||
                this.branchOnInit.companyId == 'FUN' ||
                this.branchOnInit.companyId == 'RCO' ||
                this.branchOnInit.companyId == 'EXP'
            )
        ) {
            if (this.clientCenterTabs && this.clientCenterTabs.KeyAccountChk == 1) {
                isDisabledShouldReceiveSurveyChk = !this.getEditable('ff_interlocutorClientCenter_surveyChk') || !isKeyAccount;
            } else {
                isDisabledShouldReceiveSurveyChk =
                    !this.getEditable('ff_interlocutorClientCenter_surveyChk') ||
                    (this.branchOnInit.userId != this.interlocutor.PUserId && !isDistrictManager && !isRegionManager);
            }
        }

        if (!this.disabledFirst) {
            if (this.getEditable('ff_interlocutorClientCenter_interlocutorId')) {
                this.interlocutorForm.get('interlocutorId').enable();
            }

            if (this.getEditable('ff_interlocutorClientCenter_functionId')) {
                this.interlocutorForm.get('functionId').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_detailFunction')) {
                this.interlocutorForm.get('detailFunction').enable();
            }

            if (this.getEditable('ff_interlocutorClientCenter_sexId')) {
                this.interlocutorForm.get('sexId').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_languageId')) {
                this.interlocutorForm.get('languageId').enable();
            }

            if (this.getEditable('ff_interlocutorClientCenter_extPhone1')) {
                this.interlocutorForm.get('extPhone1').enable();
            }

            if (this.iAction) {
                if (
                    this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                        ? this.getEditable('ff_interlocutorClientCenter_positionId_rpsvex')
                        : this.getEditable('ff_interlocutorClientCenter_positionId')
                ) {
                    this.interlocutorForm.get('positionId').enable();
                }
                if (
                    this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP'
                        ? this.getEditable('ff_interlocutorClientCenter_mailingTypeId')
                        : this.branchOnInit.companyId == 'RPS' || this.branchOnInit.companyId == 'VEX'
                        ? this.getEditable('ff_interlocutorClientCenter_mailingTypeId_out')
                        : this.getEditable('ff_interlocutorClientCenter_mailingTypeId') && this.getEditable('ff_interlocutorClientCenter_mailingTypeId_out')
                ) {
                    this.interlocutorForm.get('mailingTypeId').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_contactTypeId') && interlocPortalPerm) {
                    this.interlocutorForm.get('contactTypeId').enable();
                }
                if (!this.isActionDetail && this.isGgcc) {
                    this.interlocutorForm.get('hideSensitiveDataChk').enable();
                }
            } else {
                if (this.getEditable('ff_interlocutorClientCenter_positionId')) {
                    this.interlocutorForm.get('positionId').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_mailingTypeId')) {
                    this.interlocutorForm.get('mailingTypeId').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_status') && interlocPortalPerm) {
                    this.interlocutorForm.get('contactTypeId').enable();
                }
            }

            if (this.getEditable('ff_interlocutorClientCenter_signerBChk')) {
                this.interlocutorForm.get('signerBChk').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_centerCost_ceco')) {
                this.interlocutorForm.get('centerCostSeq').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_wantToReceiveASurveyChk')) {
                this.interlocutorForm.get('wantToReceiveASurveyChk').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_hobby1Id')) {
                this.interlocutorForm.get('hobby1Id').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_mailingChk')) {
                this.interlocutorForm.get('mailingChk').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_comments')) {
                this.interlocutorForm.get('comments').enable();
            }

            if (
                this.getEditable('ff_interlocutorClientCenter_owner') &&
                !this.isNewStructure &&
                (isTeamLeader || (this.clientCenterTabs && (this.branchOnInit.userId == this.clientCenterTabs.PUserId || !exist)))
            ) {
                this.interlocutorForm.get('pUserId').enable();
            }
            if (!isDisabledShouldReceiveSurveyChk) {
                this.interlocutorForm.get('shouldReceiveSurveyChk').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_signerChk') && !this.blockContrastData && !this.blockCertificateData && interlocPortalPerm) {
                this.interlocutorForm.get('signerChk').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_decisorChk') && !this.blockCertificateData && interlocPortalPerm && !this.blockDecisor) {
                this.interlocutorForm.get('decisorChk').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_prlChk')) {
                this.interlocutorForm.get('prlChk').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_cexChk')) {
                this.interlocutorForm.get('cexChk').enable();
            }

            if (this.isNewStructure) {
                if (this.getEditable('ff_interlocutorClientCenter_firstName') && !this.blockContrastData && !this.blockCertificateData && interlocPortalPerm) {
                    this.interlocutorForm.get('firstName').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_surname1') && !this.blockContrastData && !this.blockCertificateData && interlocPortalPerm) {
                    this.interlocutorForm.get('surname1').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_surname2') && !this.blockContrastData && !this.blockCertificateData && interlocPortalPerm) {
                    this.interlocutorForm.get('surname2').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_birthDate') && !this.blockContrastData && !this.blockCertificateData) {
                    this.interlocutorForm.get('birthDate').enable();
                }
                if (
                    this.getEditable('ff_interlocutorClientCenter_fiscalDocId') &&
                    !this.blockContrastData &&
                    !this.blockFiscalDoc &&
                    !this.blockCertificateData &&
                    interlocPortalPerm
                ) {
                    this.interlocutorForm.get('fiscalDocId').enable();
                }
                if (
                    this.getEditable('ff_interlocutorClientCenter_fiscalDocNumber') &&
                    !this.blockContrastData &&
                    !this.blockFiscalDoc &&
                    !this.blockCertificateData &&
                    interlocPortalPerm
                ) {
                    this.interlocutorForm.get('fiscalDocNumber').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_portalElement') && !this.blockCertificateData) {
                    this.interlocutorForm.get('portalElement').enable();
                }
            } else {
                if (this.getEditable('ff_interlocutorClientCenter_firstName') && !this.blockContrastData && !this.blockCertificateData && interlocPortalPerm) {
                    this.interlocutorForm.get('firstName').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_surname1') && !this.blockContrastData && !this.blockCertificateData && interlocPortalPerm) {
                    this.interlocutorForm.get('surname1').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_surname2') && !this.blockContrastData && !this.blockCertificateData && interlocPortalPerm) {
                    this.interlocutorForm.get('surname2').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_birthDate') && !this.blockContrastData && !this.blockCertificateData) {
                    this.interlocutorForm.get('birthDate').enable();
                }
                if (
                    this.getEditable('ff_interlocutorClientCenter_fiscalDocId') &&
                    !this.blockContrastData &&
                    !this.blockFiscalDoc &&
                    !this.blockCertificateData &&
                    interlocPortalPerm
                ) {
                    this.interlocutorForm.get('fiscalDocId').enable();
                }
                if (
                    this.getEditable('ff_interlocutorClientCenter_fiscalDocNumber') &&
                    !this.blockContrastData &&
                    !this.blockFiscalDoc &&
                    !this.blockCertificateData &&
                    interlocPortalPerm
                ) {
                    this.interlocutorForm.get('fiscalDocNumber').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_portalElement') && !this.blockCertificateData) {
                    this.interlocutorForm.get('portalElement').enable();
                }

                if (this.getEditable('ff_interlocutorClientCenter_addressCountryId')) {
                    this.interlocutorForm.get('addressCountryId').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_addressId')) {
                    this.interlocutorForm.get('addressId').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_addressStreet')) {
                    this.interlocutorForm.get('addressStreet').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_addressNumber')) {
                    this.interlocutorForm.get('addressNumber').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_addressAditional')) {
                    this.interlocutorForm.get('addressAditional').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_addressProvinceId')) {
                    this.interlocutorForm.get('addressProvinceId').enable();
                }
                if (this.getEditable('ff_interlocutorClientCenter_addressZipCode')) {
                    this.interlocutorForm.get('addressZipCode').enable();
                }
            }

            this.disabledFirst = true;

            if (this.isNewStructure) {
                this.validateHobby(this.interlocutorForm.getRawValue().hobby1Id, this.interlocutorForm.getRawValue().hobby2Id);
            } else {
                if (this.iAction) {
                    this.validateHobby(this.interlocutorForm.getRawValue().hobby1Id, this.interlocutorForm.getRawValue().hobby2Id);
                }

                this.checkProvince(this.interlocutorForm.getRawValue().addressCountryId);
            }

            // Si está en proceso nadie lo podrá tocar
            let disabledPrincipalChk =
                !this.getEditable('ff_interlocutorClientCenter_principalChk') || (!this.isEmployeeTeamLeader && !this.isEmployeeSalesManager);

            if (!disabledPrincipalChk) {
                this.interlocutorForm.get('principalChk').enable();
                setTimeout(() => {
                    this.principalChkSwitchToggles.toggleElement.nativeElement.disabled = false;
                });
            }
        }
    }

    enabledOther(index: number) {
        if (this.getEditable('ff_interlocutorClientCenter_firstName') && !this.blockContrastDataOther) {
            this.interlocutorForm.get('firstName').enable();
        }
        if (this.getEditable('ff_interlocutorClientCenter_surname1') && !this.blockContrastDataOther) {
            this.interlocutorForm.get('surname1').enable();
        }
        if (this.getEditable('ff_interlocutorClientCenter_surname2') && !this.blockContrastDataOther) {
            this.interlocutorForm.get('surname2').enable();
        }
        if (index == 2) {
            if (this.getEditable('ff_interlocutorClientCenter_phone1') && !this.blockContrastDataOther) {
                this.interlocutorForm.get('phone1').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_phone2') && !this.blockContrastDataOther) {
                this.interlocutorForm.get('phone2').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_extPhone1') && !this.blockContrastDataOther) {
                this.interlocutorForm.get('extPhone1').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_email') && !this.blockContrastDataOther) {
                this.interlocutorForm.get('email').enable();
            }
            if (this.getEditable('ff_interlocutorClientCenter_birthDate') && !this.blockContrastDataOther) {
                this.interlocutorForm.get('birthDate').enable();
            }
        }
    }

    clearFormField(field: string) {
        this.interlocutorForm.get(field).clearValidators();
        this.interlocutorForm.get(field).reset();
        this.interlocutorForm.get(field).disable();
        this.interlocutorForm.get(field).updateValueAndValidity();
    }

    validateHobby(hobby1Id: string, hobby2Id: string) {
        if (hobby1Id != '' && hobby1Id != null) {
            setTimeout(() => {
                if (!this.interlocutorForm.get('hobby1Id').disabled) {
                    this.interlocutorForm.get('hobby2Id').enable();
                }
            });
        } else {
            this.interlocutorForm.get('hobby2Id').disable();
        }

        if (hobby1Id == hobby2Id && hobby1Id != '' && hobby1Id != null && hobby2Id != '' && hobby2Id != null) {
            this.validSameHobby = false;
        } else {
            this.validSameHobby = true;
        }

        this.ref.detectChanges();
    }

    clearHobby() {
        this.ref.detectChanges();
        this.clearFormField('hobby2Id');
        this.validSameHobby = true;
    }

    onChangeMailingType(mailingTypeId: any) {
        if (mailingTypeId != '2' && this.branchOnInit.companyId != 'FUN') {
            if (!this.isNew) {
                this.currentDialog = 'modalDialogInterlocutorTSM';
                this.setSpinner(true);
                this.interlocutorsService
                    .getClientCenterInterlocutors(this.clientId, this.clientCenterId)
                    .then(async data => {
                        //Ocultar spinner
                        this.setSpinner(false);
                        var interlocutorTSM = data.filter(x => x.MailingTypeId == '2');
                        if (interlocutorTSM.length == 1 && interlocutorTSM[0].InterlocutorId == this.interlocutorId && this.isProfessional) {
                            this.currentDialog = 'modalDialogInterlocutorTSM';
                            this.dialogInterlocutorTSM.open();
                        }
                    })
                    .catch(error => {
                        //Ocultar spinner
                        this.setSpinner(false);
                        this.sharedService.showError(error);
                    });
            }
        }
    }

    validateSignerChange(event = null) {
        let allow = true;

        let fiscalDocId = this.interlocutorForm.getRawValue().fiscalDocId;
        let fiscalDocNumber = this.interlocutorForm.getRawValue().fiscalDocNumber;
        let signerChk = this.interlocutorForm.getRawValue().signerChk;
        let functionId = this.interlocutorForm.getRawValue().functionId;
        let portalElement = this.interlocutorForm.getRawValue().portalElement;

        if (this.clientCenterTabs && (this.clientCenterTabs.CompanyId == 'RWS' || this.clientCenterTabs.CompanyId == 'FUN')) {
            let contactTypeId = this.interlocutorForm.getRawValue().contactTypeId;
            let historical = contactTypeId && contactTypeId != null && contactTypeId != '' && contactTypeId == '9';

            if (historical || (this.interlocutor && this.interlocutor.IsPreregistered)) {
                allow = false;
                this.interlocutorForm.get('signerChk').setValue(!signerChk);
                this.sharedService.toastError('La marca de firmante no se puede cambiar');
                if (this.iAction) {
                    signerChk = !signerChk;
                }
            }
        }

        if (allow) {
            this.validateRequiredFiscalDoc(fiscalDocId, fiscalDocNumber, signerChk, functionId);
        }
        this.isPortalSigner = signerChk == true && portalElement != 0 && portalElement != '' && portalElement != null;

        if (this.isNewStructure) {
            let relationTypeId = this.interlocutorForm.get('relationTypeId').value;
            if (this.contactPersonsRelsTypesList.length > 1) {
                if (signerChk) {
                    if (this.branchOnInit.companyId == 'RWS') {
                        this.contactPersonsRelsTypesList = this.contactPersonsRelsTypesListData.filter(x => x.value != '3');
                        if (event) {
                            relationTypeId = '2';
                        }
                    } else {
                        if (this.isNew || this.isEdit) {
                            relationTypeId = '2';
                        }
                    }
                } else {
                    this.interlocutorForm.get('relationTypeId').enable();

                    if (this.isNew || this.isEdit) {
                        if (this.branchOnInit.companyId == 'RWS') {
                            this.contactPersonsRelsTypesList = this.contactPersonsRelsTypesListData;
                        } else {
                            relationTypeId = '';
                        }
                    }
                }
                if (relationTypeId != this.interlocutorForm.get('relationTypeId').value) {
                    this.interlocutorForm.get('relationTypeId').setValue(relationTypeId);
                    this.getValuesForRelationType(relationTypeId);
                }
            }
        }
    }

    validateRequiredFiscalDoc(fiscalDocId: string, fiscalDocNumber: string, signerChk: string, functionId: string) {
        if (
            this.branchOnInit.companyId == 'RPS' ||
            this.branchOnInit.companyId == 'VEX' ||
            this.branchOnInit.companyId == 'RWS' ||
            this.branchOnInit.companyId == 'FUN'
        ) {
            //Los dos informados
            if (fiscalDocId != null && fiscalDocId != '' && fiscalDocNumber != null && fiscalDocNumber != '') {
                this.validCheck = true;
                this.validCheckFiscNumber = true;
                this.requiredFiscalDoc = '';

                if (signerChk || functionId == '74') {
                    this.requiredFiscalDoc = '*';
                }
            }
            //Marcado check y Tipo no informado
            else if ((signerChk || functionId == '74') && (fiscalDocId == null || fiscalDocId == '') && fiscalDocNumber != null && fiscalDocNumber != '') {
                this.validCheck = false;
                this.validCheckFiscNumber = true;
                this.validFiscalDocFilled = true;
                this.requiredFiscalDoc = '*';
            }
            //Marcado check y Numero no informado
            else if ((signerChk || functionId == '74') && (fiscalDocNumber == null || fiscalDocNumber == '') && fiscalDocId != null && fiscalDocId != '') {
                this.validCheckFiscNumber = false;
                this.validCheck = true;
                this.validFiscalDocFilled = true;
                this.requiredFiscalDoc = '*';
            }
            //Ninguno informado
            else {
                if (signerChk || functionId == '74') {
                    this.validCheck = false;
                    this.validCheckFiscNumber = false;
                    this.validFiscalDocFilled = true;
                    this.requiredFiscalDoc = '*';
                } else {
                    this.validCheck = true;
                    this.validCheckFiscNumber = true;
                    this.requiredFiscalDoc = fiscalDocId ? '*' : '';
                }
            }
        }
        if (!this.interlocutorSearchDisable && fiscalDocNumber.length > 0) {
            this.requiredFiscalDoc = '*';
        }
    }

    async searchInterlocutor() {
        this.setSpinner(true);
        let fiscalDocNumber = this.interlocutorForm.get('fiscalDocNumber');
        let fiscalDocId = this.interlocutorForm.get('fiscalDocId');
        let email = this.interlocutorForm.get('email');
        let phone1 = this.interlocutorForm.get('phone1');

        phone1.markAsTouched();
        email.markAsTouched();
        fiscalDocNumber.markAsTouched();
        fiscalDocId.markAsTouched();

        if (email.valid && phone1.valid && fiscalDocNumber.valid && fiscalDocId.valid) {
            if (
                this.validFiscalDocLenght &&
                this.validFiscalDocLetter &&
                this.validFiscalDocFormat &&
                this.validFiscalDocFilled &&
                this.validCheckFiscNumber &&
                this.validFiscalDocDecisor
            ) {
                await this.interlocutorsService
                    .searchOInterlocutor(fiscalDocNumber.value.toUpperCase(), email.value, phone1.value)
                    .then(data => {
                        data.forEach((element, index) => {
                            element.LastName = `${element.Surname1} ${element.Surname2 != null ? element.Surname2 : ''}`;
                            element.Index = index + 1;
                        });

                        this.dataDocRequired = null;
                        if (data.length != 0) {
                            this.titleModal = 'Parece que esta persona de contacto ya existe';
                            this.dataDocRequired = data;
                            this.listInterlocutorsExistModal.openDialog(data);
                        } else {
                            if (email.value == '' || phone1.value == '') {
                                this.requiredFiscalDoc = '';
                            } else {
                                this.titleModal = '';
                                this.newInterlocutor();
                                this.validateChangePhones(this.interlocutorForm.getRawValue().phone1, this.interlocutorForm.getRawValue().phone2);
                                this.expandedPanel(this.panelContactForm, 'true');
                                this.expandedPanel(this.relationRandstad, 'true');
                                this.expandedPanel(this.panelPersonalInfo, 'true');
                                this.expandedPanel(this.panelBehaviour, 'true');
                                this.expandedPanel(this.panelInterlocutorPersonAddress, this.iAction ? 'false' : 'true');
                                if (this.isGgcc && this.isKam) {
                                    setTimeout(() => {
                                        this.interlocutorForm.get('hideSensitiveDataChk').enable();
                                    });
                                }
                            }
                        }
                    })
                    .catch(error => {
                        this.sharedService.showError(error);
                        this.setSpinner(false);
                    });
            } else {
                this.sharedService.toastError('El N° de documento no es válido');
            }
        } else {
            this.sharedService.toastError('Debes completar los campos obligatorios');
        }

        this.setSpinner(false);
    }

    expandedPanel(panel: ElementRef, expanded: string = '') {
        if (panel && panel.nativeElement) {
            let currentExpanded = panel.nativeElement.getAttribute('aria-expanded');
            if (expanded == '') {
                let targetId = panel.nativeElement.getAttribute('data-target');
                expanded = document.querySelector(targetId + ' .error-msg') && !document.querySelector(targetId + '.in') ? 'true' : currentExpanded;
            }
            if (currentExpanded != expanded) {
                panel.nativeElement.click();
            }
        }
    }

    async loadDataInterlocutor(interlocutor: any) {
        if (!interlocutor) {
            this.sharedService.toastError('Debes seleccionar una persona de contacto para cargar los datos');
        } else {
            this.setSpinner(true);
            await this.centersService
                .getContactPersonDetails(interlocutor.ContactPersonId, interlocutor.ContactPersonRelId)
                .then(data => {
                    this.interlocutor = new ClientCenterInterlocutorDetail();
                    this.allowEnableControls = true;
                    this.interlocutorSearchDisable = true;
                    this.existContactPerson = true;
                    this.enabledAll();
                    if (this.clientCenterTabs) {
                        if (this.clientCenterTabs.CompanyId == 'RWS' && interlocutor.CertificateStatusId != null && interlocutor.CertificateStatusId != '') {
                            if (interlocutor.CertificateStatusId != '7') {
                                this.blockCertificateData = true;
                                this.sharedService.toastSuccess(
                                    'Datos de persona de contacto recuperados exitosamente. Si quieres modificarlos ponte en contacto con el Centro de Soporte.'
                                );
                            }
                        }
                    }
                    this.expandPanelInterlocutor();

                    let expanded = this.panelContactForm.nativeElement.getAttribute('aria-expanded');

                    if (expanded == 'false') {
                        this.panelContactForm.nativeElement.click();
                    }

                    if (this.isNewStructure && this.isNew && !this.iAction) {
                        this.expandedPanel(this.relationRandstad, 'true');
                    }

                    this.interlocutor = data;
                    this.loadDialogDataInterlocutor();
                    this.disabledContactPersonFields();
                    this.interlocutorForm.get('mailingTypeId').setValue('2');
                    this.checkProvince(this.interlocutor.AddressCountryId, false);
                    this.interlocutorForm.get('addressProvinceId').setValue(this.interlocutor.AddressProvinceId);
                    this.checkCity(this.interlocutor.AddressProvinceId, false);
                    this.setSpinner(false);
                })
                .catch(error => {
                    this.setSpinner(false);
                    this.existContactPerson = false;
                    this.sharedService.showError(error);
                });
        }
    }

    expandPanelInterlocutor() {
        if (this.panelInterlocutor) {
            let expanded = this.panelInterlocutor.nativeElement.getAttribute('aria-expanded');

            if (expanded == 'false') {
                this.panelInterlocutor.nativeElement.click();
            }
        }
    }

    disabledContactPersonFields() {
        this.interlocutorForm.get('firstName').disable();
        this.interlocutorForm.get('surname1').disable();
        this.interlocutorForm.get('surname2').disable();
        this.interlocutorForm.get('birthDate').disable();
        this.interlocutorForm.get('sexId').disable();
        this.interlocutorForm.get('languageId').disable();
        this.interlocutorForm.get('fiscalDocId').disable();
        this.interlocutorForm.get('fiscalDocNumber').disable();
        this.interlocutorForm.get('email').disable();
        this.interlocutorForm.get('phone1').disable();
        this.interlocutorForm.get('phone2').disable();
        this.interlocutorForm.get('functionId').disable();
        this.interlocutorForm.get('detailFunction').disable();
        this.interlocutorForm.get('hobby1Id').disable();
        this.interlocutorForm.get('hobby2Id').disable();

        this.interlocutorForm.get('signerChk').disable();
        this.interlocutorForm.get('prlChk').disable();
        this.interlocutorForm.get('cexChk').disable();
        this.interlocutorForm.get('signerBChk').disable();
        this.interlocutorForm.get('decisorChk').disable();
        this.interlocutorForm.get('mailingChk').disable();
        this.interlocutorForm.get('shouldReceiveSurveyChk').disable();
        this.interlocutorForm.get('centerCostSeq').disable();

        this.interlocutorForm.get('addressCountryId').disable();
        this.interlocutorForm.get('addressId').disable();
        this.interlocutorForm.get('addressStreet').disable();
        this.interlocutorForm.get('addressNumber').disable();
        this.interlocutorForm.get('addressBlock').disable();
        this.interlocutorForm.get('addressStair').disable();
        this.interlocutorForm.get('addressFloor').disable();
        this.interlocutorForm.get('letter').disable();
        this.interlocutorForm.get('addressProvinceId').disable();
        this.interlocutorForm.get('addressZipCode').disable();
        this.interlocutorForm.get('addressCityId').disable();
        this.interlocutorForm.get('addressAditional').disable();
        this.ref.detectChanges();
    }

    disabledAll() {
        // Funcion para desactivar los campos al seleccionar interlocutor esten deshabilitados
        if (
            this.getEditable('ff_interlocutorClientCenter_firstName') &&
            this.interlocutorForm.getRawValue().firstName != '' &&
            this.interlocutorForm.getRawValue().firstName != null
        ) {
            setTimeout(() => {
                this.interlocutorForm.get('firstName').disable();
            });
        }

        if (
            this.getEditable('ff_interlocutorClientCenter_surname1') &&
            this.interlocutorForm.getRawValue().surname1 != '' &&
            this.interlocutorForm.getRawValue().surname1 != null
        ) {
            setTimeout(() => {
                this.interlocutorForm.get('surname1').disable();
            });
        }

        if (
            this.getEditable('ff_interlocutorClientCenter_surname2') &&
            this.interlocutorForm.getRawValue().surname2 != '' &&
            this.interlocutorForm.getRawValue().surname2 != null
        ) {
            setTimeout(() => {
                this.interlocutorForm.get('surname2').disable();
            });
        }

        if (
            this.getEditable('ff_interlocutorClientCenter_birthDate') &&
            this.interlocutorForm.getRawValue().birthDate != '' &&
            this.interlocutorForm.getRawValue().birthDate != null
        ) {
            setTimeout(() => {
                this.interlocutorForm.get('birthDate').disable();
            });
        }

        if (
            this.getEditable('ff_interlocutorClientCenter_sexId') &&
            this.interlocutorForm.getRawValue().sexId != '' &&
            this.interlocutorForm.getRawValue().sexId != null
        ) {
            setTimeout(() => {
                this.interlocutorForm.get('sexId').disable();
            });
        }

        if (
            this.getEditable('ff_interlocutorClientCenter_languageId') &&
            this.interlocutorForm.getRawValue().languageId != '' &&
            this.interlocutorForm.getRawValue().languageId != null
        ) {
            setTimeout(() => {
                this.interlocutorForm.get('languageId').disable();
            });
        }

        if (
            this.getEditable('ff_interlocutorClientCenter_fiscalDocId') &&
            this.interlocutorForm.getRawValue().fiscalDocId != '' &&
            this.interlocutorForm.getRawValue().fiscalDocId != null
        ) {
            setTimeout(() => {
                this.interlocutorForm.get('fiscalDocId').disable();
            });
        }

        if (
            this.getEditable('ff_interlocutorClientCenter_fiscalDocNumber') &&
            this.interlocutorForm.getRawValue().fiscalDocNumber != '' &&
            this.interlocutorForm.getRawValue().fiscalDocNumber != null
        ) {
            setTimeout(() => {
                this.interlocutorForm.get('fiscalDocNumber').disable();
            });
        }

        if (
            this.getEditable('ff_interlocutorClientCenter_email') &&
            this.interlocutorForm.getRawValue().email != '' &&
            this.interlocutorForm.getRawValue().email != null
        ) {
            setTimeout(() => {
                this.interlocutorForm.get('email').disable();
            });
        }

        if (
            this.getEditable('ff_interlocutorClientCenter_phone1') &&
            this.interlocutorForm.getRawValue().phone1 != '' &&
            this.interlocutorForm.getRawValue().phone1 != null
        ) {
            setTimeout(() => {
                this.interlocutorForm.get('phone1').disable();
            });
        }

        if (
            this.getEditable('ff_interlocutorClientCenter_phone2') &&
            this.interlocutorForm.getRawValue().phone2 != '' &&
            this.interlocutorForm.getRawValue().phone2 != null
        ) {
            setTimeout(() => {
                this.interlocutorForm.get('phone2').disable();
            });
        }

        this.ref.detectChanges();
    }

    newInterlocutor() {
        this.allowEnableControls = true;
        this.isNewInterlocutor = true;
        this.interlocutorSearchDisable = true;
        this.validatePhones(this.interlocutorForm.getRawValue().phone1, this.interlocutorForm.getRawValue().phone2);
        this.enabledAll();
        let expanded = this.panelInterlocutor.nativeElement.getAttribute('aria-expanded');

        if (expanded == 'false') {
            this.panelInterlocutor.nativeElement.click();
        }
    }

    newContactPersonModal() {
        if (this.interlocutorForm.get('fiscalDocNumber').value && this.dataDocRequired) {
            var i = 0;
            this.dataDocRequired.forEach(pos => {
                if (this.interlocutorForm.get('fiscalDocNumber').value == pos.FiscalDocNumber) {
                    this.sharedService.toastError('Este NIF/NIE ya existe para otra Persona de Contacto, no se permite su duplicidad.');
                    i = i + 1;
                    return;
                }
            });
            if (i == 1) {
                return;
            }
        }

        this.newInterlocutor();
        this.validateChangePhones(this.interlocutorForm.getRawValue().phone1, this.interlocutorForm.getRawValue().phone2);
        if (this.interlocutorForm.get('email').value) this.interlocutorForm.get('email').disable();
        if (this.interlocutorForm.get('phone1').value) this.interlocutorForm.get('phone1').disable();
        if (this.interlocutorForm.get('phone2').value) this.interlocutorForm.get('phone2').disable();
        if (this.interlocutorForm.get('fiscalDocNumber').value) this.interlocutorForm.get('fiscalDocNumber').disable();
        this.expandedPanel(this.panelContactForm, 'true');
        this.expandedPanel(this.relationRandstad, 'true');
        this.expandedPanel(this.panelPersonalInfo, 'true');
        this.expandedPanel(this.panelBehaviour, 'true');
        this.expandedPanel(this.panelInterlocutorPersonAddress, this.iAction ? 'false' : 'true');
        if (this.isGgcc && this.isKam) {
            setTimeout(() => {
                this.interlocutorForm.get('hideSensitiveDataChk').enable();
            });
        }
    }

    validateContactType() {
        if (this.clientCenterTabs.CompanyId == 'RWS' || this.clientCenterTabs.CompanyId == 'FUN') {
            let portalElement = this.interlocutorForm.getRawValue().portalElement;
            let portal = portalElement && portalElement != null && portalElement != '' && portalElement != '0';
            let contactTypeId = this.interlocutorForm.getRawValue().contactTypeId;
            let historical = contactTypeId && contactTypeId != null && contactTypeId != '' && contactTypeId == '9';

            if (historical && portal) {
                this.interlocutorForm.get('contactTypeId').setValue('1');
                this.sharedService.toastError(
                    'No puedes marcar como Inactivo a un interlocutor dado de alta en Portal. Ponte en contacto con el Centro de Soporte para realizar esta acción'
                );
            }
        }
    }

    async searchCenters() {
        this.setSpinner(true);
        let clientId = this.interlocutorForm.get('clientId');
        let clientFiscalName = this.interlocutorForm.get('clientFiscalName');
        let documentNumber = this.interlocutorForm.get('documentNumber');
        this.clientCenterClearControls();
        this.interlocutorForm.get('client').setValue('');

        if (
            (clientId.value != '' && clientId.valid) ||
            (clientFiscalName.value != '' && clientFiscalName.valid) ||
            (documentNumber.value != '' && documentNumber.valid)
        ) {
            await this.centersService
                .getCenterClientsToInterlocutor(this.branchOnInit.id, clientId.value, clientFiscalName.value, documentNumber.value)
                .then(data => {
                    this.clientCenterList = data;
                    if (this.getEditable('ff_interlocutorClientCenter_client')) {
                        this.interlocutorForm.controls.client.enable();
                    }
                })
                .catch(error => {
                    this.sharedService.showError(error);
                    this.setSpinner(false);
                });
        } else {
            this.sharedService.toastError('Debes completar un dato obligatorio en la búsqueda de cliente centro');
        }

        this.setSpinner(false);
    }

    private clientCenterClearControls() {
        this.interlocutorForm.get('addressId').setValue('');
        this.interlocutorForm.get('addressStreet').setValue('');
        this.interlocutorForm.get('addressNumber').setValue('');
        this.interlocutorForm.get('addressCountryId').setValue('');
        this.interlocutorForm.get('addressProvinceId').setValue('');
        this.interlocutorForm.get('addressCityId').setValue('');
        this.interlocutorForm.get('addressZipCode').setValue('');

        if (this.isNewStructure) {
            this.interlocutorForm.get('addressBlock').setValue('');
            this.interlocutorForm.get('addressStair').setValue('');
            this.interlocutorForm.get('addressFloor').setValue('');
            this.interlocutorForm.get('letter').setValue('');
        }
    }

    async setClientCenterOnInit() {
        if (this.iAction) {
            await this.centersService
                .getCenterClientsToInterlocutor(this.branchOnInit.id, this.clientId, '', '')
                .then(async data => {
                    this.clientCenterList = data;
                    if (this.getEditable('ff_interlocutorClientCenter_client')) {
                        this.interlocutorForm.controls.client.enable();
                        await this.setClientCenter(`${this.clientId.toString()} - ${this.clientCenterId.toString()}`);
                    }
                })
                .catch(error => {
                    this.sharedService.showError(error);
                    this.setSpinner(false);
                });
        }
    }

    async getValuesForRelationType(relationTypeId: string) {
        this.valuesForRelationType = [];
        if (this.interlocutorForm) {
            this.cecoList = [];
            this.interlocutorForm.get('centerCostSeq').setValue('');
            this.interlocutorForm.get('relationTypeValue').enable();
            if (this.currentEmployee) {
                this.interlocutorForm.get('relationTypeValue').setValue('');
                this.valuesForRelationRandstad = [];
                this.valuesForRelationRandstad.push({ value: this.currentEmployee.value, label: this.currentEmployee.label });
                this.interlocutorForm.get('relationRandstadValue').setValue(this.currentEmployee.value);
            }
        }

        if (relationTypeId == '1') {
            this.relationLabel = 'Grupo';
            this.expandedPanel(this.panelInterlocutorPersonAddress, 'true');
            this.setSpinner(true);
            await this.centersService
                .getMyDBGroups(this.branchOnInit.id)
                .then(async data => {
                    this.valuesForRelationType = data;
                    this.setSpinner(false);
                })
                .catch(error => {
                    this.sharedService.showError(error);
                    this.setSpinner(false);
                });
        } else if (relationTypeId == '2') {
            this.relationLabel = 'Cliente';
            this.expandedPanel(this.panelInterlocutorPersonAddress, 'true');
            this.setSpinner(true);
            await this.centersService
                .getMyDBClients(this.branchOnInit.id)
                .then(async data => {
                    this.valuesForRelationType = data;
                    if (this.clientId) {
                        this.interlocutorForm.get('relationTypeValue').setValue(this.clientId);
                    }
                    this.setSpinner(false);
                })
                .catch(error => {
                    this.sharedService.showError(error);
                    this.setSpinner(false);
                });
        } else if (relationTypeId == '3') {
            this.relationLabel = 'Centro';
            this.expandedPanel(this.panelInterlocutorPersonAddress, 'false');
            this.setSpinner(true);
            await this.centersService
                .getMyDBClientCenter(this.branchOnInit.id)
                .then(async data => {
                    this.valuesForRelationType = data;
                    if (this.clientId && this.clientCenterId) {
                        this.interlocutorForm.get('relationTypeValue').setValue(`${this.clientId} - ${this.clientCenterId}`);
                    }
                    this.setSpinner(false);
                })
                .catch(error => {
                    this.sharedService.showError(error);
                    this.setSpinner(false);
                });
        }
    }

    async onChangeRelationTypeValue(relationTypeValue: any) {
        let relationTypeId = this.interlocutorForm.get('relationTypeId').value;
        this.valuesForRelationRandstad = [];

        if (relationTypeId == '3') {
            this.interlocutorForm.get('addressId').setValue(relationTypeValue.AddressId);
            this.interlocutorForm.get('addressStreet').setValue(relationTypeValue.AddressStreet);
            this.interlocutorForm.get('addressNumber').setValue(relationTypeValue.AddressNumber);
            this.interlocutorForm.get('addressStair').setValue(relationTypeValue.AddressStair);
            this.interlocutorForm.get('addressBlock').setValue(relationTypeValue.AddressBlock);
            this.interlocutorForm.get('addressFloor').setValue(relationTypeValue.AddressFloor);
            this.interlocutorForm.get('letter').setValue(relationTypeValue.AddressDoor);
            this.interlocutorForm.get('addressAditional').setValue(relationTypeValue.AddressAditional);
            this.interlocutorForm.get('addressCountryId').setValue(relationTypeValue.AddressCountryId);
            this.checkProvince(relationTypeValue.AddressCountryId);
            this.interlocutorForm.get('addressProvinceId').setValue(relationTypeValue.AddressProvinceId);
            this.checkCity(relationTypeValue.AddressProvinceId);
            this.interlocutorForm.get('addressCityId').setValue(relationTypeValue.AddressCityId);
            this.interlocutorForm.get('addressZipCode').setValue(relationTypeValue.AddressZipCode);

            this.valuesForRelationRandstad.push({ value: relationTypeValue.PUserId, label: relationTypeValue.PUserName });
            this.interlocutorForm.get('relationRandstadValue').setValue(relationTypeValue.PUserId);
            this.setSpinner(true);

            await this.centersService
                .getCentersCosts(relationTypeValue.ClientId, relationTypeValue.ClientCenterId, true)
                .then(data => {
                    this.cecoList = data;
                    this.setSpinner(false);
                })
                .catch(error => {
                    this.sharedService.showError(error);
                    this.setSpinner(false);
                });
        } else {
            this.cecoList = [];
            this.valuesForRelationRandstad.push({ value: this.currentEmployee.value, label: this.currentEmployee.label });
            this.interlocutorForm.get('relationRandstadValue').setValue(this.currentEmployee.value);
        }
        this.interlocutorForm.get('centerCostSeq').setValue('');
    }

    async getCurrentEmployee(): Promise<any> {
        await this.centersService
            .getUsersByFiscalDocNumber(this.tokenInfo.nameid, this.branchOnInit.id)
            .then(branchUsers => {
                let branchUsersList = branchUsers.filter(x => x.value == this.branchOnInit.userId);
                if (branchUsersList && branchUsersList.length > 0) {
                    this.currentEmployee = branchUsersList[0];
                }
            })
            .catch(error => {
                this.sharedService.showError(error);
            });

        if (!this.currentEmployee) {
            await this.centersService
                .getUsersByFiscalDocNumber(this.tokenInfo.nameid, '', this.branchOnInit.unitId)
                .then(unitUsers => {
                    if (unitUsers && unitUsers.length > 0) {
                        this.currentEmployee = unitUsers[0];
                    }
                })
                .catch(error => {
                    this.sharedService.showError(error);
                });
        }

        if (!this.currentEmployee) {
            await this.centersService
                .getEmployee(this.tokenInfo.nameid, this.branchOnInit.id)
                .then(data => {
                    this.currentEmployee = data;
                    this.currentEmployee.label =
                        this.currentEmployee.Surname2 !== null
                            ? this.currentEmployee.FirstName + ' ' + this.currentEmployee.Surname1 + ' ' + this.currentEmployee.Surname2
                            : this.currentEmployee.FirstName + ' ' + this.currentEmployee.Surname1;
                })
                .catch(error => {
                    this.sharedService.showError(error);
                });
        }
    }

    ///////////////////////////////////////////////// eSolution  -

    initEsolutionForm() {
        // Para el componente ng-select
        let descriptionValidator = [];

        if (this.getMandatory('ff_searchEsolution_description')) {
            descriptionValidator.push(Validators.required);
        }

        this.esolutionForm = this.formBuilder.group({
            type: [{ value: '', disabled: !this.getEditable('ff_searchEsolution_description') }, descriptionValidator],

            urlEsolution: [{ value: '', disabled: !this.getEditable('ff_searchEsolution_urlEsolution') }, [Validators.pattern(/^(ftp|http|https):\/\/[^ "]+$/)]]
        });
    }

    changeModeEsolution(isNew: boolean) {
        if (isNew) {
            this.setSpinner(true);
            this.isNewEsolution = isNew;
            this.isActionDetail = false;
            this.isDetailModeEsolution = false;
            if (this.iAction) {
                this.oCallbackChgModESolEvent.emit();
            }

            this.onChangeMode.emit(this.isActionDetail);
            this.setInterlocutorHeader('Nueva solucion especifica');
            this.initEsolutionForm();
            this.setSpinner(false);

            let expanded = this.listPanelHeaderEsolution.nativeElement.getAttribute('aria-expanded');

            if (expanded == 'false') {
                this.listPanelHeaderEsolution.nativeElement.click();
            }
        } else {
            this.setSpinner(true);
            this.isActionDetail = true;
            this.isDeleteEsolution = true;
            this.isDetailModeEsolution = true;
            this.onChangeMode.emit(this.isActionDetail);

            this.setSpinner(false);

            let expanded = this.listPanelHeaderEsolution.nativeElement.getAttribute('aria-expanded');

            if (expanded == 'false') {
                this.listPanelHeaderEsolution.nativeElement.click();
            }
        }
    }

    //Validar Formulario
    validateSaveEsolutionForm() {
        return this.esolutionForm.valid;
    }

    //Ventana modal
    openDeleteEsolution() {
        this.changeModeEsolution(false);
        this.currentDialog = 'modalDialogDeleteEsolution';
        this.dialogDeleteEsolution.open();
    }

    resetEsolutionForm() {
        if (this.esolutionForm) {
            for (const key in this.esolutionForm.controls) {
                this.clearFormFieldEsolutions(key);
            }
            this.esolutionForm = undefined;
        }
    }

    clearFormFieldEsolutions(field: string) {
        this.esolutionForm.get(field).clearValidators();
        this.esolutionForm.get(field).reset();
        this.esolutionForm.get(field).disable();
        this.esolutionForm.get(field).updateValueAndValidity();
    }

    paginationEsolution(page: number) {
        if (page !== this.paginationParamsEsolution.currentPage) {
            this.paginationParamsEsolution.currentPage = page;
            this.paginationParamsEsolution.currentIndex = page - 1;
        }
    }

    //Obtencion token para acceso eSolution y llamada al API eSolutions
    public async esolutionApi(portalElement: number) {
        await this.raasService
            .getCaasToken()
            .then(async caas => {
                await this.centersService
                    .getUserDataStudio(portalElement, caas.access_token)
                    .then(data => {
                        this.clientEsolutionsList = data;
                        this.setSpinner(false);
                        this.isNewEsolution = false;
                    })
                    .catch(error => {
                        this.setSpinner(false);
                        this.isNewEsolution = false;
                        this.sharedService.showError(error);
                    });
            })
            .catch(error => {
                this.setSpinner(false);
                this.isNewEsolution = false;
                this.sharedService.showError(error);
            });
    }

    async loadEsolution(portalElement: number): Promise<void> {
        if (portalElement > 0) {
            this.setSpinner(true);
            let existKnResp = this.isNewStructure
                ? this.centersService.checkKnRespContactPerson(this.interlocutor.InterlocutorId, portalElement, this.clientCenterTabs.BranchId)
                : this.centersService.checkKnRespInterlocutor(
                      this.interlocutor.ClientId,
                      this.interlocutor.ClientCenterId,
                      this.interlocutor.InterlocutorId,
                      portalElement,
                      this.clientCenterTabs.BranchId
                  );
            await existKnResp
                .then(async data => {
                    await this.esolutionApi(portalElement);
                    this.esolutionPaginationList[0] = [];
                    let count2 = 0;
                    if (this.clientEsolutionsList.length > 0) {
                        //Paginacion lista soluciones especificas
                        for (let i = 0; i < this.clientEsolutionsList.length; i += this.paginationParamsEsolution.pageMaxSize) {
                            let nextIndex = Math.min(this.paginationParamsEsolution.pageMaxSize * (count2 + 1), this.clientEsolutionsList.length);
                            let currentList = this.clientEsolutionsList.slice(i, nextIndex);
                            this.esolutionPaginationList[count2] = currentList;
                            count2++;
                        }
                    }
                    this.setSpinner(false);
                })
                .catch(error => {
                    this.sharedService.showError(error);
                    this.setSpinner(false);
                });
        }
    }

    //Seleccion de esolution
    async checkEsolution(esolution: any) {
        // Si el interlocutor estaba ya seleccionado, es una deselección
        if (this.selectedEsolution && this.selectedEsolution.IdAplicacion === esolution.IdAplicacion) {
            this.selectedEsolution = undefined;
        } else {
            this.selectedEsolution = esolution;
            this.setSpinner(false);
        }
    }

    async changeModeDetailEsolution() {
        this.setSpinner(true);
        this.isActionDetail = true;
        this.onChangeMode.emit(this.isActionDetail);
        this.isNewEsolution = false;
        this.isDeleteEsolution = false;
        this.resetEsolutionForm();
        this.setInterlocutorHeader(this.panelTitle);
        this.setSpinner(false);
    }

    //Funcion para eliminar
    public async deleteEsolution(model: any) {
        this.setSpinner(true);
        await this.raasService
            .getCaasToken()
            .then(async caas => {
                await this.centersService
                    .putUserDataStudio(model, caas.access_token)
                    .then(() => {
                        this.sharedService.toastSuccess(this.msgOkDeleteEsolution);
                        this.selectedEsolution = undefined;
                        this.changeModeDetailEsolution();
                        this.loadEsolution(model.knResp);
                        this.setSpinner(false);
                        this.isDetailModeEsolution = true;
                    })
                    .catch(error => {
                        this.setSpinner(false);
                        this.isDeleteEsolution = false;
                        this.isDetailModeEsolution = true;
                        this.sharedService.showError(error);
                    });
            })
            .catch(error => {
                this.setSpinner(false);
                this.isDeleteEsolution = false;
                this.isDetailModeEsolution = true;
                this.sharedService.showError(error);
            });
    }

    getSolutionTypeDescription(type: string) {
        let typeSolution = this.typeEsolutionList.filter(x => x.value == type)[0];
        return typeSolution.label;
    }

    //Guardar datos de eSolution
    async saveDataEsolution(model: any): Promise<void> {
        this.setSpinner(true);
        if (this.validateSaveEsolutionForm()) {
            let esolModel = {
                type: model.type,
                descripcion: this.getSolutionTypeDescription(model.type),
                url: model.urlEsolution,
                knResp: this.interlocutor.PortalElement
            };
            if (this.isSave == false) {
                await this.createEsolution(esolModel);
            }
        } else {
            this.sharedService.scrollToError(this.esolutionForm, this.el);
            this.setSpinner(false);
        }
    }

    //Llamada al api de creacion
    public async createEsolution(model: any): Promise<void> {
        if (this.isSave == false) {
            this.isSave = true;
            await this.raasService
                .getCaasToken()
                .then(async caas => {
                    await this.centersService
                        .postUserDataStudio(model, caas.access_token)
                        .then(() => {
                            this.isSave = true;
                            this.sharedService.toastSuccess(this.msgOkEsolution);
                            this.changeModeDetailEsolution();
                            this.loadEsolution(model.knResp);
                        })
                        .catch(error => {
                            this.isSave = false;
                            this.changeModeDetailEsolution();
                            this.sharedService.showError(error);
                        });
                })
                .catch(error => {
                    this.isSave = false;
                    this.changeModeDetailEsolution();
                    this.sharedService.showError(error);
                });
        }
    }

    principalChkSwitchToggle(checked: any) {
        this.interlocutorForm.get('principalChk').setValue(checked);
    }

    controlsCompaniesContactPersonRels() {
        this.isMailingTypeIdHidden = true;
        this.isCenterCostHidden = true;
        if (this.branchOnInit.companyId == 'RCO' || this.branchOnInit.companyId == 'EXP') {
            this.isMailingTypeIdHidden = false;
        }
        if (this.branchOnInit.companyId == 'RWS') {
            this.isCenterCostHidden = false;
        }
    }

    async validateFiscalDocDuplicatePC(fiscalDocNumber: string) {
        if (
            fiscalDocNumber != '' &&
            fiscalDocNumber != null &&
            this.validFiscalDocLenght &&
            this.validFiscalDocLetter &&
            this.validFiscalDocFormat &&
            this.validFiscalDocFilled &&
            this.isNewStructure
        ) {
            this.setSpinner(true);

            await this.centersService
                .validateFiscalNumberContactPersonIsDuplicated(fiscalDocNumber, this.interlocutor.InterlocutorId)
                .then(data => {
                    this.validFiscalDocNotDuplicated = !data;
                    this.setSpinner(false);
                })
                .catch(() => {
                    this.setSpinner(false);
                });
        }
    }

    ////////////////////////////////////////////////////////////////////
    // Funciones para aplicar los permisos de Gestor

    async getAllPermissions(): Promise<any> {
        let promiseList = [];
        promiseList.push(this.accessManagerService.getResourcePermissions(2565));
        promiseList.push(this.accessManagerService.getResourcePermissions(2628));
        return await forkJoin(promiseList).toPromise();
    }

    async getBranchPermission(branchId: string): Promise<void> {
        this.branchPermissions = await this.accessManagerService.getResourcePermissions(2565, branchId);
    }

    getVisible(resourceName: string) {
        return this.accessManagerService.GetPermissions(resourceName, this.permission, AccessManagerResourceActionType.VisibleId);
    }

    getEditable(resourceName: string) {
        return this.accessManagerService.GetPermissions(resourceName, this.permission, AccessManagerResourceActionType.EnableId);
    }

    getMandatory(resourceName: string) {
        return this.accessManagerService.GetPermissions(resourceName, this.permission, AccessManagerResourceActionType.MandatoryId);
    }

    getEditableUser(resourceName: string) {
        return this.accessManagerService.GetPermissions(resourceName, this.permissionUser, AccessManagerResourceActionType.EnableId);
    }

    getEditableForBranch(resourceName: string) {
        if (!this.branchPermissions) {
            return true;
        }
        return this.accessManagerService.GetPermissions(resourceName, this.branchPermissions, AccessManagerResourceActionType.EnableId);
    }
}