import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { Observable, lastValueFrom, map, startWith } from 'rxjs';
import { ContactData, DataDialogContact } from 'src/app/interfaces/acquisition-management/provider.interface';
import { AddressByZipCodeResponse } from 'src/app/interfaces/address-by-zip-code.interface';
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 { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { SystemAdminService } from 'src/app/services/system-admin.service';
import { countryCodeEmoji } from 'country-code-emoji';
import flag from 'country-code-emoji';

@Component({
  selector: 'app-info-contact-provider',
  templateUrl: './contact-provider-form.component.html',
  styleUrls: ['./contact-provider-form.component.css']
})
export class ContactProviderFormComponent implements OnInit {

  public formGroup: FormGroup;
  public titleDialog: string;
  public isLoading: boolean;
  public isLoadingForm: boolean;

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

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

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

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataDialog: DataDialogContact,
    public resourcesService: ResourcesService,
    private _dialogRef: MatDialogRef<DataDialogContact>,
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
  ) {
    if (dataDialog.typeDialog === 'REGISTER') {
      this.titleDialog = 'Registro de Contacto';
    } else if (dataDialog.typeDialog === 'UPDATE') {
      this.titleDialog = 'Modificación de Contacto';
    }else{
      this.titleDialog = 'Contacto';
    }
    this.formGroup = this.createFromGroup();
    this.isLoading = false;
    this.isLoadingForm = false;

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

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

  ngOnInit(): void {
    this.setDataForm();
    this.getCoutries();

    this.formGroup.controls['LOCALIDAD'].valueChanges.subscribe(value => {
      if(!this.enableSearchByZipCode) {
        let countryVal = this.formGroup.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.formGroup.controls['COLONIA'].setValue('');
            this.formGroup.controls['COLONIA'].disable();
          }
        }else{
          this.formGroup.controls['COLONIA'].enable();
        }
      }
    });

    this.filteredLadas1 = this.formGroup.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.formGroup.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.filteredSettings = this.formGroup.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.formGroup.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.formGroup.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.formGroup.controls['ENTIDAD'].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.formGroup.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;
      })
    );
  }

  // Creación de formulario de registro de módulos
  private createFromGroup(): FormGroup {
    return new FormGroup({
      ID_CONTACTO : new FormControl(this.dataDialog.dataSource.length + 1, Validators.required),
      NOMBRE_CONTACTO : new FormControl('', Validators.required),
      TIPO_CONTACTO : new FormControl('', Validators.required),
      CALLE : new FormControl('', Validators.required),
      NUMERO_EXTERIOR : new FormControl('', Validators.required),
      NUMERO_INTERIOR : new FormControl(''),
      CODIGO_POSTAL : new FormControl('', [Validators.required, Validators.pattern("[0-9]{5}")]),
      COLONIA : new FormControl('', Validators.required),
      LOCALIDAD : new FormControl('', Validators.required),
      MUNICIPIO : new FormControl('', Validators.required),
      ENTIDAD : new FormControl('', Validators.required),
      PAIS : new FormControl('', Validators.required),
      LADA1 : new FormControl('', Validators.required),
      TELEFONO1 : new FormControl('', Validators.required),
      LADA2 : new FormControl(''),
      TELEFONO2 : new FormControl(''),
      CORREO1 : new FormControl('', [Validators.required, Validators.email]),
      CORREO2 : new FormControl('', Validators.email),
      OBSERVACIONES : new FormControl('', Validators.required),
      ESTADO : new FormControl('Nuevo', Validators.required),
    });
  }

  private setDataForm() {
    if (this.dataDialog.typeDialog === 'UPDATE' || this.dataDialog.typeDialog === 'ONLYREAD') {
      this.isLoading = true;
      this.formGroup.controls['ID_CONTACTO'].setValue(this.dataDialog.dataElement.ID_CONTACTO);
      this.formGroup.controls['NOMBRE_CONTACTO'].setValue(this.dataDialog.dataElement.NOMBRE_CONTACTO);
      this.formGroup.controls['TIPO_CONTACTO'].setValue(this.dataDialog.dataElement.TIPO_CONTACTO);
      this.formGroup.controls['CALLE'].setValue(this.dataDialog.dataElement.CALLE);
      this.formGroup.controls['NUMERO_EXTERIOR'].setValue(this.dataDialog.dataElement.NUMERO_EXTERIOR);
      this.formGroup.controls['NUMERO_INTERIOR'].setValue(this.dataDialog.dataElement.NUMERO_INTERIOR);
      this.formGroup.controls['CODIGO_POSTAL'].setValue(this.dataDialog.dataElement.CODIGO_POSTAL);
      this.formGroup.controls['COLONIA'].setValue(this.dataDialog.dataElement.COLONIA);
      this.formGroup.controls['LOCALIDAD'].setValue(this.dataDialog.dataElement.LOCALIDAD);
      this.formGroup.controls['MUNICIPIO'].setValue(this.dataDialog.dataElement.MUNICIPIO);
      this.formGroup.controls['ENTIDAD'].setValue(this.dataDialog.dataElement.ENTIDAD);
      this.formGroup.controls['PAIS'].setValue(this.dataDialog.dataElement.PAIS);
      this.formGroup.controls['LADA1'].setValue(this.dataDialog.dataElement.LADA1);
      this.formGroup.controls['TELEFONO1'].setValue(this.dataDialog.dataElement.TELEFONO1);
      this.formGroup.controls['LADA2'].setValue(this.dataDialog.dataElement.LADA2);
      this.formGroup.controls['TELEFONO2'].setValue(this.dataDialog.dataElement.TELEFONO2);
      this.formGroup.controls['CORREO1'].setValue(this.dataDialog.dataElement.CORREO1);
      this.formGroup.controls['CORREO2'].setValue(this.dataDialog.dataElement.CORREO2);
      this.formGroup.controls['OBSERVACIONES'].setValue(this.dataDialog.dataElement.OBSERVACIONES);
      if (this.dataDialog.dataElement.ESTADO !== 'Nuevo') {
        this.formGroup.controls['ESTADO'].setValue('Modificado');
      }
      this.isLoading = false;
    }
  }


  public registerContact() {
    this.isLoadingForm = true;
    let arrDataSource: Array<ContactData> = this.dataDialog.dataSource;
    arrDataSource.push(this.formGroup.value);
    this._dialogRef.close(arrDataSource);
    this.isLoadingForm = false;
  }

  public updateContact() {
    this.isLoadingForm = true;
    let arrDataSource: Array<ContactData> = this.dataDialog.dataSource;
    arrDataSource = arrDataSource.map((element: ContactData) => {
      if (element.ID_CONTACTO === this.formGroup.controls['ID_CONTACTO'].value) {
        element = this.formGroup.value;
      }
      return element;
    });
    this._dialogRef.close(arrDataSource);
    this.isLoadingForm = false;
  }


  public validatePhone2() {
    let phone2: string = this.formGroup.controls['TELEFONO2'].value;
    if (phone2 !== null && phone2 !== '') {
      this.formGroup.controls['LADA2'].setValidators(Validators.required);
    } else {
      this.formGroup.controls['LADA2'].clearValidators();
    }
    this.formGroup.controls['LADA2']?.updateValueAndValidity();
  }

  public validateLada2() {
    let lada2: string = this.formGroup.controls['LADA2'].value;
    if (lada2 !== null && lada2 !== '') {
      this.formGroup.controls['TELEFONO2'].setValidators(Validators.required);
    } else {
      this.formGroup.controls['TELEFONO2'].clearValidators();
    }
    this.formGroup.controls['TELEFONO2'].updateValueAndValidity();
  }


  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.formGroup.controls['CODIGO_POSTAL'].value.toString();

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

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


      this.formGroup.controls['CODIGO_POSTAL'].enable();
      this.formGroup.controls['COLONIA'].enable();
      this.formGroup.controls['MUNICIPIO'].enable();
      this.formGroup.controls['ENTIDAD'].enable();
      this.formGroup.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.formGroup.controls['PAIS'].setValue('México (MEX)', { emitValue: false, });
          this.citySettings = [];
          this.citySettingsStr = [];

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

          if (responseData.response.CODIGO_MUNICIPIO !== null) {
            this.formGroup.controls['MUNICIPIO'].setValue(`${responseData.response.NOMBRE_MUNICIPIO} (${responseData.response.CODIGO_MUNICIPIO})`);
          } else {
            this.formGroup.controls['MUNICIPIO'].setValue(`Sin municipio`);
          }
          
          if (responseData.response.CODIGO_ESTADO !== null) {
            this.formGroup.controls['ENTIDAD'].setValue(`${responseData.response.NOMBRE_ESTADO} (${responseData.response.CODIGO_ESTADO})`);
          } else {
            this.formGroup.controls['ENTIDAD'].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.formGroup.controls['COLONIA'].setValue('Sin colonia');
            this.formGroup.controls['LOCALIDAD'].setValue(`Sin localidad`);
            this.formGroup.controls['MUNICIPIO'].setValue(`Sin municipio`);
            this.formGroup.controls['ENTIDAD'].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.formGroup.controls['PAIS'].value;

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

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

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

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

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

    if(countryCode == 'CAN' || countryCode == 'MEX' || countryCode == 'USA'){
      this.searchCountryStates(countryCode);
    }else{
      this.formGroup.controls['ENTIDAD'].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.formGroup.controls['ENTIDAD'].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.formGroup.controls['ENTIDAD'].value;
    if (entity === null || entity === undefined) {
      entity = '';
    }

    let countryVal = this.formGroup.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.formGroup.controls['MUNICIPIO'].setValue('');
        this.formGroup.controls['MUNICIPIO'].disable();
        this.formGroup.controls['LOCALIDAD'].setValue('');
        this.formGroup.controls['LOCALIDAD'].disable();
        this.formGroup.controls['COLONIA'].setValue('');
        this.formGroup.controls['COLONIA'].disable();
      }
    }else{
      this.formGroup.controls['MUNICIPIO'].enable();
    }
  }
  private verifyState(value: string){
    let countryVal = this.formGroup.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.formGroup.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.formGroup.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.formGroup.controls['MUNICIPIO'].value;    

      let countryVal = this.formGroup.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.formGroup.controls['LOCALIDAD'].setValue('');
          this.formGroup.controls['LOCALIDAD'].disable();
          this.formGroup.controls['COLONIA'].setValue('');
          this.formGroup.controls['COLONIA'].disable();
        }
      }else{
        this.formGroup.controls['LOCALIDAD'].enable();
      }
    }
  }
  private verifyCity(value: string){
    let stateVal = this.formGroup.controls['ENTIDAD'].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.formGroup.controls['LOCALIDAD'].enable();
          }else if(responseData.response.length == 1 && responseData.response[0].CODIGOLOCALIDAD != null){
            this.formGroup.controls['LOCALIDAD'].enable();
          }else{
            this.formGroup.controls['LOCALIDAD'].disable();
            this.formGroup.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.formGroup.controls['ENTIDAD'].value;
    let stateArr = stateVal.split('(').reverse();
    let stateCode = stateArr[0].replace(')', '');

    let cityVal = this.formGroup.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.formGroup.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.formGroup.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.formGroup.controls['CODIGO_POSTAL'].setValue(settingValid[0].CODIGOPOSTAL);
    }
  }

}
