Untitled

mail@pastecode.io avatar
unknown
typescript
2 years ago
12 kB
2
Indexable
Never
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { NotificationService } from 'src/app/shared/services/notification.service';
import { GeofenceService } from '../../services/geofence.service';
import * as _ from 'lodash';
import * as moment from 'moment';
import { DateFormatUTCPipe } from 'src/app/shared/pipes/date-format-utc.pipe';
import { AppModule } from 'src/app/app.module';
@Component({
  selector: 'st-modal-geofence',
  templateUrl: './modal-geofence.component.html',
  styleUrls: ['./modal-geofence.component.scss']
})
export class ModalGeofenceComponent implements OnInit {

  @Input() nameModal: string = '';
  @Input() hideDetail: boolean = false;
  @Input() isEditModal: any;
  @Input() infoEdit: any;
  @Input() stateTown: any;

  showGeocedefence: boolean = true;

  public geofence: any = {
    id: null,
    poligonTypeId: null,
    poligonTypeDescription: null,
    name: "",
    description: null,
    area: null,
    attributes: null,
    idCalendar: null,
    calendarDescription: null,
    color: null,
    temporal: false,
    startDate: null,
    endDate: null
  }

  pointList: { lat: number; lng: number }[] = [];
  poligon: any;
  lat: any;
  lng: any;
  zoom: any = 8;
  isEdit: any = false;
  disableSelectOnEdit: any = false;
  isTemporalGeofence: any = false;
  iniDate: any;
  endDate: any;
  wDevice: boolean = true;
  device: any;
  caca: any;

  disabledAll: any;
  disabledTemporal: boolean = false;
  disabledEndDateTmp: boolean = false;

  @Output()
  public hideModal = new EventEmitter<any>();

  typePoligon = [
    { id: 1, description: "Poligono", status: true },
    { id: 2, description: "Circulo", status: true }
  ];

  constructor(public geofenceService: GeofenceService,
    private dateFormat: DateFormatUTCPipe,
    private message: NotificationService) { }

  ngOnInit(): void {
    if (this.stateTown) {
      this.message.warning('Solo puedes observar el mapa sin editar');
    }
    if (this.infoEdit.id) {
      this.assignFormData();
      this.isEdit = true;
      this.showGeocedefence = false;
      this.disableSelectOnEdit = true;
      this.poligon = this.generateGeofencePrintableCoords(this.infoEdit);
      this.zoom = 17;
      if (this.isTemporalGeofence) {
        this.disabledTemporal = true;
      }
    } else {
      this.assignDataCreate();
      this.lat = 19.405068;
      this.lng = -99.2155705;
      this.zoom = 5;
      this.isEdit = false;
      this.showGeocedefence = true;
    }

  }

  assignDataCreate() {
    this.geofence = {
      area: "",
      attributes: "",
      calendarDescription: "",
      color: "",
      description: "",
      id: 0,
      idCalendar: null,
      name: "",
      poligonTypeId: 0
    };
  }

  assignFormData() {
    this.geofence.startDate = '';
    this.geofence.endDate = '';
    this.geofence.id = this.infoEdit.id;
    this.geofence.poligonTypeId = this.infoEdit.poligonTypeId;
    this.geofence.poligonTypeDescription = this.infoEdit.poligonTypeDescription;
    this.geofence.name = this.infoEdit.name;
    this.geofence.description = this.infoEdit.description;
    this.geofence.area = this.infoEdit.area;
    this.geofence.attributes = this.infoEdit.attributes;
    this.geofence.idCalendar = this.infoEdit.idCalendar;
    this.geofence.calendarDescription = 0;
    this.geofence.color = this.infoEdit.color;
    this.geofence.startDate = this.dateFormat.transform(this.infoEdit.startDate, 'YYYY-MM-ddTHH:mm');
    this.geofence.endDate = this.dateFormat.transform(this.infoEdit.endDate, 'YYYY-MM-ddTHH:mm');
    this.isTemporalGeofence = this.infoEdit.temporal;
    this.iniDate = this.infoEdit.startDate;
    this.endDate = this.infoEdit.endDate;
    this.caca = this.geofence.startDate;
    this.disabledEndDateTmp = moment(new Date()).isAfter(moment(this.geofence.endDate));
  }

  onPoligonChange(event: any) {
    this.geofence.poligonTypeId = +event.target.value;
  }

  onColorChange(event: any) {
    this.geofence.color = event.target.value;
    if (this.poligon) {
      this.poligon.color = event.target.value;
    }
  }

  public cerrarModal() {
    this.hideModal.emit();
  }

  public fillArea(event: any) {
    this.pointList = event;
  }

  generateGeofencePrintableCoords(geofence: any): any {
    const dataString = this.cleanUpShapeData(geofence);
    if (geofence.poligonTypeDescription === 'Polígono') {
      this.generatePolygonData(geofence, dataString);
    } else if (geofence.poligonTypeDescription === 'Círculo') {
      this.generateCircleData(geofence, dataString);
    }
    return geofence;
  }

  cleanUpShapeData(geofence: any): string {
    geofence.paths = [];
    const regexStart = /\(*/gi;
    const regexEnd = /\)*/gi;
    const dataString = geofence.area.replace('POLYGON', '').replace('CIRCLE', '').replace(regexStart, '').replace(regexEnd, '').trim();
    return dataString;
  }

  generatePolygonData(geofence: any, dataString: any): void {
    const coords = dataString.trim().split(',');
    _.forEach(coords, pairCoords => {
      const XY = pairCoords.trim().split(' ');
      geofence.paths.push({ lat: Number(XY[0]), lng: Number(XY[1]) });
    });
    this.lat = geofence.paths[0].lat;
    this.lng = geofence.paths[0].lng;
  }

  generateCircleData(geofence: any, dataString: any): void {
    const XYZ = dataString.trim().replace(',', '').split(' ');
    geofence.latitude = Number(XYZ[0]);
    geofence.longitude = Number(XYZ[1]);
    geofence.radius = Number(XYZ[2]);
    this.lat = geofence.latitude;
    this.lng = geofence.longitude;
  }

  typeGraphicSelected(event: any) {
    this.geofence.poligonTypeId = (event == 'POLYGON') ? 1 : 2;
  }

  deviceAssigned(event: any) {
    this.device = event || null;
  }

  fillCircleData(event: any) {
    event.latlng && event.radius ? this.geofence.area = "CIRCLE(" + event.latlng.lat() + " " + event.latlng.lng() + ", " + event.radius + ")" : this.geofence.area = "";
  }

  activeTemporal(event: any) {
    if (!this.isEdit) {
      this.isTemporalGeofence = event.target.checked;
    }
  }

  onSubmit() {
    if (this.isTemporalGeofence) {
      this.validateDatesEditGeofenceTemporal(this.caca, this.endDate);
    } else {
      this.geofence.temporal = false;
      this.geofence.startDate = null;
      this.geofence.endDate = null;
      this.saveGeofence();
    }
  }

  validateDates(dateIni: any, dateEnd: any) {
    let date1: any = null;
    let date2 = null;
    let dataDay: any = null;
    if (!dateEnd || !dateEnd) {
      this.message.warning("Debe seleccionar fecha inicio y fecha fin.");
    } else {
      date1 = new Date(dateIni);
      date2 = new Date(dateEnd);
      dataDay = new Date();
      if (date2 <= date1) {
        this.message.warning("La fecha final no puede ser menor o igual a la fecha inicial.");
        return;
      } else if (Date.parse(date1) < Date.parse(dataDay)) {
        this.message.warning("La fecha inicial debe ser mayor o igual a la actual");
        return;
      }
      else {
        this.geofence.temporal = true;
        this.saveGeofence();
      }
    }
  }

  validateDatesEditGeofenceTemporal(dateIni: any, dateEnd: any) {
    let date1: any = null;
    let date2 = null;
    let dataDay: any = null;
    if (!dateEnd || !dateEnd) {
      this.message.warning("Debe seleccionar fecha inicio y fecha fin.");
    } else {
      date1 = new Date(dateIni);
      date2 = new Date(dateEnd);
      dataDay = new Date();
      if (date2 <= date1) {
        this.message.warning("La fecha final no puede ser menor o igual a la fecha inicial.");
        return;
      } else {
        this.geofence.temporal = true;
        this.saveGeofence();
      }
    }
  }

  saveGeofence() {
    this.validateForm()
  }

  private validateForm() {
    if (this.geofence.name.trim() == "" || this.geofence.poligonTypeId == 0) {
      if (this.geofence.name.trim() == "") { this.message.warning("No se puede agregar geocerca sin nombre"); return; }
      this.message.warning("Debes agregar todos los campos");
    } else {
      this.setForm()
    }
  }

  private setForm() {
    this.geofence.attributes = '{"color":"' + (this.geofence.color || '#000000') + '"}';
    if (!this.isEdit && this.geofence.poligonTypeId === 1 && this.pointList.length !== 0) {
      this.createPolygon();
      this.validateMapa();
    } else {
      this.validateUpdate();
    }
  }

  private validateUpdate() {
    if (this.isEdit && this.geofence.poligonTypeId === 1 && this.pointList.length !== 0) {
      this.createPolygon();
      this.updateGeofence();
    } else if (this.geofence.poligonTypeId === 2 && this.isEdit) {
      this.geofence.area === "" ? this.message.warning("Debe agregar una geocerca en el mapa") : this.updateGeofence();
    } else {
      this.validateMapa();
    }
  }

  private createPolygon() {
    var area = "";
    this.pointList.forEach(point => {
      area += point.lat + " " + point.lng + ",";
    });
    this.geofence.area = "POLYGON((" + area.substring(0, area.length - 1) + "))";
  }

  private validateMapa() {
    if (this.geofence.area === "") {
      this.message.warning("Debe agregar una geocerca en el mapa");
      return;
    }
    this.createGeofencence();
  }

  private createGeofencence() {
    if (this.isTemporalGeofence) {
      this.geofence.startDate = this.calcISODatetoStringIni(this.iniDate);
      this.geofence.endDate = this.calcISODatetoStringIni(this.endDate);
    }
    if (this.wDevice && this.device) this.geofence.deviceId = this.device;
    this.geofence.idCalendar = 0;
    const geo = this.clean(this.geofence)
    this.geofenceService.create(geo).subscribe(
      (response) => {
        if (response.codigo == 0) {
          this.message.succes("Geocerca creada correctamente");
          this.cerrarModal();
        } else {
          this.message.error("Error: " + response.mensaje);
        }
      },
      (error) => {
        if (error.status == 400) {
          this.message.warning("Favor de verificar campos: " + error.error.mensaje);
        } else {
          this.message.error("Error: " + error.error.mensaje);
        }
      }
    )
  }

  calcISODatetoStringIni(date: any) {
    var _date = moment(date);
    if (_date.isValid())
      return _date.toISOString().substring(0, 19);
    return undefined;
  }

  clean(obj: any) {
    for (const propName in obj) {
      if (obj[propName] === null || obj[propName] === undefined) {
        delete obj[propName];
      }
    }
    return obj
  }

  private updateGeofence() {
    this.geofence.endDate = this.endDate;
    this.geofence.starDate = this.iniDate;
    this.geofenceService.update({...this.geofence, endDate: this.infoEdit.endDate}).subscribe(
      (data) => {
        this.message.succes("Geocerca editada correctamente");
        this.cerrarModal();
      },
      (error) => {
        if (error.status == 400) {
          this.message.warning("Favor de verificar campos: " + error.error.mensaje);
        } else {
          this.message.error("No se puedo editar la geocerca, Contactar con Administrador");
        }
      }
    );
  }

  clearMap(id?: any) {
    this.disableSelectOnEdit = false;
    this.cleanDataGeofence(id);
    this.cleanDataPoligon();
  }

  cleanDataGeofence(id: any) {
    this.geofence = {
      ...this.geofence,
      // id: this.infoEdit?.id,
      // name: this.infoEdit ? this.infoEdit.name : this.geofence.name,
      // poligonTypeId: id ? id : 0,
      // color: this.infoEdit ? this.infoEdit.color : this.geofence.color,
      area: ""
    };
  }

  cleanDataPoligon() {
    this.poligon = {
      ...this.poligon,
      area: "",
      attributes: this.poligon.attributes,
      calendarDescription: this.poligon.calendarDescription,
      color: this.poligon.color,
      description: this.poligon.description,
      id: this.poligon.id,
      idCalendar: this.poligon.idCalendar,
      latitude: null,
      longitude: null,
      name: this.poligon.name,
      paths: [],
      poligonTypeDescription: this.poligon.poligonTypeDescription,
      poligonTypeId: 0,
      radius: null
    }
  }

  changeStatus(): void {
    this.wDevice = !this.wDevice;
  }
}