import { MagnitudeFormComponent } from './magnitude-form/magnitude-form.component';
import { Permissions } from './../../../interfaces/permissions.interface';
import { FunctionsService } from './../../../services/functions.service';
import { MenuFunction, MenuResponse } from './../../../interfaces/menu.interface';
import { Submodules, SubmodulesResponse } from './../../../interfaces/submodules.interface';
import { LoginParamsResponse } from './../../../interfaces/login-params.interface';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { MatDialog } from '@angular/material/dialog';
import { ModuleInterface } from './../../../interfaces/modules.interface';
import { ModulesService } from './../../../services/modules.service';
import { MaterialIcon, MaterialIconsResponse } from './../../../interfaces/material-icons.interface';
import { SystemAdminService } from 'src/app/services/system-admin.service';
import { Observable, lastValueFrom, map, startWith } from 'rxjs';
import { EncService } from 'src/app/services/enc/enc.service';
import { Component, OnInit, ViewChild, ElementRef, Inject } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatTableDataSource } from '@angular/material/table';
import { DynamicFormService } from 'src/app/services/forms-management/dynamic-form.service';
import { HttpErrorResponse } from '@angular/common/http';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { Router } from '@angular/router';
import { SocketService } from 'src/app/services/socket.service';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { UsersProfilesService } from 'src/app/services/users-profiles.service';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';
import { EditPriorityComponent } from './edit-priority/edit-priority.component';
import { TempFileInfo } from 'src/app/interfaces/temp-file-info.interface';
import { FormTaxInformation, ResponseDataGetTaxInformation } from 'src/app/interfaces/tax-information.interface';
import { GdelService } from 'src/app/services/document-management/gdel.service';
import { CitySettings, CitySettingsResponse } from 'src/app/interfaces/city-settings.interface';
import { CityTown, CityTownsResponse } from 'src/app/interfaces/city-towns.interface';
import { CountriesList, CountriesListResponse, LadaSelection } from 'src/app/interfaces/countries-list.interface';
import { CountryState, CountryStatesResponse } from 'src/app/interfaces/country-states.interface';
import { StateCitiesResponse, StateCity } from 'src/app/interfaces/state-cities.interface';
import { TaxRegimeList, TaxRegimeListResponse } from 'src/app/interfaces/tax-regime-list.interface';
import countryCodeEmoji from 'country-code-emoji';
import flag from 'country-code-emoji';
import { AddressByZipCodeResponse } from 'src/app/interfaces/address-by-zip-code.interface';
import { MagnitudesListItem, MagnitudesListResponse, UnitsByMagnitudeListItem, UnitsByMagnitudeListResponse } from 'src/app/interfaces/counters-activators.interface';
import { UnitFormComponent } from './unit-form/unit-form.component';
import { CatalogMeasuresService } from 'src/app/services/counters-and-triggers/catalog-measures.service';
import { RequestDeleteMeasures, RequestFormMeasures } from 'src/app/interfaces/failure-analysis/catalog-measures.interface';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-system-params',
  templateUrl: './system-params.component.html',
  styleUrls: ['./system-params.component.css']
})
export class SystemParamsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  magnitudeSelected: string;

  magnitudes: MagnitudesListItem[];
  unitsByMagnitude: UnitsByMagnitudeListItem[];
  magnitudesAux: MagnitudesListItem[];
  unitsByMagnitudeAux: UnitsByMagnitudeListItem[];
  materialIcons: MaterialIcon[];
  modules: ModuleInterface[];
  submodules: Map<string, Submodules[]>;
  functionsPerSubmodule: Map<string, Map<string, MenuFunction[]>>;
  functionsPerModule: Map<string, MenuFunction[]>;
  iconsArr: Map<string, string[]>;
  iconsCategories: string[];

  moduleName = new FormControl('');
  moduleIcon = new FormControl('');
  submoduleModule = new FormControl('');
  submoduleName = new FormControl('');
  submoduleIcon = new FormControl('');
  functionModule = new FormControl('');
  functionSubmodule = new FormControl('');
  functionName = new FormControl('');
  functionIcon = new FormControl('');

  imageFormats = ["jpg", "png", "gif", "bmp", "tiff", "svg"];
  attached: TempFileInfo[];

  upImg: boolean;
  upBac: boolean;
  imgStr: string;
  bacStr: string;

  @ViewChild('file') file?: ElementRef;

  public txtBuscador: string;
  public btnSmall: boolean;
  public dataSource: MatTableDataSource<any>;
  public isLoadingForm: boolean = false;
  public displayedColumns: string[];

  formsManagementEnabled: boolean;
  loginImagesEditEnabled: boolean;
  modulesIconsEditEnabled: boolean;
  submodulesIconsEditEnabled: boolean;
  functionsIconsEditEnabled: boolean;

  currentHour: number;
  currentMinutes: number;
  currentSeconds: number;
  orderPrioritiesArr: PriorityInterface[];

  public formGroupTax: FormGroup;

  public arrTaxRegime: Array<TaxRegimeList>;
  public taxRegimeStr: string[];

  public arrCountries: Array<CountriesList>;
  public ladas: LadaSelection[];
  public ladasStr: string[];
  public countries: CountriesList[];
  public countryStates: CountryState[];
  public cityTowns: CityTown[];
  public stateCities: StateCity[];
  public citySettings: CitySettings[];
  public countriesStr: string[];
  public stateCitiesStr: string[];
  public countryStatesStr: string[];
  public cityTownsStr: string[];
  public citySettingsStr: string[];

  public searchingUnits: boolean;
  public searchingMagnitudes: boolean;
  public enableSearchByZipCode: boolean;
  public searchingStates: boolean;
  public searchingSettings: boolean;
  public searchingTowns: boolean;
  public searchingCities: boolean;
  public searchingAddress: boolean;
  public citiesInput: boolean;

  filteredLadas1?: Observable<string[]>;
  filteredLadas2?: Observable<string[]>;
  filteredTaxRegime?: Observable<string[]>;
  filteredCountries?: Observable<string[]>;
  filteredStates?: Observable<string[]>;
  filteredCities?: Observable<string[]>;
  filteredTowns?: Observable<string[]>;
  filteredSettings?: Observable<string[]>;

  constructor(
    @Inject(DOCUMENT) private _document: Document,
    public dialog: MatDialog,
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _modulesService: ModulesService,
    private _matDialog: MatDialog,
    private _formService: DynamicFormService,
    private _router: Router,
    private _funcService: FunctionsService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _gdelService: GdelService,
    private _resourcesService: ResourcesService,
    private _catalogMeasuresService: CatalogMeasuresService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.magnitudeSelected = "";

    this.upImg = false;
    this.upBac = false;
    this.imgStr = "";
    this.bacStr = "";
    this.txtBuscador = '';
    this.btnSmall = false;

    this.magnitudes = [];
    this.unitsByMagnitude = [];
    this.magnitudesAux = [];
    this.unitsByMagnitudeAux = [];
    this.materialIcons = [];
    this.modules = [];
    this.iconsArr = new Map<string, string[]>;
    this.submodules = new Map<string, Submodules[]>;
    this.functionsPerSubmodule = new Map<string, Map<string, MenuFunction[]>>;
    this.functionsPerModule = new Map<string, MenuFunction[]>;
    this.iconsCategories = [];
    this.attached = [];

    this.dataSource = new MatTableDataSource<any>();
    this.displayedColumns = [ 'NOMBRE_FORM', 'MODULO', 'FECHA_REG', 'ESTADO', 'ACCIONES' ];

    this.formsManagementEnabled = true;
    this.loginImagesEditEnabled = true;
    this.modulesIconsEditEnabled = true;
    this.submodulesIconsEditEnabled = true;
    this.functionsIconsEditEnabled = true;

    this.currentHour = 0;
    this.currentMinutes = 0;
    this.currentSeconds = 0;
    this.orderPrioritiesArr = [];

    this.formGroupTax = this.createFormGroup();
    this.arrTaxRegime = [];
    this.taxRegimeStr = [];
    

    this.arrCountries = [];
    this.ladas = [];
    this.ladasStr = [];
    this.countries = [];
    this.countryStates = [];
    this.cityTowns = [];
    this.stateCities = [];
    this.citySettings = [];
    this.countriesStr = [];
    this.stateCitiesStr = [];
    this.countryStatesStr = [];
    this.cityTownsStr = [];
    this.citySettingsStr = [];

    this.searchingUnits = false;
    this.searchingMagnitudes = false;
    this.enableSearchByZipCode = true;
    this.searchingStates = false;
    this.searchingSettings = false;
    this.searchingTowns = false;
    this.searchingCities = false;
    this.searchingAddress = false;
    this.citiesInput = false;
  }

  ngOnInit(): void {
    this.getTaxRegimeActive();
    this.getCoutries();
    this.getTaxInformation();
    this.getMaterialIcons();
    this.getMagnitudes();


    
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      let idUser = localStorage.getItem('idusuario')!;
      let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesSevice.getUser(idUser, idUser, 1));
      let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

      if(parseInt(currentProfile) != usrInfo.response.PERFIL){
        this._router.navigate(['/sam/home']);
      }

      let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
      if(profileUpdated == currentProfile){
        try{
          let profile = localStorage.getItem('perfil')!;
          let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesSevice.getProfile(
            profile,
            idUser,
            1
          ));

          let modPerm = profInfo.response.PERMISOS.permissions.filter(item => item.id == 'S002V01M01ADSI')[0];
          let funPerm = modPerm.children.filter(item => item.id == 'S002V01F11PASI')[0];

          this.formsManagementEnabled = funPerm.children.filter(item => item.id == 'S002V01P01GEFO')[0].access > 0;
          this.loginImagesEditEnabled = funPerm.children.filter(item => item.id == 'S002V01P04EILO')[0].access > 0;
          this.modulesIconsEditEnabled = funPerm.children.filter(item => item.id == 'S002V01P05EIMO')[0].access > 0;
          this.submodulesIconsEditEnabled = funPerm.children.filter(item => item.id == 'S002V01P06EISU')[0].access > 0;
          this.functionsIconsEditEnabled = funPerm.children.filter(item => item.id == 'S002V01P07EIFU')[0].access > 0;
        }catch(error: any){
          if(error.error == undefined){
            this._resourcesService.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else if(error.error.msg == undefined){
            this._resourcesService.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else{
            this._resourcesService.openSnackBar(error.error.msg);
          }
        }
      }
    });

    this.formGroupTax.controls['LOCALIDAD'].valueChanges.subscribe(value => {
      if(!this.enableSearchByZipCode) {
        let countryVal = this.formGroupTax.controls['PAIS'].value;
        let countryArr = countryVal.split('(').reverse();
        let countryCode = countryArr[0].replace(')', '');

        if(countryCode == 'MEX'){
          let validValue = this.cityTownsStr.filter(item => item == value);
          if(validValue.length > 0){
            let valueArr = value.split('(').reverse();
            let townCode = valueArr[0].replace(')', '');

            this.verifyTown(townCode);
          }else{
            this.formGroupTax.controls['COLONIA'].setValue('');
            this.formGroupTax.controls['COLONIA'].disable();
          }
        }else{
          this.formGroupTax.controls['COLONIA'].enable();
        }
      }
    })

    this.filteredLadas1 = this.formGroupTax.controls['LADA1'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.ladasStr.filter((item) => item.toLowerCase().includes(filterValue));
      })
    );

    this.filteredLadas2 = this.formGroupTax.controls['LADA2'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.ladasStr.filter((item) => item.toLowerCase().includes(filterValue));
      })
    );

    this.filteredTaxRegime = this.formGroupTax.controls['REGIMEN_FISCAL'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.taxRegimeStr.filter(item => item.toLowerCase().includes(filterValue));
      })
    );

    this.filteredSettings = this.formGroupTax.controls['COLONIA'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.citySettingsStr.filter(item => item.toLowerCase().includes(filterValue));
      }),
    );

    this.filteredTowns = this.formGroupTax.controls['LOCALIDAD'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.cityTownsStr.filter(item => item.toLowerCase().includes(filterValue));
      }),
    );
    
    this.filteredCities = this.formGroupTax.controls['MUNICIPIO'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.stateCitiesStr.filter(item => item.toLowerCase().includes(filterValue));
      })
    );

    this.filteredStates = this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.countryStatesStr.filter(item => item.toLowerCase().includes(filterValue));
      })
    );

    this.filteredCountries = this.formGroupTax.controls['PAIS'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        let countries = this.countriesStr.filter(item => item.toLowerCase().includes(filterValue));

        return countries;
      })
    );
  }

  private createFormGroup() {
    return new FormGroup({
      NOMBRE_FISCAL: new FormControl('', Validators.required),
      RFC: new FormControl('', [Validators.required, Validators.pattern(new RegExp(/^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/))]),
      CORREO_ELECTRONICO: new FormControl('', [Validators.required, Validators.email]),
      REGIMEN_FISCAL: new FormControl('', Validators.required),
      LADA1: new FormControl('', Validators.required),
      TELEFONO_FIJO: new FormControl('', Validators.required),
      LADA2: new FormControl('', Validators.required),
      TELEFONO_MOVIL: new FormControl('', Validators.required),
      CODIGO_POSTAL: new FormControl('', Validators.required),
      TIPOVIALIDAD: new FormControl('', Validators.required),
      NOMBRE_VIALIDAD: new FormControl('', Validators.required),
      ENTRE_CALLE: new FormControl('', Validators.required),
      Y_CALLE: new FormControl('', Validators.required),
      NUMERO_EXTERIOR: new FormControl('', Validators.required),
      NUMERO_INTERIOR: new FormControl(''),
      COLONIA: new FormControl('', Validators.required),
      LOCALIDAD: new FormControl('', Validators.required),
      MUNICIPIO: new FormControl('', Validators.required),
      ENTIDAD_FEDERATIVA: new FormControl('', Validators.required),
      PAIS: new FormControl('', Validators.required),
    });
  }

  async getMaterialIcons(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let materialIcons: MaterialIconsResponse = await lastValueFrom(this._sysAdminService.getMaterialIcons(idUser, 1));

      this.hasError = materialIcons.error;
      if(!this.hasError){
        this.materialIcons = materialIcons.response;
      }else{
        this.errorStr = materialIcons.msg;
        this.isLoading = false;
      }

      this.materialIcons.forEach(icon => {
        let categorie = icon.categorie[0];
        if(this.iconsArr.has(categorie)){
          let arr = this.iconsArr.get(categorie);
          arr?.push(icon.name);
        }else{
          let arr = [icon.name];
          this.iconsArr.set(categorie, arr);
        }
      });

      this.iconsCategories = Array.from(this.iconsArr.keys());
      this.getModules();
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = "Ocurrió un error inesperado.";
      }else if(error.error.msg == undefined){
        this.errorStr = "Ocurrió un error inesperado.";
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async getModules(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let menu: MenuResponse = await lastValueFrom(this._modulesService.getMenu(idUser, 1));

      this.hasError = menu.error;
      if(this.hasError){
        this.errorStr = menu.msg;
        this.isLoading = false;
      }else{
        menu.response.forEach(mod => {
          if(mod.SUBMODULES.length > 0){
            let submodules: Submodules[] = [];
            let submoduleFunctions: Map<string, MenuFunction[]> = new Map<string, MenuFunction[]>;

            mod.SUBMODULES.forEach(submod => {
              if(submod.FUNCIONES.length > 0){
                let functions: MenuFunction[] = [];

                submod.FUNCIONES.forEach(func => {
                  functions.push(func);
                });

                submoduleFunctions.set(submod.IDSUBMODULO, functions);
              }

              let submodule: Submodules = {
                IDSUBMODULO: submod.IDSUBMODULO,
                NOMBRESUBMODULO: submod.NOMBRESUBMODULO,
                ICONOSUBMODULO: submod.ICONOSUBMODULO,
                IMAGENSUBMODULO: ""
              }

              submodules.push(submodule);
            });

            this.functionsPerSubmodule.set(mod.IDMODULO, submoduleFunctions);
            this.submodules.set(mod.IDMODULO, submodules);
          }else{
            let moduleFunctions: MenuFunction[] = [];
            mod.MENUS.forEach(menu => {
              moduleFunctions.push(menu);
            });

            this.functionsPerModule.set(mod.IDMODULO, moduleFunctions);
          }

          let module: ModuleInterface = {
            IDMODULO: mod.IDMODULO,
            NOMBREMODULO: mod.NOMBREMODULO,
            ICONOMODULO: mod.ICONOMODULO,
          };

          this.modules.push(module);
        });

        this.getLoginImages();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async getSubmodules(module: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idMod = await this._encService.encrypt(module);
      let submodules: SubmodulesResponse = await lastValueFrom(this._modulesService.getSubmodules(idMod, idUser, 1));

      this.submodules.set(module, submodules.response);
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  changeModuleIcon(module: string){
    let mod = this.modules.filter(item => item.IDMODULO == module)[0];
    this.moduleIcon.setValue(mod.ICONOMODULO);
  }

  changeSubmoduleIcon(submodule: string){
    let moduleSelected = this.submodules.get(this.submoduleModule.value!);
    let submoduleSelected = moduleSelected?.filter(item => item.IDSUBMODULO == submodule)[0];
    this.submoduleIcon.setValue(submoduleSelected?.ICONOSUBMODULO!);
  }

  changeFunctionIcon(func: string){
    if(this.functionsPerModule.has(this.functionModule.value!)){
      let moduleSelected = this.functionsPerModule.get(this.functionModule.value!);
      let functionSelected = moduleSelected?.filter(item => item.IDFUNCION == func)[0];
      this.functionIcon.setValue(functionSelected?.ICONOFUNCION!);
    }else{
      let moduleSelected = this.functionsPerSubmodule.get(this.functionModule.value!);
      let submoduleSelected = moduleSelected?.get(this.functionSubmodule.value!);
      let functionSelected = submoduleSelected?.filter(item => item.IDFUNCION == func)[0];
      this.functionIcon.setValue(functionSelected?.ICONOFUNCION!);
    }
  }

  submodChange(){
    this.submoduleName.setValue('');
    this.submoduleIcon.setValue('');
  }

  updateModuleIcon(newIcon: string){
    let moduleSelected = this.modules.filter(item => item.IDMODULO == this.moduleName.value)[0];
    let modulesAux: ModuleInterface[] = [];

    this.modules.forEach(module => {
      if(moduleSelected.IDMODULO == module.IDMODULO){
        moduleSelected.ICONOMODULO = newIcon;
        modulesAux.push(moduleSelected);
      }else{
        modulesAux.push(module);
      }
    });

    this.modules = modulesAux;
  }

  updateSubmoduleIcon(newIcon: string){
    let moduleSelected = this.submodules.get(this.submoduleModule.value!);
    let submoduleSelected = moduleSelected?.filter(item => item.IDSUBMODULO == this.submoduleName.value)[0];
    let submodulesAux: Submodules[] = [];

    moduleSelected?.forEach(submodule => {
      if(submoduleSelected?.IDSUBMODULO == submodule.IDSUBMODULO){
        submoduleSelected.ICONOSUBMODULO = newIcon;
        submodulesAux?.push(submoduleSelected);
      }else{
        submodulesAux?.push(submodule);
      }
    });

    this.submodules.set(this.submoduleModule.value!, submodulesAux!);
  }

  updateFunctionIcon(newIcon: string){
    if(this.functionsPerSubmodule.has(this.functionModule.value!)){
      let moduleSelected = this.functionsPerSubmodule.get(this.functionModule.value!);
      let submoduleSelected = moduleSelected?.get(this.functionSubmodule.value!);
      let functionSelected = submoduleSelected?.filter(item => item.IDFUNCION == this.functionName.value)[0];
      let functionsAux: MenuFunction[] = [];

      submoduleSelected?.forEach(func => {
        if(functionSelected?.IDFUNCION == func.IDFUNCION){
          func.ICONOFUNCION = newIcon;
          functionsAux.push(functionSelected);
        }else{
          functionsAux?.push(func);
        }
      });

      moduleSelected?.set(this.functionSubmodule.value!, functionsAux);
      this.functionsPerSubmodule.set(this.functionModule.value!, moduleSelected!);
    }else{
      let moduleSelected = this.functionsPerModule.get(this.functionModule.value!);
      let functionSelected = moduleSelected?.filter(item => item.IDFUNCION == this.functionName.value)[0];
      let moduleAux: MenuFunction[] = [];

      moduleSelected?.forEach(func => {
        if(functionSelected?.IDFUNCION == func.IDFUNCION){
          functionSelected.ICONOFUNCION = newIcon;
          moduleAux?.push(functionSelected);
        }else{
          moduleAux?.push(func);
        }
      });

      this.functionsPerModule.set(this.functionModule.value!, moduleAux);
    }
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  checkFile(event: any){
    let extArr = event.target.files[0].name.split(".").reverse();
    let extStr = extArr[0];

    if(this.imageFormats.includes(extStr)){
      let maxFileSize = 1048576 * 250;
      let fileSize = event.target.files[0].size;

      if(fileSize > maxFileSize){
        this._resourcesService.openSnackBar(`El tamaño del archivo supera el límite de 75 MB`);
      }else{
        let dialogRef = this._matDialog.open(AlertComponent, {
          data: {
            title: 'Advertencia',
            icon: 'warning',
            description: '¿Está seguro de realizar la acción solicitada?'
          }
        });

        dialogRef.afterClosed().subscribe(res => {
          if(res == true){
            let type = this.upImg ? 'img' : 'bac';
            this.updateImg(type, event.target.files[0]);
          }else{
            this.upImg = false;
            this.upBac = false;
          }
        });
      }
    }else{
      this._resourcesService.openSnackBar('El archivo seleccionado no tiene un formato de imagen');
      this.cancelHandle();
    }
  }

  formatBytes(bytes: number, decimals = 2) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  }

  imageHandler(type: string){
    if(type == 'img'){
      this.upImg = true;
      this.file?.nativeElement.click();
    }else{
      this.upBac = true;
      this.file?.nativeElement.click();
    }
  }

  async updateImg(type: string, fileData: any){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('file', fileData);
      formData.append('id_user', idUser);
      formData.append('linea', "1");

      let response = await lastValueFrom(this._gdelService.uploadTempFile(formData));
      if(response.error){
        this._resourcesService.openSnackBar(response.msg);
        this.upBac = false;
        this.upImg = false;
      }else{
        let tipo = type == 'img' ? 'image' : 'background';
        let formData = new FormData();

        formData.append('id_user', idUser!);
        formData.append('linea', '1');
        formData.append('tipo', tipo);
        formData.append('archivo', response.response.idArchivo);

        await lastValueFrom(this._sysAdminService.saveLoginImage(formData));

        window.location.reload();
      }
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }

      this.upBac = false;
      this.upImg = false;
    }
  }

  async getLoginImages(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let loginImages: LoginParamsResponse = await lastValueFrom(this._sysAdminService.getLoginImages(idUser, 1));

      if(loginImages.error){
        this.errorStr = loginImages.msg;
        this.hasError = true;
        this.isLoading = false;
      }else{
        this.imgStr = `http://git.ittec.mx/sam/public/assets/${loginImages.response.login_params.login_image}`;
        this.bacStr = `http://git.ittec.mx/sam/public/assets/${loginImages.response.login_params.login_background}`;

        this.upBac = false;
        this.upImg = false;
        this.obtenerFormularios();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  cancelHandle(){
    this.upBac = false;
    this.upImg = false;
  }

  hasSubmodules(idMod: string): boolean{
    let hasSubmodules = this.submodules.has(idMod);
    return !hasSubmodules;
  }

  funcModChange(value: string){
    if(this.submodules.has(value)){
      this.functionSubmodule.enable();
    }else{
      this.functionSubmodule.disable();
    }

    this.functionSubmodule.setValue('');
    this.functionName.setValue('');
    this.functionIcon.setValue('');
  }

  funSubmodChange(){
    this.functionName.setValue('');
    this.functionIcon.setValue('');
  }

  getFunctions(): MenuFunction[]{
    let moduleFunctions = this.functionsPerModule.get(this.functionModule.value!);
    let submoduleFunctions = this.functionsPerSubmodule.get(this.functionModule.value!)?.get(this.functionSubmodule.value!);
    if(moduleFunctions != undefined){
      return moduleFunctions;
    }else if(submoduleFunctions != undefined){
      return submoduleFunctions;
    }else{
      return [];
    }
  }

  async saveModules(){
    try{
      let modulesStr = JSON.stringify(this.modules);
      let modulesEnc = await this._encService.encrypt(modulesStr);
      let idUser = localStorage.getItem('idusuario');
      let info = new FormData();

      info.append('id_user', idUser!);
      info.append('linea', '1');
      info.append('module_icons', modulesEnc);

      await lastValueFrom(this._sysAdminService.updateModuleIcons(info));
      this._resourcesService.openSnackBar('Los iconos de los módulos se actualizaron correctamente.');
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  async saveSubmodules(){
    try{
      let idUser = localStorage.getItem('idusuario');
      let submodulesStr = JSON.stringify(Object.fromEntries(this.submodules));
      let submodulesEnc = await this._encService.encrypt(submodulesStr);
      let info = new FormData();

      info.append('id_user', idUser!);
      info.append('linea', '1');
      info.append('submodule_icons', submodulesEnc);

      await lastValueFrom(this._sysAdminService.updateSubmoduleIcons(info));
      this._resourcesService.openSnackBar('Los iconos de los submódulos se actualizaron correctamente.');
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  async saveFunctions(){
    try{
      let functionsPerModuleStr = JSON.stringify(Object.fromEntries(this.functionsPerModule));
      let functionsPerModuleEnc = await this._encService.encrypt(functionsPerModuleStr);

      let functionsPerSubmoduleObjAuxStr = JSON.stringify(Object.fromEntries(this.functionsPerSubmodule));
      let functionsPerSubmoduleObjAux = JSON.parse(functionsPerSubmoduleObjAuxStr);

      this.functionsPerSubmodule.forEach((value, key) => {
        let functionsAux = Object.fromEntries(value);
        functionsPerSubmoduleObjAux[key] = functionsAux;
      });

      let functionsPerSubmoduleStr = JSON.stringify(functionsPerSubmoduleObjAux);
      let functionsPerSubmoduleEnc = await this._encService.encrypt(functionsPerSubmoduleStr);

      let idUser = localStorage.getItem('idusuario');
      let info = new FormData();

      info.append('id_user', idUser!);
      info.append('linea', '1');
      info.append('module_functions_icons', functionsPerModuleEnc);
      info.append('submodule_functions_icons', functionsPerSubmoduleEnc);

      await lastValueFrom(this._sysAdminService.updateFunctionIcons(info));
      this._resourcesService.openSnackBar('Los iconos de las funciones se actualizaron correctamente.');
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  applyFilter(event: any, type: string){
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource!.filter = filterValue.trim().toLowerCase();

    if(this.dataSource?.paginator){
      this.dataSource.paginator.firstPage();
    }
  }

  public async obtenerFormularios() {
    this.isLoading = true;
    let idUser = localStorage.getItem('idusuario')!;
    await lastValueFrom(this._formService.getForm(idUser)).then(
      (data: ResponseData) => {
        this.dataSource.data = !data.error ? data.response : [];
      },(error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );

    let permissionsEnc = localStorage.getItem('permisos');
    let permissionsDec = await this._encService.decrypt(permissionsEnc!);
    let permissionsArr: Permissions = JSON.parse(permissionsDec);

    let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M01ADSI')[0];
    let funPerm = modPerm.children.filter(item => item.id == 'S002V01F11PASI')[0];

    this.formsManagementEnabled = funPerm.children.filter(item => item.id == 'S002V01P01GEFO')[0].access > 0;
    this.loginImagesEditEnabled = funPerm.children.filter(item => item.id == 'S002V01P04EILO')[0].access > 0;
    this.modulesIconsEditEnabled = funPerm.children.filter(item => item.id == 'S002V01P05EIMO')[0].access > 0;
    this.submodulesIconsEditEnabled = funPerm.children.filter(item => item.id == 'S002V01P06EISU')[0].access > 0;
    this.functionsIconsEditEnabled = funPerm.children.filter(item => item.id == 'S002V01P07EIFU')[0].access > 0;

    this.getOrderPriorities();
  }

  async getOrderPriorities(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let priorities = await lastValueFrom(this._sysAdminService.getOrderPriorities(idUser, 1));

      if(priorities.error){
        this.errorStr = priorities.msg;
        this.hasError = true;
      }else{
        this.orderPrioritiesArr = priorities.response.order_priorities;
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
    }
  }

  private async getTaxRegimeActive() {
    const idUser: string = this._resourcesService.getUser();
    const line: number =  parseInt(this._resourcesService.getLineNumber());
    await lastValueFrom(this._sysAdminService.getTaxRegimeList(idUser, line)).then(
      (responseData: TaxRegimeListResponse) => {
        if (!responseData.error) {
          this.arrTaxRegime = responseData.response;
          let moralTaxRegime = this.arrTaxRegime.filter(item => item.APPLY_MORAL == 'Sí');
          this.taxRegimeStr = [];
          moralTaxRegime.forEach(item => {
            this.taxRegimeStr.push(`${item.TAX_REGIME_DESC} (${item.TAX_REGIME_KEY})`);
          });
        } else {
          this._resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  private async getCoutries() {
    const idUser: string = this._resourcesService.getUser();
    const line: number = parseInt(this._resourcesService.getLineNumber());
    await lastValueFrom(this._sysAdminService.getCountriesList(idUser, line)).then(
      (responseData: CountriesListResponse) => {
        if (!responseData.error) {
          this.arrCountries = responseData.response;

          let mex = responseData.response.filter(item => item.COUNTRY_ID == 'MEX');
          this.arrCountries.push(mex[0]);
          this.countriesStr.push(`${mex[0].NAME} (${mex[0].COUNTRY_ID})`);

          let mexLada: LadaSelection = {
            FLAG: [mex[0].NOMECLARUTA_ISO2!].map(countryCodeEmoji)[0],
            LADA: mex[0].LADA!
          };          
          
          this.ladas.push(mexLada);
          this.ladasStr.push(`${mexLada.FLAG} ${mexLada.LADA}`);

          let usa = responseData.response.filter(item => item.COUNTRY_ID == 'USA');
          this.arrCountries.push(usa[0]);
          this.countriesStr.push(`${usa[0].NAME} (${usa[0].COUNTRY_ID})`);

          let usaLada: LadaSelection = {
            FLAG: [usa[0].NOMECLARUTA_ISO2!].map(countryCodeEmoji)[0],
            LADA: usa[0].LADA!
          };
          
          this.ladas.push(usaLada);
          this.ladasStr.push(`${usaLada.FLAG} ${usaLada.LADA}`);

          let can = responseData.response.filter(item => item.COUNTRY_ID == 'CAN');
          this.arrCountries.push(can[0]);
          this.countriesStr.push(`${can[0].NAME} (${can[0].COUNTRY_ID})`);

          let canLada: LadaSelection = {
            FLAG: [can[0].NOMECLARUTA_ISO2!].map(countryCodeEmoji)[0],
            LADA: can[0].LADA!
          };
          
          this.ladas.push(canLada);
          this.ladasStr.push(`${canLada.FLAG} ${canLada.LADA}`);
                    
          responseData.response.forEach(country => {
            if(country.COUNTRY_ID != null && country.COUNTRY_ID != 'MEX' && country.COUNTRY_ID != 'USA' && country.COUNTRY_ID != 'CAN'){
              this.arrCountries.push(country);
              this.countriesStr.push(`${country.NAME} (${country.COUNTRY_ID})`);

              try{
                flag(country.NOMECLARUTA_ISO2!);
                let hasLada = country.LADA != '';

                if(hasLada){
                  let lada: LadaSelection = {
                    FLAG: [country.NOMECLARUTA_ISO2!].map(countryCodeEmoji)[0],
                    LADA: country.LADA!
                  };

                  this.ladas.push(lada);
                  this.ladasStr.push(`${lada.FLAG} ${lada.LADA}`);
                }
              }catch(error: any){
                //Saltar país
              }
            }
          });

        } else {
          this._resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }
  public async searchZipCode() {
    
    let postalCode:string = this.formGroupTax.controls['CODIGO_POSTAL'].value.toString();

    if (postalCode.length === 5 && this.enableSearchByZipCode) {
      
      this.formGroupTax.controls['COLONIA'].setValue('');
      this.formGroupTax.controls['MUNICIPIO'].setValue('');
      this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].setValue('');
      this.formGroupTax.controls['PAIS'].setValue('');
      
      this.formGroupTax.controls['CODIGO_POSTAL'].disable();
      this.formGroupTax.controls['COLONIA'].disable();
      this.formGroupTax.controls['MUNICIPIO'].disable();
      this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].disable();
      this.formGroupTax.controls['PAIS'].disable();

      this.isLoadingForm = true;
      this.searchingAddress = true;
      await this.searchAddressByZipCode(postalCode);
      this.searchingAddress = false;
      this.isLoadingForm = false;


      this.formGroupTax.controls['CODIGO_POSTAL'].enable();
      this.formGroupTax.controls['COLONIA'].enable();
      this.formGroupTax.controls['MUNICIPIO'].enable();
      this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].enable();
      this.formGroupTax.controls['PAIS'].enable();
    }
  }
  private async searchAddressByZipCode(postalCode:string) {
    const encPostalCode: string = await this._encService.encrypt(postalCode);
    const idUser: string = this._resourcesService.getUser();
    const lineNumber:number = parseInt(this._resourcesService.getLineNumber());
    await lastValueFrom(this._sysAdminService.getAddressByZipCode(
      encPostalCode, idUser, lineNumber
    )).then(
      (responseData: AddressByZipCodeResponse) => {
        if (!responseData.error) {

          this.formGroupTax.controls['PAIS'].setValue('México (MEX)', { emitValue: false, });
          this.citySettings = [];
          this.citySettingsStr = [];

          if (responseData.response.CODIGO_LOCALIDAD !== null) {
            this.formGroupTax.controls['LOCALIDAD'].setValue(`${responseData.response.NOMBRE_LOCALIDAD} (${responseData.response.CODIGO_LOCALIDAD})`);
          } else {
            this.formGroupTax.controls['LOCALIDAD'].setValue(`Sin localidad`);
          }

          if (responseData.response.CODIGO_MUNICIPIO !== null) {
            this.formGroupTax.controls['MUNICIPIO'].setValue(`${responseData.response.NOMBRE_MUNICIPIO} (${responseData.response.CODIGO_MUNICIPIO})`);
          } else {
            this.formGroupTax.controls['MUNICIPIO'].setValue(`Sin municipio`);
          }
          
          if (responseData.response.CODIGO_ESTADO !== null) {
            this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].setValue(`${responseData.response.NOMBRE_ESTADO} (${responseData.response.CODIGO_ESTADO})`);
          } else {
            this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].setValue(`Sin entidad federativa`);
          }

          if(responseData.response.COLONIAS.length > 0){
            responseData.response.COLONIAS.forEach(item => {
              let setting: CitySettings = {
                CODIGOCOLONIA: item.CODIGO_COLONIA,
                CODIGOPOSTAL: postalCode,
                NOMBRECOLONIA: item.NOMBRE_COLONIA,
              };
              this.citySettings.push(setting);
              this.citySettingsStr.push(`${item.NOMBRE_COLONIA} (${item.CODIGO_COLONIA})`);
            });


          }else{
            this.formGroupTax.controls['COLONIA'].setValue('Sin colonia');
            this.formGroupTax.controls['LOCALIDAD'].setValue(`Sin localidad`);
            this.formGroupTax.controls['MUNICIPIO'].setValue(`Sin municipio`);
            this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].setValue(`Sin entidad federativa`);
          }

        } else {
          this._resourcesService.openSnackBar(responseData.msg);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this._resourcesService.checkErrors(httpErrorResponse)
    );
  }


  // Filtra los Paises
  public checkIfAddress() {
    let country:string = this.formGroupTax.controls['PAIS'].value;

    let validValue = this.countriesStr.filter(item => item == country);
    this.formGroupTax.controls['CODIGO_POSTAL'].setValue('', {
      emitEvent: false,
    });

    if(validValue.length > 0){
      let valueArr = country.split('(').reverse();
      let countryCode = valueArr[0].replace(')', '');

      this.formGroupTax.controls['CODIGO_POSTAL'].disable();
      this.enableSearchByZipCode = false;
      this.verifyCountry(countryCode);
    }else{
      this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].setValue('');
      this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].disable();
      this.formGroupTax.controls['MUNICIPIO'].setValue('');
      this.formGroupTax.controls['MUNICIPIO'].disable();
      this.formGroupTax.controls['LOCALIDAD'].setValue('');
      this.formGroupTax.controls['LOCALIDAD'].disable();
      this.formGroupTax.controls['COLONIA'].setValue('');
      this.formGroupTax.controls['COLONIA'].disable();

      this.formGroupTax.controls['CODIGO_POSTAL'].enable();
      this.enableSearchByZipCode = true;
    }
  }
  private verifyCountry(countryCode: string){
    this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].disable();
    this.countryStates = [];
    this.countryStatesStr = [];
    this.stateCities = [];
    this.stateCitiesStr = [];
    this.cityTowns = [];
    this.cityTownsStr = [];
    this.citySettings = [];
    this.citySettingsStr = [];

    if(countryCode != 'MEX'){
      this.formGroupTax.controls['CODIGO_POSTAL'].enable();
    }

    if(countryCode == 'CAN' || countryCode == 'MEX' || countryCode == 'USA'){
      this.searchCountryStates(countryCode);
    }else{
      this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].enable();
    }
  }
  private async searchCountryStates(contryCode: string){
    try{
      this.searchingStates = true;

      const idUser: string = this._resourcesService.getUser();
      const line: number = parseInt(this._resourcesService.getLineNumber());
      const encCountryCode:string = await this._encService.encrypt(contryCode);

      await lastValueFrom(this._sysAdminService.getStatesByCountryCode( encCountryCode, idUser, line)).then(
        (responseData: CountryStatesResponse) => {
          if(!responseData.error){

            this.countryStatesStr = [];
            this.countryStates = responseData.response;    
            this.countryStates.forEach(item => {
              this.countryStatesStr.push(`${item.NOMBREESTADO} (${item.CODIGOESTADO})`);
            });
            this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].enable();

          } else {
            this._resourcesService.openSnackBar(responseData.msg);
          }
        }, (httpErrorResponse: HttpErrorResponse) => this._resourcesService.checkErrors(httpErrorResponse)
      );
      this.searchingStates = false;

    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar("Ocurrió un error inesperado.");
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar("Ocurrió un error inesperado.");
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }

      this.searchingStates = false;
    }
  }

  // Filtra las Entidades Federativas
  public checkEntity() {

    let entity: string = this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].value;
    if (entity === null || entity === undefined) {
      entity = '';
    }

    let countryVal = this.formGroupTax.controls['PAIS'].value;
    let countryArr = countryVal.split('(').reverse();
    let countryCode = countryArr[0].replace(')', '');

    if(countryCode == 'MEX' || countryCode == 'USA' || countryCode == 'CAN'){
      let validValue = this.countryStatesStr.filter(item => item == entity);
      if(validValue.length > 0){
        let valueArr = entity.split('(').reverse();
        let stateCode = valueArr[0].replace(')', '');

        this.verifyState(stateCode);
      }else{
        this.formGroupTax.controls['MUNICIPIO'].setValue('');
        this.formGroupTax.controls['MUNICIPIO'].disable();
        this.formGroupTax.controls['LOCALIDAD'].setValue('');
        this.formGroupTax.controls['LOCALIDAD'].disable();
        this.formGroupTax.controls['COLONIA'].setValue('');
        this.formGroupTax.controls['COLONIA'].disable();
      }
    }else{
      this.formGroupTax.controls['MUNICIPIO'].enable();
    }
  }
  private verifyState(value: string){
    let countryVal = this.formGroupTax.controls['PAIS'].value;
    let countryArr = countryVal.split('(').reverse();
    let countryCode = countryArr[0].replace(')', '');
    this.stateCities = [];
    this.stateCitiesStr = [];
    this.cityTowns = [];
    this.cityTownsStr = [];
    this.citySettings = [];
    this.citySettingsStr = [];

    if(countryCode == 'MEX'){
      this.citiesInput = false;
      this.searchStateCities(value);
    }else{
      this.citiesInput = true;
      this.formGroupTax.controls['MUNICIPIO'].enable();
    }
  }
  private async searchStateCities(stateCode: string){
    this.searchingCities = true;
    
    const idUser:string = this._resourcesService.getUser();
    const stateCodeEnc: string = await this._encService.encrypt(stateCode);
    const line: number = parseInt(this._resourcesService.getLineNumber());

    await lastValueFrom(this._sysAdminService.getCitiesByStateCode(stateCodeEnc, idUser, line)).then(
      (responseData: StateCitiesResponse) => {
        if (!responseData.error) {
          this.stateCities = responseData.response;
          this.stateCitiesStr = [];
          this.stateCities.forEach(item => {
            this.stateCitiesStr.push(`${item.NOMBREMUNICIPIO} (${item.CODIGOMUNICIPIO})`);
          });
          this.formGroupTax.controls['MUNICIPIO'].enable();
        } else {
          this._resourcesService.openSnackBar(responseData.msg);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this._resourcesService.checkErrors(httpErrorResponse)
    );
    
    this.searchingCities = false;
  }


  // Filtra los Municipios
  public checkCity() {
    if(!this.enableSearchByZipCode) {
      let municipality: string = this.formGroupTax.controls['MUNICIPIO'].value;    

      let countryVal = this.formGroupTax.controls['PAIS'].value;
      let countryArr = countryVal.split('(').reverse();
      let countryCode = countryArr[0].replace(')', '');

      if(countryCode == 'MEX'){
        let validValue = this.stateCitiesStr.filter(item => item == municipality);
        if(validValue.length > 0){
          let valueArr = municipality.split('(').reverse();
          let cityCode = valueArr[0].replace(')', '');        
          this.verifyCity(cityCode);
        }else{
          this.formGroupTax.controls['LOCALIDAD'].setValue('');
          this.formGroupTax.controls['LOCALIDAD'].disable();
          this.formGroupTax.controls['COLONIA'].setValue('');
          this.formGroupTax.controls['COLONIA'].disable();
        }
      }else{
        this.formGroupTax.controls['LOCALIDAD'].enable();
      }
    }
  }
  private verifyCity(value: string){
    let stateVal = this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].value;
    let stateArr = stateVal.split('(').reverse();
    let stateCode = stateArr[0].replace(')', '');
    
    this.cityTowns = [];
    this.cityTownsStr = [];
    this.citySettings = [];
    this.citySettingsStr = [];
    
    this.searchStateTowns(stateCode, value);
  }
  private async searchStateTowns(stateCode: string, cityCode: string){
    
    this.searchingTowns = true;
    
    const idUser: string = this._resourcesService.getUser();
    const stateCodeEnc: string = await this._encService.encrypt(stateCode);
    const cityCodeEnc: string = await this._encService.encrypt(cityCode);
    const line: number = parseInt(this._resourcesService.getLineNumber());

    await lastValueFrom(this._sysAdminService.getTowns(stateCodeEnc,cityCodeEnc,idUser,line)).then(
      (responseData: CityTownsResponse) => {
        if (!responseData.error) {
          
          this.cityTownsStr = [];
          this.cityTowns = responseData.response;

          this.cityTowns.forEach(town => {
            if(town.CODIGOLOCALIDAD == null){
              this.cityTownsStr.push('Sin localidad');
            }else{
              this.cityTownsStr.push(`${town.NOMBRELOCALIDAD} (${town.CODIGOLOCALIDAD})`);
            }
          });

          if(responseData.response.length > 1){
            this.formGroupTax.controls['LOCALIDAD'].enable();
          }else if(responseData.response.length == 1 && responseData.response[0].CODIGOLOCALIDAD != null){
            this.formGroupTax.controls['LOCALIDAD'].enable();
          }else{
            this.formGroupTax.controls['LOCALIDAD'].disable();
            this.formGroupTax.controls['LOCALIDAD'].setValue('Sin localidad');
          }
        } else {
          this._resourcesService.openSnackBar(responseData.msg);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this._resourcesService.checkErrors(httpErrorResponse)
    );
    
    this.searchingTowns = false;
  }


  private verifyTown(value: string){
    let stateVal = this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].value;
    let stateArr = stateVal.split('(').reverse();
    let stateCode = stateArr[0].replace(')', '');

    let cityVal = this.formGroupTax.controls['MUNICIPIO'].value;
    let cityArr = cityVal.split('(').reverse();
    let cityCode = cityArr[0].replace(')', '');
    
    this.citySettings = [];
    this.citySettingsStr = [];
    
    let townCode = value == 'Sin localidad' ? '-' : value;
    this.searchCitySettings(stateCode, cityCode, townCode);
  }
  private async searchCitySettings(stateCode: string, cityCode: string, townCode: string){
    this.searchingSettings = true;

    const idUser: string = this._resourcesService.getUser();
    const stateCodeEnc: string = await this._encService.encrypt(stateCode);
    const cityCodeEnc: string = await this._encService.encrypt(cityCode);
    const townCodeEnc: string = await this._encService.encrypt(townCode);
    const line: number = parseInt(this._resourcesService.getLineNumber());

    await lastValueFrom(this._sysAdminService.getCitySettings(stateCodeEnc,cityCodeEnc,townCodeEnc,idUser,line)).then(
      (responseData: CitySettingsResponse) => {
        if (!responseData.error) {
          this.citySettings = responseData.response;
          this.citySettingsStr = [];

          this.citySettings.forEach(setting => {
            this.citySettingsStr.push(`${setting.NOMBRECOLONIA} (${setting.CODIGOCOLONIA})`);
          });

          this.formGroupTax.controls['COLONIA'].enable();
        } else {
          this._resourcesService.openSnackBar(responseData.msg);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this._resourcesService.checkErrors(httpErrorResponse)
    );
    this.searchingSettings = false;
  }

  // Filtra las Colonias
  public checkColony() {

    if(!this.enableSearchByZipCode) {
      let colony:string = this.formGroupTax.controls['COLONIA'].value;
    
      let validValue = this.citySettingsStr.filter(item => item == colony);
      if(validValue.length > 0){
        let valueArr = colony.split('(').reverse();
        let settingCode = valueArr[0].replace(')', '');
  
        this.verifySetting(settingCode);
      }
    }
    
  }
  private verifySetting(value: string){
    let settingValid = this.citySettings.filter(item => item.CODIGOCOLONIA == value);    
    if(settingValid.length > 0){
      this.formGroupTax.controls['CODIGO_POSTAL'].setValue(settingValid[0].CODIGOPOSTAL);
    }
  }

  editPriority(priorityVal: string){
    let priority = this.orderPrioritiesArr.filter(item => item.value == priorityVal)[0];
    let dialogReg = this._matDialog.open(EditPriorityComponent, {
      disableClose: true,
      width: '480px',
      data: {
        priority: priority,
      }
    });

    dialogReg.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ""){
        this.updatePriority(res);
      }
    });
  }

  async updatePriority(priorityStr: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let priorityObj: PriorityInterface = JSON.parse(priorityStr);
      let prioritiesArrAux: PriorityInterface[] = [];

      this.orderPrioritiesArr.forEach(item => {
        if(item.value == priorityObj.value){
          prioritiesArrAux.push(priorityObj);
        }else{
          prioritiesArrAux.push(item);
        }
      });

      this.orderPrioritiesArr = prioritiesArrAux;
      
      let prioritiesStr = JSON.stringify(this.orderPrioritiesArr);
      let formData = new FormData();

      formData.append('id_user', idUser!);
      formData.append('linea', '1');
      formData.append('priorities', prioritiesStr);

      await lastValueFrom(this._sysAdminService.updateOrderPriorities(formData));

      this._resourcesService.openSnackBar('La configuración de las prioridades se guardó correctamente.');
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  public async alert(typeAlert: string, data: any = null) {
    this.isLoadingForm = true;

    if (typeAlert === 'ELM') {
      this.dialog.open(AlertComponent, {
        disableClose: true,
        width: '350px',
        data: {
          icon: "warning",
          title: "Eliminar Formulario",
          description: "¿Está seguro de eliminar este formulario?"
        },
      }).afterClosed().subscribe((result) => {
        if (result && typeAlert === 'ELM') {
          this.eliminar(data);
        }
      });
      this.isLoadingForm = false;
    } else if (typeAlert === 'CONFIRM') {
      this.dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          icon: "warning",
          title: "Confirmación",
          description: "¿Está seguro de modificar la información fiscal?"
        },
      }).afterClosed().subscribe((result) => {
        if (result && typeAlert === 'CONFIRM') {
          this.saveTaxInformation();
        }
      });
      this.isLoadingForm = false;
    }
  }

  public async saveTaxInformation() {
    this.isLoadingForm = true;
    let lada1:string = this.formGroupTax.controls['LADA1'].value.toString().trim();
    let arrLada1:Array<string> = lada1.split(' ');
    if (arrLada1.length > 1) {
      lada1 = arrLada1.pop()!;
    } 
    let lada2:string = this.formGroupTax.controls['LADA2'].value.toString().trim();
    let arrLada2:Array<string> = lada2.split(' ');
    if (arrLada2.length > 1) {
      lada2 = arrLada2.pop()!;
    } 

    let regimenFiscal:string = this.formGroupTax.controls['REGIMEN_FISCAL'].value.toString().trim();
    if (regimenFiscal.includes('(') && regimenFiscal.includes(')')) {
      regimenFiscal = regimenFiscal.split('(')[1].split(')')[0];
    } else {
      this._resourcesService.openSnackBar('Debe seleccionar una opción en el campo Régimen Fiscal');
      return;
    }

    const REQUEST_FORM: FormTaxInformation = {
      NOMBRE_FISCAL: this.formGroupTax.controls['NOMBRE_FISCAL'].value.toString().trim(),
      RFC: this.formGroupTax.controls['RFC'].value.toString().trim(),
      CORREO_ELECTRONICO: this.formGroupTax.controls['CORREO_ELECTRONICO'].value.toString().trim(),
      REGIMEN_FISCAL: regimenFiscal,
      LADA1: lada1,
      TELEFONO_FIJO: this.formGroupTax.controls['TELEFONO_FIJO'].value,
      LADA2: lada2,
      TELEFONO_MOVIL: this.formGroupTax.controls['TELEFONO_MOVIL'].value,
      CODIGO_POSTAL: this.formGroupTax.controls['CODIGO_POSTAL'].value.toString().trim(),
      TIPOVIALIDAD: this.formGroupTax.controls['TIPOVIALIDAD'].value.toString().trim(),
      NOMBRE_VIALIDAD: this.formGroupTax.controls['NOMBRE_VIALIDAD'].value.toString().trim(),
      ENTRE_CALLE: this.formGroupTax.controls['ENTRE_CALLE'].value.toString().trim(),
      Y_CALLE: this.formGroupTax.controls['Y_CALLE'].value.toString().trim(),
      NUMERO_EXTERIOR: this.formGroupTax.controls['NUMERO_EXTERIOR'].value.toString().trim(),
      NUMERO_INTERIOR: this.formGroupTax.controls['NUMERO_INTERIOR'].value === null ? this.formGroupTax.controls['NUMERO_INTERIOR'].value : this.formGroupTax.controls['NUMERO_INTERIOR'].value.toString().trim(),
      COLONIA: this.formGroupTax.controls['COLONIA'].value,
      LOCALIDAD: this.formGroupTax.controls['LOCALIDAD'].value.toString().trim(),
      MUNICIPIO: this.formGroupTax.controls['MUNICIPIO'].value.toString().trim(),
      ENTIDAD_FEDERATIVA: this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].value.toString().trim(),
      PAIS: this.formGroupTax.controls['PAIS'].value.toString().trim(),
      USER: this._resourcesService.getUser(),
      LINE_NUMBER: this._resourcesService.getLineNumber(),
    }

    await lastValueFrom(this._sysAdminService.saveTaxInformation(REQUEST_FORM)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this._resourcesService.openSnackBar(`¡La información fiscal ha sido actualizada!`);
        } else {
          this._resourcesService.openSnackBar(responseData.msg);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this._resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoadingForm = false;
  }

  private async getTaxInformation() {

    this.isLoading = true;
    const LINE_NUMBER: number = parseInt(this._resourcesService.getLineNumber());
    await lastValueFrom(this._sysAdminService.getTaxInformation(LINE_NUMBER)).then(
      (responseData: ResponseDataGetTaxInformation) => {
        if (!responseData.error) {
          if (responseData.response !== null) {
            this.formGroupTax.controls['NOMBRE_FISCAL'].setValue(responseData.response.INFI_NOFI);
            this.formGroupTax.controls['RFC'].setValue(responseData.response.INFI_XRFC);
            this.formGroupTax.controls['CORREO_ELECTRONICO'].setValue(responseData.response.INFI_COEL);
            this.formGroupTax.controls['REGIMEN_FISCAL'].setValue(responseData.response.INFI_CORF);
            this.formGroupTax.controls['LADA1'].setValue(responseData.response.INFI_LAD1);
            this.formGroupTax.controls['TELEFONO_FIJO'].setValue(responseData.response.INFI_TEL1);
            this.formGroupTax.controls['LADA2'].setValue(responseData.response.INFI_LAD2);
            this.formGroupTax.controls['TELEFONO_MOVIL'].setValue(responseData.response.INFI_TEL2);
            this.formGroupTax.controls['CODIGO_POSTAL'].setValue(responseData.response.INFI_COPO);
            this.formGroupTax.controls['TIPOVIALIDAD'].setValue(responseData.response.INFI_TIVI);
            this.formGroupTax.controls['NOMBRE_VIALIDAD'].setValue(responseData.response.INFI_VIAL);
            this.formGroupTax.controls['ENTRE_CALLE'].setValue(responseData.response.INFI_ENCA);
            this.formGroupTax.controls['Y_CALLE'].setValue(responseData.response.INFI_YCAL);
            this.formGroupTax.controls['NUMERO_EXTERIOR'].setValue(responseData.response.INFI_NUEX);
            this.formGroupTax.controls['NUMERO_INTERIOR'].setValue(responseData.response.INFI_NUIN);
            this.formGroupTax.controls['COLONIA'].setValue(responseData.response.INFI_COLO);
            this.formGroupTax.controls['LOCALIDAD'].setValue(responseData.response.INFI_LOCA);
            this.formGroupTax.controls['MUNICIPIO'].setValue(responseData.response.INFI_MUNI);
            this.formGroupTax.controls['ENTIDAD_FEDERATIVA'].setValue(responseData.response.INFI_ENFE);
            this.formGroupTax.controls['PAIS'].setValue(responseData.response.INFI_PAIS);
          } else {
            this._resourcesService.openSnackBar(`No hay información fiscal registrada`);
          }
        } else {
          this._resourcesService.openSnackBar(responseData.msg);
        }
      }, (httpErrorResponse:HttpErrorResponse) => this._resourcesService.checkErrors(httpErrorResponse)
    );
  }

  public async eliminar(codigo_form: string) {
    await lastValueFrom(
      this._formService.deleteForm({ CODIGO_FORM: codigo_form, USER: this._resourcesService.getUser() })
    ).then(
      (data: ResponseData) => {
        if (!data.error) {
          this._resourcesService.openSnackBar('¡Eliminación correcta!');
          this.obtenerFormularios();
        }
      },
      (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  public async modificar(codigo_form: number) {
    this.isLoadingForm = true;
    await lastValueFrom(this._formService.getFormData(codigo_form)).then(
      (data: ResponseData) => {
        let str_res = JSON.stringify(data.response);
        this._router.navigate([`sam/getbfo-update/${codigo_form}`]);
      },
      (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

  public formatDate(dateRegister:string, dateUpdate:string | null):string {
    let date:string = (dateUpdate === null) ? dateRegister : dateUpdate;
    return this._funcService.orderDate(date)!;
  }

  openMagnitudeForm(type: string, idMagnitude: string = '-'){
    let dialogRef = this._matDialog.open(MagnitudeFormComponent, {
      width: '520px',
      disableClose: true,
      data: {
        idMagnitude: idMagnitude,
        type: type
      }
    });
    
    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.saveMagnitude(type, res, idMagnitude);
      }
    })
  }

  private async saveMagnitude(type: string, magnitude: string, idMagnitude: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('magnitude', magnitude);

      if(type == 'nuevo'){
        await lastValueFrom(this._sysAdminService.registerMagnitude(formData));
        this._resourcesService.openSnackBar('La magnitud se regsitró correctamente.');
      }else{
        formData.append('id_magnitude', idMagnitude);

        await lastValueFrom(this._sysAdminService.updateMagnitude(formData));
        this._resourcesService.openSnackBar('La magnitud se actualizó correctamente.');
      }
      this.getMagnitudes();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  async getMagnitudes(){
    try{
      this.searchingMagnitudes = true;

      let idUser = localStorage.getItem('idusuario')!;
      let magnitudes: MagnitudesListResponse = await lastValueFrom(this._sysAdminService.getMagnitudes(idUser, 1));

      if(!magnitudes.error){
        let magnitudesArr: MagnitudesListItem[] = [];
        for(const magnitude of magnitudes.response){
          let idDec = await this._encService.decrypt(magnitude.ID_MAGNITUD);
          magnitude.MAGNITUD = `${magnitude.MAGNITUD} (${idDec})`;

          if(magnitude.ESTADO == 'Activo'){
            magnitudesArr.push(magnitude);
          }
        }

        this.magnitudes = magnitudesArr;
        this.magnitudesAux = this.magnitudes;
      }

      this.searchingMagnitudes = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = 'Ocurrió un error inesperado.';
      }

      this.hasError = true;
      this.isLoading = false;
      this.searchingMagnitudes = false;
    }
  }

  async getUnitsByMagnitude(event: any){
    try{
      this.searchingUnits = true;

      let idUser = localStorage.getItem('idusuario')!;
      let magnitude = event.value;
      let units: UnitsByMagnitudeListResponse = await lastValueFrom(this._sysAdminService.getUnitsByMagnitude(magnitude, idUser, 1));

      if(units.error){
        this._resourcesService.openSnackBar(units.msg);
      }else{
        let unitsArr: UnitsByMagnitudeListItem[] = [];
        for(const unit of units.response){
          let idDec = await this._encService.decrypt(unit.ID_UNIDAD);
          unit.NOMBRE_UNIDAD = `${unit.NOMBRE_UNIDAD} (${idDec})`;

          if(unit.ESTADO == 'Activo'){
            unitsArr.push(unit);
          }
        }

        this.unitsByMagnitude = unitsArr;
        this.unitsByMagnitudeAux = this.unitsByMagnitude;
        this.magnitudeSelected = magnitude;
      }

      this.searchingUnits = false;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }

      this.searchingUnits = false;
    }
  }

  openDeleteAlertDialog(mode: string, idRegister: string){
    let dialogRef = this._matDialog.open(AlertComponent, {
      width: '420px',
      data: {
        title: '¡Advertencia!',
        icon: 'warning',
        description: `¿Está seguro de eliminar la ${mode == 'magnitude' ? 'magnitud' : 'unidad'}?`,
        description2: 'Esta acción no se puede eliminar'
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res == true){
        if(mode == 'magnitude'){
          this.deleteMagnitude(idRegister);
        }else{
          this.deleteUnit(idRegister);
        }
      }
    });
  }

  private async deleteMagnitude(idMagnitude: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_magnitude', idMagnitude);

      await lastValueFrom(this._sysAdminService.deleteMagnitude(formData));
      
      this._resourcesService.openSnackBar('La magnitud se eliminó correctamente.');
      this.getMagnitudes();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  async openUnitForm(type: string, idUnit: string = '-'){
    let idMagnitudeDec = await this._encService.decrypt(this.magnitudeSelected);
    let magnitudeFilt: MagnitudesListItem | null = null;

    for(const magnitude of this.magnitudes){
      let idDec = await this._encService.decrypt(magnitude.ID_MAGNITUD);
      if(idMagnitudeDec == idDec){
        magnitudeFilt = magnitude;
      }
    }

    if(magnitudeFilt == null) return;

    let dialogRef = this._matDialog.open(UnitFormComponent, {
      width: '520px',
      disableClose: true,
      data: {
        idUnit: idUnit,
        magnitude: magnitudeFilt.MAGNITUD,
        type: type
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        let resArr = res.split('|');
        if(resArr.length < 2){
          this._resourcesService.openSnackBar('La información ingresada es inválida.');
        }else{
          this.saveUnit(type, resArr[0], resArr[1], idUnit);
        }
      }
    });
  }

  private async saveUnit(type: string, unit: string, acronymus: string, idUnit: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let data: RequestFormMeasures = {
        NOMBRE_MEDIDA: unit,
        ACRONIMO_MEDIDA: acronymus,
        NUMERO_LINEA: 1,
        USUARIO: idUser,
        ID_MAGNITUD: this.magnitudeSelected
      }

      if(type == 'nuevo'){
        await lastValueFrom(this._catalogMeasuresService.registerCatalogMeasures(data));
        this._resourcesService.openSnackBar('La unidad se regsitró correctamente.');
      }else{
        data.ID_MEDIDA = idUnit;

        await lastValueFrom(this._catalogMeasuresService.updateCatalogMeasures(data));
        this._resourcesService.openSnackBar('La unidad se actualizó correctamente.');
      }

      this.getUnitsByMagnitude({value: this.magnitudeSelected});
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  private async deleteUnit(idUnit: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let data: RequestDeleteMeasures = {
        ID_MEDIDA: idUnit,
        NUMERO_LINEA: 1,
        USUARIO: idUser,
        ID_MAGNITUD: this.magnitudeSelected,
      };

      await lastValueFrom(this._catalogMeasuresService.deleteCatalogMeasures(data));
      
      this._resourcesService.openSnackBar('La unidad de medida se eliminó correctamente.');
      this.getUnitsByMagnitude({value: this.magnitudeSelected});
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  filterMagnitudesUnits(value: string, mode: string, type: string){
    let filterValue = value.toLowerCase();

    if(mode == 'clear'){
      if(type == 'magnitudes'){
        let magnitudesFilter = this._document.getElementById('magnitudesFilt') as HTMLInputElement;
        magnitudesFilter.value = '';
        this.magnitudes = this.magnitudesAux;
      }

      if(type == 'units'){
        let unitsFilter = this._document.getElementById('unitsFilt') as HTMLInputElement;
        unitsFilter.value = '';
        this.unitsByMagnitude = this.unitsByMagnitudeAux;
      }
    }else{
      if(type == 'magnitudes' && value != ''){
        let magnitudesFilt = this.magnitudesAux.filter(item => item.MAGNITUD.toLowerCase().includes(filterValue));
        this.magnitudes = magnitudesFilt;
      }else if(type == 'magnitudes' && value == ''){
        this.magnitudes = this.magnitudesAux;
      }

      if(type == 'units' && value != ''){
        let unitsFilt = this.unitsByMagnitudeAux.filter(item => item.NOMBRE_UNIDAD.toLowerCase().includes(filterValue) || item.ACRONIMO_UNIDAD.toLowerCase().includes(filterValue));
        this.unitsByMagnitude = unitsFilt;
      }else if(type == 'units' && value == ''){
        this.unitsByMagnitude = this.unitsByMagnitudeAux;
      }
    }
  }
}

export interface ResponseData {
  error: boolean;
  msg: string;
  response: Array<any> | any;
}

export interface PriorityInterface{
  value: string,
  label: string,
  color: string,
}
