import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { lastValueFrom, map, Observable, startWith } from 'rxjs';
import { CountriesList, CountriesListResponse, LadaSelection } from '../../../../../../interfaces/countries-list.interface';
import { CountryState, CountryStatesResponse } from '../../../../../../interfaces/country-states.interface';
import { StateCitiesResponse, StateCity } from '../../../../../../interfaces/state-cities.interface';
import { CityTown, CityTownsResponse } from '../../../../../../interfaces/city-towns.interface';
import { CitySettings, CitySettingsResponse } from '../../../../../../interfaces/city-settings.interface';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ContactForm, DataDialogContact } from '../../../../../../interfaces/acquisition-management/provider.interface';
import { ResourcesService } from '../../../../../../services/resources.service';
import { EncService } from '../../../../../../services/enc.service';
import { SystemAdminService } from '../../../../../../services/system-admin.service';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { AddressByZipCodeResponse } from '../../../../../../interfaces/address-by-zip-code.interface';

@Component({
    selector: 'app-contact-provider-form',
    templateUrl: './contact-provider-form.component.html',
    styleUrl: './contact-provider-form.component.css',
    standalone: false
})
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[];

  flags: Map<string, string>;

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataDialog: DataDialogContact,
    public resourcesService: ResourcesService,
    private _dialogRef: MatDialogRef<DataDialogContact>,
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _httpClient: HttpClient,
  ) {
    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 = [];

    this.flags = new Map();
  }

  // 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),
    });
  }

  async ngOnInit() {
    this.isLoading = true;
    await this.setDataForm();
    await this.getCoutries();
    this.isLoading = false;

    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;
      })
    );
  }

  private async 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;
    }
  }

  private async getCoutries() {
    const idUser: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._sysAdminService.getCountriesList(idUser, line)).then(
      async (responseData: CountriesListResponse) => {
        if (!responseData.error) {
          this.arrCountries = responseData.response;
          
          if (this.arrCountries.length === 0) {
            this.resourcesService.openSnackBar(`No existen paises registrados en el sistema.`);
            this.resourcesService.goBack()
            return;
          }

          let mex = responseData.response.filter(item => item.COUNTRY_ID == 'MEX');
          
          this.countries.push(mex[0]);
          this.countriesStr.push(`${mex[0].NAME} (${mex[0].COUNTRY_ID})`);
          this.flags.set(`${mex[0].LADA!}-${mex[0].NOMECLARUTA_ISO2!}`, mex[0].NOMECLARUTA_ISO2!);
          this.ladasStr.push(`${mex[0].LADA!}-${mex[0].NOMECLARUTA_ISO2!}`);

          let usa = responseData.response.filter(item => item.COUNTRY_ID == 'USA');
          this.countries.push(usa[0]);
          this.countriesStr.push(`${usa[0].NAME} (${usa[0].COUNTRY_ID})`);
          this.flags.set(`${usa[0].LADA!}-${usa[0].NOMECLARUTA_ISO2!}`, usa[0].NOMECLARUTA_ISO2!);
          this.ladasStr.push(`${usa[0].LADA!}-${usa[0].NOMECLARUTA_ISO2!}`);

          let can = responseData.response.filter(item => item.COUNTRY_ID == 'CAN');
          this.countries.push(can[0]);
          this.countriesStr.push(`${can[0].NAME} (${can[0].COUNTRY_ID})`);
          this.flags.set(`${can[0].LADA!}-${can[0].NOMECLARUTA_ISO2!}`, can[0].NOMECLARUTA_ISO2!);
          this.ladasStr.push(`${can[0].LADA!}-${can[0].NOMECLARUTA_ISO2!}`);
          
          for(const country of responseData.response){
            if(country.COUNTRY_ID != null && country.COUNTRY_ID != 'MEX' && country.COUNTRY_ID != 'USA' && country.COUNTRY_ID != 'CAN'){
              this.countries.push(country);
              this.countriesStr.push(`${country.NAME} (${country.COUNTRY_ID})`);
              
              if(country.LADA != '' && country.NOMECLARUTA_ISO2 != '' && country.NOMECLARUTA_ISO2 != '0'){
                let currentURI = window.location.href;
                let currentURIArr = currentURI.split('#');
                let flagURI = `${currentURIArr[0]}assets/img/flags/${country.NOMECLARUTA_ISO2!}.png`;
                let fileExists = await this.fileExists(flagURI);

                if(fileExists){
                  this.flags.set(`${country.LADA!}-${country.NOMECLARUTA_ISO2!}`, country.NOMECLARUTA_ISO2!);
                  this.ladasStr.push(`${country.LADA!}-${country.NOMECLARUTA_ISO2!}`);
                }
              }
            }
          }

        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getCoutries();
        }
      }
    );
  }  

  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 fileExists(url: string){
    try{
      let res: any = await lastValueFrom(this._httpClient.get(url).pipe());
      if(res.status == 200){
        return true;
      }else{
        return false;
      }
    }catch(error: any){
      if(error.status == 200){
        return true;
      }else{
        return false;
      }
    }
  }
  
  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 = 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);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.searchCitySettings(stateCode, cityCode, townCode);
        }
      }
    );
    this.searchingSettings = false;
  }

  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();
  }

  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 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 = 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);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.searchAddressByZipCode(postalCode);
        }
      }
    );
  }

  // 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);
    }
  }

  // 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 = 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);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.searchStateTowns(stateCode, cityCode);
        }
      }
    );
    
    this.searchingTowns = 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 = 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);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.searchStateCities(stateCode);
        }
      }
    );
    
    this.searchingCities = false;
  }

  // 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 = 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);
          }
        }, async (httpErrorResponse: HttpErrorResponse) => {
          let response = this.resourcesService.checkErrors(httpErrorResponse)
          if (response !== null && response.reload) {
            await this.searchCountryStates(contryCode);
          }
        }
      );
      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;
    }
  }

  public registerContact() {
    this.isLoadingForm = true;
    let arrDataSource: Array<ContactForm> = this.dataDialog.dataSource;

    let ID_CONTACTO = this.formGroup.controls['ID_CONTACTO'].value;
    ID_CONTACTO = ID_CONTACTO.toString().trim();

    let NOMBRE_CONTACTO = this.formGroup.controls['NOMBRE_CONTACTO'].value;
    NOMBRE_CONTACTO = NOMBRE_CONTACTO.toString().trim();

    let TIPO_CONTACTO = this.formGroup.controls['TIPO_CONTACTO'].value;
    TIPO_CONTACTO = TIPO_CONTACTO.toString().trim();

    let CALLE = this.formGroup.controls['CALLE'].value;
    CALLE = CALLE.toString().trim();

    let NUMERO_EXTERIOR = this.formGroup.controls['NUMERO_EXTERIOR'].value;
    NUMERO_EXTERIOR = NUMERO_EXTERIOR.toString().trim();

    let NUMERO_INTERIOR = this.formGroup.controls['NUMERO_INTERIOR'].value;
    if (NUMERO_INTERIOR !== null && NUMERO_INTERIOR !== undefined && NUMERO_INTERIOR !== '') {
      NUMERO_INTERIOR = NUMERO_INTERIOR.toString().trim();
    } else {
      NUMERO_INTERIOR = null;
    }

    let CODIGO_POSTAL = this.formGroup.controls['CODIGO_POSTAL'].value;
    CODIGO_POSTAL = CODIGO_POSTAL.toString().trim();

    let COLONIA = this.formGroup.controls['COLONIA'].value;
    COLONIA = COLONIA.toString().trim();

    let LOCALIDAD = this.formGroup.controls['LOCALIDAD'].value;
    LOCALIDAD = LOCALIDAD.toString().trim();

    let MUNICIPIO = this.formGroup.controls['MUNICIPIO'].value;
    MUNICIPIO = MUNICIPIO.toString().trim();

    let ENTIDAD = this.formGroup.controls['ENTIDAD'].value;
    ENTIDAD = ENTIDAD.toString().trim();

    let PAIS = this.formGroup.controls['PAIS'].value;
    PAIS = PAIS.toString().trim();

    let LADA1 = this.formGroup.controls['LADA1'].value;
    LADA1 = LADA1.toString().trim();
    LADA1 = LADA1.split('-')[0];

    let TELEFONO1 = this.formGroup.controls['TELEFONO1'].value;
    TELEFONO1 = TELEFONO1.toString().trim();

    let LADA2 = this.formGroup.controls['LADA2'].value;
    if (LADA2 !== null && LADA2 !== undefined && LADA2 !== '') {
      LADA2 = LADA2.toString().trim();
      LADA2 = LADA2.split('-')[0];
    } else {
      LADA2 = null;
    }

    let TELEFONO2 = this.formGroup.controls['TELEFONO2'].value;
    if (TELEFONO2 !== null && TELEFONO2 !== undefined && TELEFONO2 !== '') {
      TELEFONO2 = TELEFONO2.toString().trim();
    } else {
      TELEFONO2 = null;
    }

    let CORREO1 = this.formGroup.controls['CORREO1'].value;
    CORREO1 = CORREO1.toString().trim();

    let CORREO2 = this.formGroup.controls['CORREO2'].value;
    if (CORREO2 !== null && CORREO2 !== undefined && CORREO2 !== '') {
      CORREO2 = CORREO2.toString().trim();
    } else {
      CORREO2 = null;
    }

    let OBSERVACIONES = this.formGroup.controls['OBSERVACIONES'].value;
    OBSERVACIONES = OBSERVACIONES.toString().trim();

    let ESTADO = this.formGroup.controls['ESTADO'].value;
    ESTADO = ESTADO.toString().trim();

    const REQUEST_FORM = {
      ID_CONTACTO: ID_CONTACTO,
      NOMBRE_CONTACTO: NOMBRE_CONTACTO,
      TIPO_CONTACTO: TIPO_CONTACTO,
      CALLE: CALLE,
      NUMERO_EXTERIOR: NUMERO_EXTERIOR,
      NUMERO_INTERIOR: NUMERO_INTERIOR,
      CODIGO_POSTAL: CODIGO_POSTAL,
      COLONIA: COLONIA,
      LOCALIDAD: LOCALIDAD,
      MUNICIPIO: MUNICIPIO,
      ENTIDAD: ENTIDAD,
      PAIS: PAIS,
      LADA1: LADA1,
      TELEFONO1: TELEFONO1,
      LADA2: LADA2,
      TELEFONO2: TELEFONO2,
      CORREO1: CORREO1,
      CORREO2: CORREO2,
      OBSERVACIONES: OBSERVACIONES,
      ESTADO: ESTADO,
    }

    arrDataSource.push(REQUEST_FORM);
    this._dialogRef.close(arrDataSource);
    this.isLoadingForm = false;
  }

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

        let ID_CONTACTO = this.formGroup.controls['ID_CONTACTO'].value;
        ID_CONTACTO = ID_CONTACTO.toString().trim();

        let NOMBRE_CONTACTO = this.formGroup.controls['NOMBRE_CONTACTO'].value;
        NOMBRE_CONTACTO = NOMBRE_CONTACTO.toString().trim();

        let TIPO_CONTACTO = this.formGroup.controls['TIPO_CONTACTO'].value;
        TIPO_CONTACTO = TIPO_CONTACTO.toString().trim();

        let CALLE = this.formGroup.controls['CALLE'].value;
        CALLE = CALLE.toString().trim();

        let NUMERO_EXTERIOR = this.formGroup.controls['NUMERO_EXTERIOR'].value;
        NUMERO_EXTERIOR = NUMERO_EXTERIOR.toString().trim();

        let NUMERO_INTERIOR = this.formGroup.controls['NUMERO_INTERIOR'].value;
        if (NUMERO_INTERIOR !== null && NUMERO_INTERIOR !== undefined && NUMERO_INTERIOR !== '') {
          NUMERO_INTERIOR = NUMERO_INTERIOR.toString().trim();
        } else {
          NUMERO_INTERIOR = null;
        }

        let CODIGO_POSTAL = this.formGroup.controls['CODIGO_POSTAL'].value;
        CODIGO_POSTAL = CODIGO_POSTAL.toString().trim();

        let COLONIA = this.formGroup.controls['COLONIA'].value;
        COLONIA = COLONIA.toString().trim();

        let LOCALIDAD = this.formGroup.controls['LOCALIDAD'].value;
        LOCALIDAD = LOCALIDAD.toString().trim();

        let MUNICIPIO = this.formGroup.controls['MUNICIPIO'].value;
        MUNICIPIO = MUNICIPIO.toString().trim();

        let ENTIDAD = this.formGroup.controls['ENTIDAD'].value;
        ENTIDAD = ENTIDAD.toString().trim();

        let PAIS = this.formGroup.controls['PAIS'].value;
        PAIS = PAIS.toString().trim();

        let LADA1 = this.formGroup.controls['LADA1'].value;
        LADA1 = LADA1.toString().trim();
        LADA1 = LADA1.split('-')[0];

        let TELEFONO1 = this.formGroup.controls['TELEFONO1'].value;
        TELEFONO1 = TELEFONO1.toString().trim();

        let LADA2 = this.formGroup.controls['LADA2'].value;
        if (LADA2 !== null && LADA2 !== undefined && LADA2 !== '') {
          LADA2 = LADA2.toString().trim();
          LADA2 = LADA2.split('-')[0];
        } else {
          LADA2 = null;
        }

        let TELEFONO2 = this.formGroup.controls['TELEFONO2'].value;
        if (TELEFONO2 !== null && TELEFONO2 !== undefined && TELEFONO2 !== '') {
          TELEFONO2 = TELEFONO2.toString().trim();
        } else {
          TELEFONO2 = null;
        }

        let CORREO1 = this.formGroup.controls['CORREO1'].value;
        CORREO1 = CORREO1.toString().trim();

        let CORREO2 = this.formGroup.controls['CORREO2'].value;
        if (CORREO2 !== null && CORREO2 !== undefined && CORREO2 !== '') {
          CORREO2 = CORREO2.toString().trim();
        } else {
          CORREO2 = null;
        }

        let OBSERVACIONES = this.formGroup.controls['OBSERVACIONES'].value;
        OBSERVACIONES = OBSERVACIONES.toString().trim();

        let ESTADO = this.formGroup.controls['ESTADO'].value;
        ESTADO = ESTADO.toString().trim();

        const REQUEST_FORM = {
          ID_CONTACTO: ID_CONTACTO,
          NOMBRE_CONTACTO: NOMBRE_CONTACTO,
          TIPO_CONTACTO: TIPO_CONTACTO,
          CALLE: CALLE,
          NUMERO_EXTERIOR: NUMERO_EXTERIOR,
          NUMERO_INTERIOR: NUMERO_INTERIOR,
          CODIGO_POSTAL: CODIGO_POSTAL,
          COLONIA: COLONIA,
          LOCALIDAD: LOCALIDAD,
          MUNICIPIO: MUNICIPIO,
          ENTIDAD: ENTIDAD,
          PAIS: PAIS,
          LADA1: LADA1,
          TELEFONO1: TELEFONO1,
          LADA2: LADA2,
          TELEFONO2: TELEFONO2,
          CORREO1: CORREO1,
          CORREO2: CORREO2,
          OBSERVACIONES: OBSERVACIONES,
          ESTADO: ESTADO,
        }

        element = REQUEST_FORM;
      }
      return element;
    });
    this._dialogRef.close(arrDataSource);
    this.isLoadingForm = false;
  }
}
