import { Component, 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 { ResourcesService, ResponseData } from '../../../../../services/resources.service';
import { DispatchService } from '../../../../../services/acquisition-management/dispatch.service';
import { ActivatedRoute, Router } from '@angular/router';
import { EncService } from '../../../../../services/enc.service';
import { SystemAdminService } from '../../../../../services/system-admin.service';
import { MatDialog } from '@angular/material/dialog';
import { HttpErrorResponse } from '@angular/common/http';
import { DispatchRequest, ResponseDataDispatchById } from '../../../../../interfaces/acquisition-management/dispatch.interface';
import { AddressByZipCodeResponse } from '../../../../../interfaces/address-by-zip-code.interface';
import { AlertComponent } from '../../../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-dispatch-form',
    templateUrl: './dispatch-form.component.html',
    styleUrl: './dispatch-form.component.css',
    standalone: false
})
export class DispatchFormComponent implements OnInit {
  public formGroup: FormGroup;
  public isLoading: boolean;
  public isLoadingForm: boolean;
  public typeRequest: string;
  public title: string;

  public filteredLadas?: Observable<string[]>;
  public filteredCountries?: Observable<string[]>;
  public filteredStates?: Observable<string[]>;
  public filteredCities?: Observable<string[]>;
  public filteredTowns?: Observable<string[]>;
  public 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(
    public resourcesService: ResourcesService,
    private _dispatchService: DispatchService,
    private _activatedRouter: ActivatedRoute,
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _dialog: MatDialog,
    private _router: Router,
  ) {
    this.formGroup = this.createFormGroup();
    this.title = '';
    this.typeRequest = '';
    this.isLoadingForm = true;
    this.isLoading = true;

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

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

    this.flags = new Map();
  }

  private createFormGroup() {
    return new FormGroup({
      ID_DESPACHO: new FormControl(''),
      NOMBRE_DESPACHO: new FormControl('', Validators.required),
      NOMBRE_RESPONSABLE: new FormControl('', Validators.required),
      APELLIDO_PATERNO: new FormControl('', Validators.required),
      APELLIDO_MATERNO: new FormControl(''),
      LADA: new FormControl('', Validators.required),
      TELEFONO: new FormControl('', Validators.required),
      CORREO_ELECTRONICO: new FormControl('', [Validators.required, Validators.email]),
      CALLE: new FormControl('', Validators.required),
      NUMERO_EXTERIOR: new FormControl('', Validators.required),
      NUMERO_INTERIOR: new FormControl(''),
      CODIGO_POSTAL: new FormControl('', Validators.required),
      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),
      COMENTARIOS: new FormControl(''),
    });
  }

  async ngOnInit(){
    await this.getCoutries();
    await this.getTypeRequest();

    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.filteredLadas = this.formGroup.controls['LADA'].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_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.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;
      })
    );

    this.isLoadingForm = false;
    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) {
          console.log(responseData.response);
          
          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.resourcesService.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 async getTypeRequest() {
    const encTypeRequest:string = this._activatedRouter.snapshot.paramMap.get('form')!;
    const dataTypeRequest = JSON.parse(await this._encService.decrypt(encTypeRequest));
    this.typeRequest = dataTypeRequest.typeForm;    
    const idDispatch = dataTypeRequest.idDispatch;
    
    if (this.typeRequest === 'UPD') {
      this.title = 'Modificación de despacho';
      await this.getDispatchById(idDispatch);
      
    } else {
      this.title = 'Registro de despacho';

    }
  }

  private verifyTown(value: string){
    let stateVal = this.formGroup.controls['ENTIDAD_FEDERATIVA'].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 = 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;
  }

  private async getDispatchById(idDispatch:string) {
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._dispatchService.getDispatchById(idDispatch, user, line)).then(
      (responseData: ResponseDataDispatchById) => {
        if (!responseData.error) {
          this.formGroup.controls['ID_DESPACHO'].setValue( responseData.response.ID_DESPACHO );
          this.formGroup.controls['NOMBRE_DESPACHO'].setValue( responseData.response.NOMBRE_DESPACHO );
          this.formGroup.controls['NOMBRE_RESPONSABLE'].setValue( `${responseData.response.NOMBRE}`);
          this.formGroup.controls['APELLIDO_PATERNO'].setValue( responseData.response.APELLIDO_PATERNO );
          this.formGroup.controls['APELLIDO_MATERNO'].setValue( responseData.response.APELLIDO_MATERNO );
          this.formGroup.controls['LADA'].setValue( responseData.response.LADA );
          this.formGroup.controls['TELEFONO'].setValue( responseData.response.TELEFONO );
          this.formGroup.controls['CORREO_ELECTRONICO'].setValue( responseData.response.CORREO_ELECTRONICO );
          this.formGroup.controls['CALLE'].setValue( responseData.response.CALLE );
          this.formGroup.controls['NUMERO_EXTERIOR'].setValue( responseData.response.NUMERO_EXTERIOR );
          this.formGroup.controls['NUMERO_INTERIOR'].setValue( responseData.response.NUMERO_INTERIOR );
          this.formGroup.controls['CODIGO_POSTAL'].setValue( responseData.response.CODIGO_POSTAL );
          this.formGroup.controls['COLONIA'].setValue( responseData.response.COLONIA );
          this.formGroup.controls['LOCALIDAD'].setValue( responseData.response.LOCALIDAD );
          this.formGroup.controls['MUNICIPIO'].setValue( responseData.response.MUNICIPIO );
          this.formGroup.controls['ENTIDAD_FEDERATIVA'].setValue( responseData.response.ENTIDAD_FEDERATIVA );
          this.formGroup.controls['PAIS'].setValue( responseData.response.PAIS );
          this.formGroup.controls['COMENTARIOS'].setValue( responseData.response.COMENTARIOS );
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getDispatchById(idDispatch);
        }
      }
    )
  }

  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_FEDERATIVA'].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_FEDERATIVA'].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_FEDERATIVA'].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_FEDERATIVA'].setValue(`${responseData.response.NOMBRE_ESTADO} (${responseData.response.CODIGO_ESTADO})`);
          } else {
            this.formGroup.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.formGroup.controls['COLONIA'].setValue('Sin colonia');
            this.formGroup.controls['LOCALIDAD'].setValue(`Sin localidad`);
            this.formGroup.controls['MUNICIPIO'].setValue(`Sin municipio`);
            this.formGroup.controls['ENTIDAD_FEDERATIVA'].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_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 = 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_FEDERATIVA'].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_FEDERATIVA'].setValue('');
      this.formGroup.controls['ENTIDAD_FEDERATIVA'].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_FEDERATIVA'].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_FEDERATIVA'].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_FEDERATIVA'].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 dialogAlert() {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        icon: "warning",
        title: this.typeRequest === 'REG' ? 'Registro de Despacho' : 'Modificación de Despacho',
        description: `¿Está seguro de ${this.typeRequest === 'REG' ? 'registrar' : 'modificar'} el despacho?`
      },
    }).afterClosed().subscribe((result) => {
      if (result && this.typeRequest === 'REG') {
        this.registerDispatch()
      } else if (result && this.typeRequest === 'UPD') {
        this.updateDispatch();
      }
    });
  }

  private async registerDispatch() {
    this.isLoadingForm = true;
    const objectRegister = this.requestForm();
    if (objectRegister === null) {
      return;
    }
    await lastValueFrom(this._dispatchService.registerDispatch( objectRegister )).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡El despacho se ha registrado exitosamente!`);
          this._router.navigate(['/sam/GEAD/DESP/MDDE']);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.registerDispatch();
        }
      }
    )
    this.isLoadingForm = false;
  }

  private requestForm(): DispatchRequest | null {
    let strNumeroDespacho:string = this.formGroup.controls['ID_DESPACHO'].value;
    strNumeroDespacho = strNumeroDespacho === null ? '' : strNumeroDespacho;
    strNumeroDespacho = strNumeroDespacho.toString().trim();
    let strNombreDespacho:string = this.formGroup.controls['NOMBRE_DESPACHO'].value;
    strNombreDespacho = strNombreDespacho.toString().trim();
    let strNombreResponsable:string = this.formGroup.controls['NOMBRE_RESPONSABLE'].value;
    strNombreResponsable = strNombreResponsable.toString().trim();
    let strApellidoPaterno:string = this.formGroup.controls['APELLIDO_PATERNO'].value;
    strApellidoPaterno = strApellidoPaterno === null ? '' : strApellidoPaterno;
    strApellidoPaterno = strApellidoPaterno.toString().trim();
    let strApellidoMaterno = this.formGroup.controls['APELLIDO_MATERNO'].value;
    if (strApellidoMaterno !== null && strApellidoMaterno !== '') {
      strApellidoMaterno = strApellidoMaterno.toString().trim();
    }
    let strLada:string = this.formGroup.controls['LADA'].value;
    strLada = strLada.toString().trim();
    let arrLada = strLada.split(' ');    
    if (arrLada.length === 2) {
      strLada = arrLada[1];
    }
    let strTelefono:string = this.formGroup.controls['TELEFONO'].value;
    strTelefono = strTelefono.toString().trim();
    let strCorreoElectronico:string = this.formGroup.controls['CORREO_ELECTRONICO'].value;
    strCorreoElectronico = strCorreoElectronico.toString().trim();
    let strCalle:string = this.formGroup.controls['CALLE'].value;
    strCalle = strCalle.toString().trim();
    let strNumeroExterior:string = this.formGroup.controls['NUMERO_EXTERIOR'].value;
    strNumeroExterior = strNumeroExterior.toString().trim();
    let strNumeroInterior:string = this.formGroup.controls['NUMERO_INTERIOR'].value;
    strNumeroInterior = strNumeroInterior === null ? '' : strNumeroInterior;
    strNumeroInterior = strNumeroInterior.toString().trim();
    let strCodigoPostal:string = this.formGroup.controls['CODIGO_POSTAL'].value;
    strCodigoPostal = strCodigoPostal.toString().trim();
    let strColonia:string = this.formGroup.controls['COLONIA'].value;
    strColonia = strColonia.toString().trim();
    let strLocalidad:string = this.formGroup.controls['LOCALIDAD'].value;
    strLocalidad = strLocalidad.toString().trim();
    let strMunicipio:string = this.formGroup.controls['MUNICIPIO'].value;
    strMunicipio = strMunicipio.toString().trim();
    let strEntidadFederativa:string = this.formGroup.controls['ENTIDAD_FEDERATIVA'].value;
    strEntidadFederativa = strEntidadFederativa.toString().trim();
    let strPais:string = this.formGroup.controls['PAIS'].value;
    strPais = strPais.toString().trim();
    let strComentarios:string = this.formGroup.controls['COMENTARIOS'].value;
    strComentarios = strComentarios === null ? '' : strComentarios;
    strComentarios = strComentarios.toString().trim();

    const requestData: DispatchRequest =  {
      ID_DESPACHO: strNumeroDespacho,
      NOMBRE_DESPACHO: strNombreDespacho,
      NOMBRE_RESPONSABLE: strNombreResponsable,
      APELLIDO_PATERNO: strApellidoPaterno,
      APELLIDO_MATERNO: strApellidoMaterno,
      LADA: strLada,
      TELEFONO: strTelefono,
      CORREO_ELECTRONICO: strCorreoElectronico,
      CALLE: strCalle,
      NUMERO_EXTERIOR: strNumeroExterior,
      NUMERO_INTERIOR: strNumeroInterior,
      CODIGO_POSTAL: strCodigoPostal,
      COLONIA: strColonia,
      LOCALIDAD: strLocalidad,
      MUNICIPIO: strMunicipio,
      ENTIDAD_FEDERATIVA: strEntidadFederativa,
      PAIS: strPais,
      COMENTARIOS: strComentarios,
      USUARIO: this.resourcesService.getUser(),
      LINE_NUMBER: this.resourcesService.getLineNumber(),
    }
    return requestData
  }

  private async updateDispatch() {
    this.isLoadingForm = true;
    const objectUpdate = this.requestForm();
    if (objectUpdate === null) {
      this.isLoadingForm = false;
      return;
    }
    await lastValueFrom(this._dispatchService.updateDispatch( objectUpdate )).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡El despacho se ha modificado exitosamente!`);
          this._router.navigate(['/sam/GEAD/DESP/MDDE']);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.updateDispatch();
        }
      }
    )
    this.isLoadingForm = false;
  }
}
