File: /var/www/vhost/disk-apps/pwa.sports-crowd.com/src/app/pages/address/address.ts
import { Component, OnInit } from "@angular/core";
import { NavController, AlertController } from "@ionic/angular";
import { ActivatedRoute } from "@angular/router";
import { TranslateService } from "@ngx-translate/core";
import { UserService } from "../../services/user.service";
import { AddressService } from "../../services/address.service";
import { UtilsService } from "../../services/utils.service";
import { StorageService } from "../../services/storage.service";
import { Location } from '@angular/common';
import { Geolocation } from '@capacitor/geolocation';
import { NativeGeocoder } from '@capgo/nativegeocoder';
@Component({
selector: "page-address",
templateUrl: "address.html",
styleUrls: ["./address.scss"],
})
export class AddressPage implements OnInit {
private messageText: any;
pageOrigin: any;
allCities: any = [];
coords: any;
options: any;
// addressInfo: any = {typeTrack: 'Carrera', track1: '5', track2: '10', track3: '58 Apto 501', tagName : 'Apto', neighborhood: 'Centro', howToGet: 'Al lado del super'};
selectOptionsDepartament = {};
selectOptionsCity = {};
statusInvalidTypeTrack: boolean = false;
statusInvalidTagName: boolean = false;
statusInvalidNeighborhood: boolean = false;
statusInvalidDepartment: boolean = false;
statusInvalidCity: boolean = false;
statusCityService: boolean = false;
addressString: string = "";
departamentLocationUser: any;
cityLocationUser: any;
cityUser: any;
departmentUser: any;
neighborhood: any;
coordsAddress: any;
statusCallGetPositionUser: boolean = false;
statusSendCreateAddress: boolean = false;
inPoint: boolean = false;
backButton: any = false;
coverage_id: any = null;
location: any;
constructor(
public navCtrl: NavController,
private translateService: TranslateService,
public addressProvider: AddressService,
public alertCtrl: AlertController,
private storage: StorageService,
public userProvider: UserService,
public utilsService: UtilsService,
public route: ActivatedRoute,
private locationService: Location
) {
this.getPositionUser();
this.pageOrigin = this.route.snapshot.paramMap.get("pageOrigin");
this.backButton = this.route.snapshot.paramMap.get("backButton");
// se consulta la traduccion de departamento y ciudad para el titulo del select
this.translateService.get(["LABEL_DEPARTAMENT"]).subscribe((values) => {
this.selectOptionsDepartament = {
title: values.LABEL_DEPARTAMENT,
mode: "md",
};
});
this.translateService.get(["LABEL_CITY"]).subscribe((values) => {
this.selectOptionsCity = {
title: values.LABEL_CITY,
mode: "md",
};
});
//
// traduccion textos
translateService
.get(["CITY_OUT_OF_COVERAGE", "ADDRESS_OUT_OF_COVERAGE", "ALREADY_ADDRESS", "HIGH_ACCURACY", "LOCATION_NOT_FUNCTION"])
.subscribe((values) => {
this.messageText = {
cityOutCoverage: values.CITY_OUT_OF_COVERAGE,
addressOutCoverage: values.ADDRESS_OUT_OF_COVERAGE,
alreadyAddress: values.ALREADY_ADDRESS,
high_accuracy: values.HIGH_ACCURACY,
locationNotFunction: values.LOCATION_NOT_FUNCTION,
sendCoveragePending: values.SEND_COVERAGE_PENDING,
};
});
}
ngOnInit() {
}
ionViewDidLoad() { }
ionViewWillEnter() {
this.addressProvider.getAllDepartments();
this.addressProvider.getAllCitiesService();
}
async getPositionUser() {
this.coords = await Geolocation.getCurrentPosition();
let optionsGeocoder = {
useLocale: true,
maxResults: 5,
latitude: this.coords.latitude,
longitude: this.coords.longitude,
apiKey: 'AIzaSyDv579f74i_47NZHBfdxAxprOsZ526iHVI'
};
NativeGeocoder.reverseGeocode(optionsGeocoder)
.then((result) => {
setTimeout(() => {
let department = this.addressProvider._allDepartments.find((department) => department.name === result[0].administrativeArea);
if (department) {
this.departmentUser = department.id;
this.cityLocationUser = result[0].subAdministrativeArea;
this.getAllCities(this.departmentUser, true);
}
}, 500);
})
.catch((error: any) => {
console.log("error nativeGeocoder: ", error);
});
}
async getAllCities(department_id, statusLoading) {
if (statusLoading) {
this.utilsService.presentLoading(this.translateService.instant("all.loading"));
}
(await this.addressProvider.getAllCities(department_id)).subscribe(
(resp) => {
if (resp["status"] == "success") {
this.allCities = resp["cities"];
setTimeout(() => {
if (this.allCities && this.cityLocationUser) {
let city = this.allCities.find((city) => city.name === this.cityLocationUser);
if (city) {
this.cityUser = city.id;
}
}
}, 500);
if (statusLoading) {
this.utilsService.dismissLoading();
}
}
},
(err) => {
console.log("error signup: ", err);
if (statusLoading) {
this.utilsService.dismissLoading();
}
}
);
}
showWarning(stringName) {
this.utilsService.presentToast(3000, "warning", "top", this.translateService.instant(stringName));
}
validatedAddress(formAddress) {
if (!this.location.address) {
this.showWarning('ADDRESS_REQUIRED');
return;
}
this.createAddress(formAddress);
}
async alertNotCoverage(formAddress) {
const alert = await this.alertCtrl.create({
message: this.messageText.cityOutCoverage,
buttons: [
{
text: "Cancelar",
handler: () => { },
},
{
text: "Notificarme",
handler: () => {
this.storage.get("infoUser").then((infoUser) => {
if (infoUser) {
this.storage.get("token").then((token) => {
if (token) {
this.utilsService.presentLoading(this.translateService.instant("all.sending")).then(async () => {
let info = {
email: infoUser.email,
lat: this.coords.latitude ? this.coords.latitude : "",
lng: this.coords.longitude ? this.coords.longitude : "",
city_id: formAddress.controls.city.value,
};
(await this.addressProvider.saveCoveragePending(info, token.access_token)).subscribe((resp) => {
this.utilsService.dismissLoading();
if (resp["status"] == "success") {
this.utilsService.presentToast(3000, "success", "top", this.translateService.instant("SEND_COVERAGE_PENDING"));
}
}, (_) => this.utilsService.dismissLoading());
}).catch((_) => this.utilsService.dismissLoading());
}
});
}
});
},
},
],
});
await alert.present();
}
async alertGetLocation() {
const alert = await this.alertCtrl.create({
header: this.messageText.locationNotFunction,
buttons: [
{
text: "Obtener ubicación",
handler: () => {
this.getPositionUser();
},
},
],
});
await alert.present();
}
async alertAddressOutCoverage() {
const alert = await this.alertCtrl.create({
header: this.messageText.addressOutCoverage,
buttons: ["OK"],
});
await alert.present();
}
async alertAddressExist() {
const alert = await this.alertCtrl.create({
header: this.messageText.alreadyAddress,
buttons: ["OK"],
});
await alert.present();
}
async createAddress(formAddress) {
formAddress.value.latitude = this.location.lat;
formAddress.value.longitude = this.location.lng;
formAddress.value.coverage_id = this.coverage_id;
formAddress.value.address = this.location.address;
(await this.addressProvider.addAddressUser(formAddress.value, await this.utilsService.getAccessToken())).subscribe(
(resp) => {
this.storage.set("addressUser", resp["address"]);
this.utilsService.dismissLoading();
this.statusSendCreateAddress = false;
if (resp["status"] == "success") {
this.storage.get("infoUser").then((res) => {
let dataUser = res;
dataUser.addresses = resp["address"];
dataUser.user_info.is_initial = 0;
// se actualiza la informacion del usuario en el localstorage
this.storage.set("infoUser", dataUser);
this.utilsService.presentToast(
3000,
"success",
"top",
this.translateService.instant('SUCCESS_SAVE_LOCATION')
);
this.locationService.back();
});
} else if (resp["status"] == "already_address") {
this.alertAddressExist();
}
},
(err) => {
console.log("error signup: ", err);
this.utilsService.dismissLoading();
this.statusSendCreateAddress = false;
}
);
}
setLocation(location) {
this.location = location;
}
}