import { AfterViewInit, Component, Inject, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { UserResponse, UsersResponse } from '../../../interfaces/users.interface';
import { lastValueFrom, map, Observable, startWith } from 'rxjs';
import { MatStepper } from '@angular/material/stepper';
import { ComponentInformationSelect, DataDialogComponentSelect, FormDataPersonality, GetDataTable, GetInformationDataSelect, GetTables, ResponseDataGetInformationDataSelect, ResponseDataGetTables, TypeFormDataPersonality } from '../../../interfaces/forms-management/form-management.interface';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { ResourcesService } from '../../../services/resources.service';
import { SystemAdminService } from '../../../services/system-admin.service';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { EncService } from '../../../services/enc.service';
import { DynamicFormService } from '../../../services/forms-management/dynamic-form.service';
import { MaterialIcon, MaterialIconsResponse } from '../../../interfaces/material-icons.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { ExampleComponentComponent } from '../example-component/example-component.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-configurate-select',
    templateUrl: './configurate-select.component.html',
    styleUrl: './configurate-select.component.css',
    standalone: false
})
export class ConfigurateSelectComponent implements OnInit, AfterViewInit {

  public formGroupConfigure: FormGroup;
  public isLoading: boolean;
  public isLoadingIcon: boolean;
  public isLoadingUser: boolean;

  public typeForm: 'R' | 'M';
  
  public arrIcons: string[];
  public arrUsers: UserResponse[];
  public arrColumns: string[];
  public arrIdentification: string[];
  
  public filteredOptionsIcons!: Observable<string[]>;
  @ViewChild('stepper') stepper!: MatStepper;
  public getIndexStep: number;
  
  public formGroupDataInformation: FormGroup;
  public arrTablesName: GetTables[];
  public arrColumnsTable: GetTables[];
  public isLoadingFieldTableName: boolean;

  public dataSourceInformationTable: MatTableDataSource<GetInformationDataSelect>;
  @ViewChild('paginatorInformationTable') paginatorDataInformationTable!: MatPaginator;
  public displayedColumnsInformationTable: string[];
  public isLoadingInformationTable: boolean;

  public formGroupPersonalityData: FormGroup;
  public dataSourcePersonality: MatTableDataSource<FormDataPersonality>;
  public displayedColumnsPersonality: string[];
  @ViewChild('paginatorDataPersonality') paginatorDataPersonality!: MatPaginator;
  public typeFormDataPersonality: TypeFormDataPersonality;
  public isLoadingPersonalityData: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public infoDataForm: DataDialogComponentSelect,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<false | ComponentInformationSelect>,
    private _systemAdminService: SystemAdminService,
    private _usersProfilesService: UsersProfilesService,
    private _encService: EncService,
    private _dynamicFormService: DynamicFormService,
  ) {
    this.typeForm = this.infoDataForm.TYPE_FORM;
    this.isLoading = false;
    this.isLoadingIcon = false;
    this.isLoadingUser = false;
    
    this.formGroupConfigure = this._createFormGroupConfigure();
    
    this.arrIcons = [];
    this.arrUsers = [];
    this.arrColumns = this.infoDataForm.COLUMNS;
    this.arrIdentification = this.infoDataForm.IDS;
    
    this.getIndexStep = 0;
    this.formGroupDataInformation = this._createFormGroupDataInformation();
    this.arrTablesName = [];
    this.arrColumnsTable = [];
    this.isLoadingFieldTableName = false;
    
    this.formGroupPersonalityData = this._createFormGroupPersonalityData();
    this.dataSourceInformationTable = new MatTableDataSource<GetInformationDataSelect>
    this.displayedColumnsInformationTable = [ 'NO', 'VALOR', 'NOMBRE', 'ACCIONES' ];
    this.isLoadingInformationTable = false;
    
    this.dataSourcePersonality = new MatTableDataSource<FormDataPersonality>();
    this.displayedColumnsPersonality = [ 'NO', 'VALOR', 'NOMBRE', 'ACCIONES' ];
    this.typeFormDataPersonality = { TYPE_FORM: 'R' };
    this.isLoadingPersonalityData = false;    
  }
  
  async ngOnInit() {
    this.isLoading = true;
    await this._getMaterialIcons();
    await this._getUsers();
    await this._getTablesName();
    this._getInformationComponent();
    this.isLoading = false;

    this.filteredOptionsIcons = this.formGroupConfigure.controls['ICONO'].valueChanges.pipe(
      startWith(''),
      map((value: any) => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.arrIcons.filter(option => option.toLowerCase().includes(filterValue));
      })
    );

    this.formGroupDataInformation.controls['TABLA'].valueChanges.subscribe((table: string) => {      
      if (table === '' || table === null || table === undefined) {
        this.formGroupDataInformation.controls['COLUMNA_VALOR'].disable();
        this.formGroupDataInformation.controls['COLUMNA_NOMBRE'].disable();
      } else {
        this.formGroupDataInformation.controls['COLUMNA_VALOR'].enable();
        this.formGroupDataInformation.controls['COLUMNA_NOMBRE'].enable();
      }
      this.arrColumnsTable = this.arrTablesName.filter((element: GetTables) => table === element.NOMBRE_TABLA);
    });

    
    this.formGroupConfigure.controls['TIPO_INFORMACION'].valueChanges.subscribe((typeInformation: string) => {
      if (typeInformation === 'CONSULTA_TABLA') {
        this.formGroupDataInformation.controls['TABLA'].setValidators(Validators.required);
        this.formGroupDataInformation.controls['TABLA'].updateValueAndValidity();
        this.formGroupDataInformation.controls['COLUMNA_VALOR'].setValidators(Validators.required);
        this.formGroupDataInformation.controls['COLUMNA_VALOR'].updateValueAndValidity();
        this.formGroupDataInformation.controls['COLUMNA_NOMBRE'].setValidators(Validators.required);
        this.formGroupDataInformation.controls['COLUMNA_NOMBRE'].updateValueAndValidity();

        this.formGroupPersonalityData.controls['VALOR_CAMPO'].clearValidators();
        this.formGroupPersonalityData.controls['VALOR_CAMPO'].updateValueAndValidity();
        this.formGroupPersonalityData.controls['NOMBRE_CAMPO'].clearValidators();
        this.formGroupPersonalityData.controls['NOMBRE_CAMPO'].updateValueAndValidity();

      } else if (typeInformation === 'DATOS_PERSONALIZADOS') {
        this.formGroupPersonalityData.controls['VALOR_CAMPO'].setValidators(Validators.required);
        this.formGroupPersonalityData.controls['VALOR_CAMPO'].updateValueAndValidity();
        this.formGroupPersonalityData.controls['NOMBRE_CAMPO'].setValidators(Validators.required);
        this.formGroupPersonalityData.controls['NOMBRE_CAMPO'].updateValueAndValidity();

        this.formGroupDataInformation.controls['TABLA'].clearValidators();
        this.formGroupDataInformation.controls['TABLA'].updateValueAndValidity();
        this.formGroupDataInformation.controls['COLUMNA_VALOR'].clearValidators();
        this.formGroupDataInformation.controls['COLUMNA_VALOR'].updateValueAndValidity();
        this.formGroupDataInformation.controls['COLUMNA_NOMBRE'].clearValidators();
        this.formGroupDataInformation.controls['COLUMNA_NOMBRE'].updateValueAndValidity();


      } else {
        this.resourcesService.openSnackBar(`Opción no disponible`);
      }
    });
  }
  
  ngAfterViewInit() {
    this.dataSourceInformationTable.paginator = this.paginatorDataInformationTable;
    this.dataSourcePersonality.paginator = this.paginatorDataPersonality;
  }

  private _createFormGroupConfigure(): FormGroup {
    return new FormGroup({
      COLUMNA: new FormControl(null, Validators.required),
      ETIQUETA: new FormControl(null, Validators.required),
      IDENTIFICADOR: new FormControl(null, Validators.required),
      TIPO_SELECT: new FormControl(null, Validators.required),
      ICONO: new FormControl(null),
      VALOR_DEFECTO: new FormControl(null),
      DESHABILITAR: new FormControl(null),
      REQUERIDO: new FormControl(null),
      PERMISOS: new FormControl([], Validators.required),
      TIPO_INFORMACION: new FormControl([], Validators.required),
      TAMANO_COLUMNA: new FormControl(12, Validators.required),
    });
  }

  private _createFormGroupDataInformation(): FormGroup {
    return new FormGroup({
      TABLA: new FormControl(null),
      COLUMNA_VALOR: new FormControl({ value: null, disabled: true }),
      COLUMNA_NOMBRE: new FormControl({ value: null, disabled: true }),
    });
  }

  private _createFormGroupPersonalityData(): FormGroup {
    return new FormGroup({
      VALOR_CAMPO: new FormControl(null),
      NOMBRE_CAMPO: new FormControl(null),
    });
  }

  private async _getMaterialIcons() {
    this.isLoadingIcon = true;
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._systemAdminService.getMaterialIcons(USER, LINE)).then(
      (responseData: MaterialIconsResponse) => {
        if (!responseData.error) {
          this.arrIcons = responseData.response.map((element: MaterialIcon) => `${ element.name }`);
        } else {
          this.resourcesService.openSnackBar(`${ responseData.msg }`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._getMaterialIcons();
        }
      }
    );
    this.isLoadingIcon = false;
  }

  private async _getUsers() {
    this.isLoadingUser = true;
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._usersProfilesService.getUsers(USER, LINE)).then(
      async (responseData: UsersResponse) => {
        if ( !responseData.error ) {
          this.arrUsers = [];
          for(const user of responseData.response){
            user.IDUSUARIO = await this._encService.decrypt(user.IDUSUARIO);
            this.arrUsers.push(user);
          }
          // this.arrUsers = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${ responseData.msg }`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._getUsers();
        }
      }
    );
    this.isLoadingUser = false;
  }

  private async _getTablesName() {
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._dynamicFormService.getTables(USER, LINE)).then(
      (responseData: ResponseDataGetTables) => {        
        if (!responseData.error) {
          this.arrTablesName = responseData.response;
          
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._getTablesName();
        }
      }
    );
  }

  private async _getInformationComponent() {
    if (this.infoDataForm.COMPONENTS !== undefined) { 
      const COMPONENTS: ComponentInformationSelect = this.infoDataForm.COMPONENTS;

      this.formGroupConfigure.controls['COLUMNA'].setValue(COMPONENTS.COLUMNA);
      if (this.infoDataForm.ENABLED) {
        this.formGroupConfigure.controls['COLUMNA'].enable();
      } else {
        this.formGroupConfigure.controls['COLUMNA'].disable();
      }
      this.formGroupConfigure.controls['ETIQUETA'].setValue(COMPONENTS.ETIQUETA);
      this.formGroupConfigure.controls['IDENTIFICADOR'].setValue(COMPONENTS.IDENTIFICADOR);
      this.formGroupConfigure.controls['TIPO_SELECT'].setValue(COMPONENTS.TIPO_SELECT);
      this.formGroupConfigure.controls['ICONO'].setValue(COMPONENTS.ICONO);
      this.formGroupConfigure.controls['VALOR_DEFECTO'].setValue(COMPONENTS.VALOR_DEFECTO);
      this.formGroupConfigure.controls['DESHABILITAR'].setValue(COMPONENTS.DESHABILITAR);
      this.formGroupConfigure.controls['REQUERIDO'].setValue(COMPONENTS.REQUERIDO);

      let USER_PERMISSION: string[] = [];
      for (const userPermission of COMPONENTS.PERMISOS) {
        const USER: string = await this._encService.decrypt(userPermission);
        USER_PERMISSION.push(USER);
      }
      this.formGroupConfigure.controls['PERMISOS'].setValue(USER_PERMISSION);
      this.formGroupConfigure.controls['TIPO_INFORMACION'].setValue(COMPONENTS.TIPO_INFORMACION);
      this.formGroupConfigure.controls['TAMANO_COLUMNA'].setValue(COMPONENTS.TAMANO_COLUMNA);

      if (COMPONENTS.TIPO_INFORMACION === 'CONSULTA_TABLA' && COMPONENTS.OBTENER_DATOS_TABLA !== undefined && COMPONENTS.VALORES_INUTILIZABLES !== undefined) {

        const TABLA: string = COMPONENTS.OBTENER_DATOS_TABLA.TABLA;
        const DEC_TABLA: string = await this._encService.decrypt(TABLA);

        const COLUMNA_VALOR: string = COMPONENTS.OBTENER_DATOS_TABLA.COLUMNA_VALOR;
        const DEC_COLUMNA_VALOR: string = await this._encService.decrypt(COLUMNA_VALOR);

        const COLUMNA_NOMBRE: string = COMPONENTS.OBTENER_DATOS_TABLA.COLUMNA_NOMBRE;
        const DEC_COLUMNA_NOMBRE: string = await this._encService.decrypt(COLUMNA_NOMBRE);

        this.formGroupDataInformation.controls['TABLA'].setValue(DEC_TABLA);
        this.formGroupDataInformation.controls['COLUMNA_VALOR'].setValue(DEC_COLUMNA_VALOR);
        this.formGroupDataInformation.controls['COLUMNA_NOMBRE'].setValue(DEC_COLUMNA_NOMBRE);

        await this.getInformationTable();

        const REMOVE_VALUES: string[] = COMPONENTS.VALORES_INUTILIZABLES;
        const DATA_REMOVE: GetInformationDataSelect[] = this.dataSourceInformationTable.data.map((informationDataSelect: GetInformationDataSelect) => {
          if (REMOVE_VALUES.includes(informationDataSelect.VALOR_CAMPO)) {
            informationDataSelect.ESTADO_CAMPO = 'Inactivo';
          }
          return informationDataSelect;
        });
        this.dataSourceInformationTable.data = DATA_REMOVE;

      } else if (COMPONENTS.TIPO_INFORMACION === 'DATOS_PERSONALIZADOS' && COMPONENTS.DATOS_PERSONALIZABLES !== undefined) {
        this.dataSourcePersonality.data = COMPONENTS.DATOS_PERSONALIZABLES;

      } else {
        this.resourcesService.openSnackBar(`Tipo de información no disponible.`);
      }
    }
  }

  public async getInformationTable() {
    this.isLoadingInformationTable = true;

    const TABLA: string = this.formGroupDataInformation.controls['TABLA'].value;
    const ENC_TABLA: string = await this._encService.encrypt(TABLA);
    this.formGroupDataInformation.controls['TABLA'].disable();

    const VALUE: string = this.formGroupDataInformation.controls['COLUMNA_VALOR'].value;
    const ENC_VALUE: string = await this._encService.encrypt(VALUE);
    this.formGroupDataInformation.controls['COLUMNA_VALOR'].disable();

    const NAME: string = this.formGroupDataInformation.controls['COLUMNA_NOMBRE'].value;
    const ENC_NAME: string = await this._encService.encrypt(NAME);
    this.formGroupDataInformation.controls['COLUMNA_NOMBRE'].disable();

    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    
    await lastValueFrom(this._dynamicFormService.getInformationDataSelect(ENC_TABLA, ENC_VALUE, ENC_NAME, USER, LINE)).then(
      (responseData: ResponseDataGetInformationDataSelect) => {
        if (!responseData.error) {
          this.dataSourceInformationTable.data = responseData.response.map((element: GetInformationDataSelect) => { return { 
            VALOR_CAMPO: element.VALOR_CAMPO,
            NOMBRE_CAMPO: element.NOMBRE_CAMPO,
            ESTADO_CAMPO: 'Activo',
          }});
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getInformationTable();
        }
      }
    );

    this.formGroupDataInformation.controls['TABLA'].enable();
    this.formGroupDataInformation.controls['COLUMNA_VALOR'].enable();
    this.formGroupDataInformation.controls['COLUMNA_NOMBRE'].enable();

    this.isLoadingInformationTable = false;
  }

  public updateColumnsNumber(accion: '+' | '-') {
    let columnNumber: number = this.formGroupConfigure.controls['TAMANO_COLUMNA'].value;
    if (accion === '+') {
      if (columnNumber < 12) {
        columnNumber += 1;
      }
    } else if (accion === '-') {
      if (columnNumber > 1) {
        columnNumber -= 1;
      }
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible`);
      return;
    }
    this.formGroupConfigure.controls['TAMANO_COLUMNA'].setValue(columnNumber)
  }

  public selectionChange(event: any) {
    
    this.getIndexStep = event.selectedIndex;
    if (event.selectedIndex === 0) {
      this.stepper.next();
    } else if (event.selectedIndex === 1) {
      this.stepper.previous();
    }
    
  }

  public allPermission() {
    const COUNT_USER: number = this.arrUsers.length;
    const USER_PERMISSION: string[] = this.formGroupConfigure.controls['PERMISOS'].value;
    const COUNT_PERMISSION: number = USER_PERMISSION.length;

    return COUNT_PERMISSION === COUNT_USER;
  }

  public somePermission() {
    const COUNT_USER: number = this.arrUsers.length;
    const USER_PERMISSION: string[] = this.formGroupConfigure.controls['PERMISOS'].value;
    const COUNT_PERMISSION: number = USER_PERMISSION.length;
    return COUNT_PERMISSION < COUNT_USER && COUNT_PERMISSION > 0;
  }

  public selectedAll(isChecked: boolean) {
    if (isChecked) {
      const USERS: string[] = this.arrUsers.map((user: UserResponse) => `${ user.IDUSUARIO }`);
      this.formGroupConfigure.controls['PERMISOS'].setValue(USERS);
    } else {
      this.formGroupConfigure.controls['PERMISOS'].setValue([]);
    }
  }

  public countInformationTable(): number {
    const INFORMATION_TABLE: GetInformationDataSelect[] = this.dataSourceInformationTable.data.filter((getIntormationDataSelect: GetInformationDataSelect) => getIntormationDataSelect.ESTADO_CAMPO === 'Activo');
    return INFORMATION_TABLE.length;
  }

  public async removeInformationTable(index: number) {
    let arrInformationTable: GetInformationDataSelect[] = this.dataSourceInformationTable.data;
    arrInformationTable[index]['ESTADO_CAMPO'] = 'Inactivo';
    this.dataSourceInformationTable.data = arrInformationTable;
  }

  public async addInformationTable(index: number) {
    let arrInformationTable: GetInformationDataSelect[] = this.dataSourceInformationTable.data;
    arrInformationTable[index]['ESTADO_CAMPO'] = 'Activo';
    this.dataSourceInformationTable.data = arrInformationTable;
  }

  public addDataPersonality() {
    this.isLoadingPersonalityData = true;
    const FORM_PERSONALITY = this.formGroupPersonalityData.value;
    let dataSourcePersonality: FormDataPersonality[] = this.dataSourcePersonality.data;
    dataSourcePersonality.push(FORM_PERSONALITY);
    this.dataSourcePersonality.data = dataSourcePersonality;
    this.formGroupPersonalityData.reset();
    this.isLoadingPersonalityData = false;
  }

  public updateDataPersonality() {
    this.isLoadingPersonalityData = true;
    if (this.typeFormDataPersonality.INDEX !== undefined) {
      const index: number = this.typeFormDataPersonality.INDEX;
      const FORM_PERSONALITY = this.formGroupPersonalityData.value;
      let dataSourcePersonality: FormDataPersonality[] = this.dataSourcePersonality.data;
      dataSourcePersonality[index] = FORM_PERSONALITY;
      this.dataSourcePersonality.data = dataSourcePersonality;
      this.formGroupPersonalityData.reset();
      this.typeFormDataPersonality.TYPE_FORM = 'R';
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible`);
    }
    this.isLoadingPersonalityData = false;
  }

  public editDataPersonality(index: number) {
    const FORM_PERSONALITY = this.dataSourcePersonality.data[index];
    this.formGroupPersonalityData.setValue(FORM_PERSONALITY);
    this.typeFormDataPersonality.TYPE_FORM = 'M';
    this.typeFormDataPersonality.INDEX = index;
  }

  public deleteDataPersonality(index: number) {
    let dataSourcePersonality: FormDataPersonality[] = this.dataSourcePersonality.data.filter(
      (formDataPersonality: FormDataPersonality, indexPersonality: number) => indexPersonality !== index);

    this.dataSourcePersonality.data = dataSourcePersonality;
  }

  public nextStep() {
    this.stepper.next();
    this.getIndexStep = 1;
  }
  
  public previousStep() {
    this.stepper.previous();
    this.getIndexStep = 0;
  }

  public validateId() {
    const ID: string = this.formGroupConfigure.controls['IDENTIFICADOR'].value;
    if (this.arrIdentification.includes(ID)) {
      this.resourcesService.openSnackBar(`El identicador ya está registrado en otro componente.`);
      return false;
    }
    return true;
  }

  public async openExampleSelect() {
    const COMPONENT_SELECT: ComponentInformationSelect | null = await this._createComponentSelect();
    if (COMPONENT_SELECT !== null) {
      this._dialog.open(ExampleComponentComponent, {
        data: {
          TYPE_COMPONENT: 'SELECT',
          COMPONENT: COMPONENT_SELECT
        },
        width: '450px',
        maxWidth: '450px',
      });
    }
  }

  private async _createComponentSelect(): Promise<ComponentInformationSelect | null> {

    let columna = this.formGroupConfigure.controls['COLUMNA'].value;
    columna = columna.toString().trim();
    let etiqueta = this.formGroupConfigure.controls['ETIQUETA'].value;
    etiqueta = etiqueta.toString().trim();
    let identificador = this.formGroupConfigure.controls['IDENTIFICADOR'].value;
    identificador = identificador.toString().trim();
    let tipoSelect = this.formGroupConfigure.controls['TIPO_SELECT'].value;
    if (tipoSelect !== 'NORMAL' && tipoSelect !== 'MULTIPLE') {
      this.resourcesService.openSnackBar(`El campo Tipo SELECT tiene datos no válidos`);
      return null;
    }
    let icono = this.formGroupConfigure.controls['ICONO'].value;
    if (icono === null || icono === '') {
      icono = null;
    } else {
      icono = icono.toString().trim();
    }
    let valorDefecto = this.formGroupConfigure.controls['VALOR_DEFECTO'].value;
    if (valorDefecto === null || valorDefecto === '') {
      valorDefecto = null;
    } else {
      valorDefecto = valorDefecto.toString().trim();
    }
    let deshabilitar = this.formGroupConfigure.controls['DESHABILITAR'].value;
    if (deshabilitar !== null && deshabilitar.length === 0) {
      deshabilitar = null;
    }
    let requerido = this.formGroupConfigure.controls['REQUERIDO'].value;
    if (requerido !== null && requerido.length === 0) {
      requerido = null;
    }
    let permisos = this.formGroupConfigure.controls['PERMISOS'].value;
    let PERMISOS_ENC: string[] = [];
    permisos.forEach(async (user: string) => {
      const ENC_USER: string = await this._encService.encrypt(user);
      PERMISOS_ENC.push(ENC_USER);
    });
    
    let tipoInformacion = this.formGroupConfigure.controls['TIPO_INFORMACION'].value;
    if (tipoInformacion !== 'CONSULTA_TABLA' && tipoInformacion !== 'DATOS_PERSONALIZADOS') {
      this.resourcesService.openSnackBar(`El campo Tipo de información tiene datos no válidos`);
      return null;
    }
    let tamanoColumna = this.formGroupConfigure.controls['TAMANO_COLUMNA'].value;


    let COMPONENT_SELECT: ComponentInformationSelect = {
      COLUMNA: columna,
      ETIQUETA: etiqueta,
      IDENTIFICADOR: identificador,
      TIPO_SELECT: tipoSelect,
      ICONO: icono,
      VALOR_DEFECTO: valorDefecto,
      DESHABILITAR: deshabilitar,
      REQUERIDO: requerido,
      PERMISOS: PERMISOS_ENC,
      TIPO_INFORMACION: tipoInformacion,
      TAMANO_COLUMNA: tamanoColumna,
    }

    if (tipoInformacion === 'CONSULTA_TABLA') {

      const TABLA: string = this.formGroupDataInformation.controls['TABLA'].value;
      const ENC_TABLA: string = await this._encService.encrypt(TABLA);

      const VALOR: string = this.formGroupDataInformation.controls['COLUMNA_VALOR'].value;
      const ENC_VALOR: string = await this._encService.encrypt(VALOR);

      const NOMBRE: string = this.formGroupDataInformation.controls['COLUMNA_NOMBRE'].value;
      const ENC_NOMBRE: string = await this._encService.encrypt(NOMBRE);

      const DATA_TABLE: GetDataTable = {
        TABLA: ENC_TABLA,
        COLUMNA_VALOR: ENC_VALOR,
        COLUMNA_NOMBRE: ENC_NOMBRE,
      }
      COMPONENT_SELECT.OBTENER_DATOS_TABLA = DATA_TABLE;

      const REMOVE_DATA:GetInformationDataSelect[] = this.dataSourceInformationTable.data.filter((informationDataSelect: GetInformationDataSelect) => informationDataSelect.ESTADO_CAMPO === 'Inactivo');
      const GET_REMOVE_INFORMATION: string[] = REMOVE_DATA.map((informationDataSelect: GetInformationDataSelect) => informationDataSelect.VALOR_CAMPO );
      COMPONENT_SELECT.VALORES_INUTILIZABLES = GET_REMOVE_INFORMATION;

    } else if (tipoInformacion === 'DATOS_PERSONALIZADOS') {
      COMPONENT_SELECT.DATOS_PERSONALIZABLES = this.dataSourcePersonality.data;

    } else {
      this.resourcesService.openSnackBar(`El campo Tipo de información tiene datos no válidos`);
      return null;
    }

    return COMPONENT_SELECT;
  }

  public async saveComponent() {
    this._dialog.open(AlertComponent, {
      data: {
        title: 'Confirmación',
        description: '¿Está seguro de registrar el componente SELECT?',
        icon: 'warning',
      },
      disableClose: true,
    }).afterClosed().subscribe(async (response) => {
      if (response) {
        const COMPONENT_SELECT: ComponentInformationSelect | null = await this._createComponentSelect();
        this._dialogRef.close(COMPONENT_SELECT);
      }
    });
  }
}
