import { ActivatedRoute, Router } from "@angular/router"; import { Component, OnInit, NgZone, ViewChild } from "@angular/core"; import { Plant } from "src/app/models/plant"; import { Rate } from "src/app/models/rate"; import { PlantsService } from "src/app/services/plants.service"; import { OrganizationsService } from "src/app/services/organizations.service"; import { latLng, tileLayer, marker, Layer, icon, Map, latLngBounds, LatLng, point, } from "leaflet"; import { MatPaginator } from "@angular/material/paginator"; import { MatSort } from "@angular/material/sort"; import { MatTableDataSource } from "@angular/material/table"; import { AuthService } from "@app/services/auth2.service"; import { of as observableOf, Observable, throwError, from } from "rxjs"; import * as moment from "moment"; import Swal from "sweetalert2"; import { RatesService } from "@app/services/rates.service"; @Component({ selector: "app-dashboard", templateUrl: "./dashboard.component.html", styleUrls: ["./dashboard.component.scss"], }) export class DashboardComponent implements OnInit { title = "Dashboard"; listData: any; rows = []; markers: Layer[] = []; points: LatLng[] = []; listAssets: any; dataSource = new MatTableDataSource(this.listAssets); displayedColumns: string[] = ["name", "country", "city", "id"]; error: boolean; listOrganizations: any; plantId: string; plant: any; sub: any; plantNotFound: boolean; selectedPlant: any; meterKeys: any; meterKeys2: any; assetKeys: any; sumarize: number = 0; totalInstalled: number = 0; totalMetersInstalled: string; lastUpdate = new Date().toLocaleString(); i: number; // Leajflet map icon = icon({ iconSize: [25, 41], iconAnchor: [13, 41], iconUrl: "assets/img/marker-icon.png", //shadowUrl: 'marker-shadow.png' }); // Open Street Map definitions LAYER_OSM = tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { maxZoom: 18, attribution: "© OpenStreetMap contributors", }); // Values to bind to Leaflet Directive options = { layers: [this.LAYER_OSM], zoom: 10, center: latLng([13.661714, -89.25153]), }; @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator; @ViewChild(MatSort, { static: true }) sort: MatSort; userLevel: number; totalAssetsInstalled: any; rates: Rate = { distribuidora: "-", codigo_tarifa: "-", tarifa_actual: { dateMin: null, dateMax: null, cargo_energia: null, cargo_energia_b1: null, cargo_energia_b2: null, cargo_energia_b3: null, cargo_energia_punta: null, cargo_energia_resto: null, cargo_energia_valle: null, }, incremento_porcentaje: { cargo_energia: null, cargo_energia_b1: null, cargo_energia_b2: null, cargo_energia_b3: null, cargo_energia_punta: null, cargo_energia_resto: null, cargo_energia_valle: null, }, }; defaultRates: boolean; constructor( private plantsService: PlantsService, private route: ActivatedRoute, private orgService: OrganizationsService, private router: Router, private zone: NgZone, private authService: AuthService, private ratesService: RatesService ) { //DEMO this.userLevel = +this.authService.getUserLevel(); Swal.fire({ allowOutsideClick: false, type: "info", text: "Espere por favor...", }); Swal.showLoading(); this.plantsService.getAllAssets().subscribe( (res) => { if (res != null) { this.listAssets = res["data"]["assets"]; this.dataSource.data = this.listAssets; this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; this.assetKeys = Object.keys(this.listAssets); //DEMO if (this.userLevel == 0) { this.sumarize = 320; this.totalAssetsInstalled = 1; } else { this.totalAssetsInstalled = this.listAssets.length || 0; for (let prop in this.assetKeys) { this.meterKeys2 = Object.keys( this.listAssets.map((item) => item["meters_installed"])[prop] ); if (this.meterKeys2.length > 0) { for (let prop2 in this.meterKeys2) { this.sumarize += this.listAssets .map((item) => item["meters_installed"]) [prop].map((response) => response["installedCapacity_kW"])[ prop2 ]; //this.totalMetersInstalled = this.sumarize.toString(); //localStorage.setItem("installedCapacityTotal_kW", this.totalMetersInstalled); } } } } } setTimeout(() => { if (this.listAssets != undefined) { this.addMarkers(); this.sendPlantId(this.listAssets[0].id); } Swal.close(); }, 1800); }, (err) => { Swal.fire({ type: "error", title: "Error en el servidor", text: err.message, }); } ); } ngOnInit() { setTimeout(() => { Swal.close(); }, 3000); this.ratesService.getDefaultRate().subscribe((res) => { this.rates = res["data"]; this.defaultRates = true; }); var responsiveOptions: any[] = [ [ "screen and (max-width: 640px)", { seriesBarDistance: 5, axisX: { labelInterpolationFnc: function (value) { return value[0]; }, }, }, ], ]; } ngOnChanges(): void { if (this.listAssets != undefined) { this.addMarkers(); this.sendPlantId(this.listAssets[0].id); } } getAsset(id: string) { return observableOf(this.listAssets.find((e) => e.id === id)); } addMarkers() { let lat, long, address, name2; for (const plant of this.listAssets) { if (plant["meters_installed"].length > 0) { // DEMO if (this.userLevel == 0) { lat = "13.6613819"; long = "-89.2514334"; address = "Urbanización Madre Selva Calle Llama del Bosque, Edificio Avante, Local 4-5/4-6, Antiguo Cuscatlán"; name2 = "Inversiones MERELEC S.A de C.V"; } else { lat = plant["meters_installed"][0].gpsLat; long = plant["meters_installed"][0].gpsLong; address = plant.address; name2 = plant.name; } const newMarker = marker([lat, long], { icon: this.icon }) .bindPopup("" + name2 + "
Dirección: " + address) .on("click", () => { this.zone.run(() => { this.sendPlantId(plant.id); }); }); this.points.push(latLng([lat, long])); this.markers.push(newMarker); } } } sendPlantId(id: string) { this.plantId = id; // DEMO if (this.userLevel == 0) { this.selectedPlant = { name: "Inversiones MERELEC S.A de C.V", country: "El Salvador", city: "La Libertad", address: "Urbanización Madre Selva Calle Llama del Bosque, Edificio Avante, Local 4-5/4-6, Antiguo Cuscatlán", installedCapacity_kW: 300, }; this.totalInstalled = 320; } else { this.totalInstalled = 0; this.selectedPlant = this.listAssets.find((e) => e.id === this.plantId); let keys = Object.keys( this.selectedPlant.meters_installed.map( (item) => item["meters_installed"] ) ); for (let prop2 in keys) { this.totalInstalled += this.selectedPlant.meters_installed.map( (response) => response["installedCapacity_kW"] )[prop2]; } } } onMapReady(map: Map) { setTimeout(() => { map.invalidateSize(); }, 0); const bounds = latLngBounds(this.points); //map.fitBounds(bounds, { // padding: point(24, 24), // maxZoom: 9.5, // animate: true //}); } goToAsset(id: string) { this.router.navigate(["/assets"], { queryParams: { id: id } }); } }