1
|
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
|
2
|
import {FormArray, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
|
3
|
import {InsertUnit} from '../../../shared/api/endpoints/models/insert-unit';
|
4
|
import {InsertSensor} from '../../../shared/api/endpoints/models/insert-sensor';
|
5
|
import {Sensor} from '../../../shared/api/endpoints/models/sensor';
|
6
|
import {ManagementService} from '../../../shared/api/endpoints/services/management.service';
|
7
|
|
8
|
@Component({
|
9
|
selector: 'app-unit-insert-popup',
|
10
|
templateUrl: './unit-insert-popup.component.html',
|
11
|
styleUrls: ['./unit-insert-popup.component.scss']
|
12
|
})
|
13
|
export class UnitInsertPopupComponent implements OnInit {
|
14
|
|
15
|
insertForm: FormGroup;
|
16
|
items: FormArray;
|
17
|
|
18
|
|
19
|
@Input() phenomenons;
|
20
|
@Input() isVisible;
|
21
|
@Output() isVisibleChange: EventEmitter<boolean> = new EventEmitter<boolean>();
|
22
|
|
23
|
constructor(
|
24
|
private formBuilder: FormBuilder,
|
25
|
private managementService: ManagementService
|
26
|
) {
|
27
|
this.initForm();
|
28
|
}
|
29
|
|
30
|
ngOnInit(): void {
|
31
|
}
|
32
|
|
33
|
close() {
|
34
|
this.isVisibleChange.emit(false);
|
35
|
}
|
36
|
|
37
|
initForm() {
|
38
|
this.insertForm = this.formBuilder.group({
|
39
|
unitId: ['', [Validators.required]],
|
40
|
unitDescription: ['', Validators.required],
|
41
|
sensors: this.formBuilder.array([this.createSensor()])
|
42
|
});
|
43
|
}
|
44
|
|
45
|
createSensor(): FormGroup {
|
46
|
return this.formBuilder.group({
|
47
|
sensorId: '',
|
48
|
sensorName: '',
|
49
|
sensorType: '',
|
50
|
phenomenons: ['']
|
51
|
});
|
52
|
}
|
53
|
|
54
|
addSensor(): void {
|
55
|
this.items = this.insertForm.get('sensors') as FormArray;
|
56
|
this.items.push(this.createSensor());
|
57
|
}
|
58
|
|
59
|
clearFormArray() {
|
60
|
const frmArray = this.insertForm?.get('sensors') as FormArray;
|
61
|
if (frmArray) {
|
62
|
frmArray.clear();
|
63
|
}
|
64
|
this.addSensor();
|
65
|
this.insertForm.reset();
|
66
|
}
|
67
|
|
68
|
processInsertion() {
|
69
|
if (this.insertForm.valid) {
|
70
|
const unit: InsertUnit = {
|
71
|
unit_id: this.insertForm.controls.unitId.value,
|
72
|
description: this.insertForm.controls.unitDescription.value
|
73
|
};
|
74
|
const sensors: InsertSensor[] = [];
|
75
|
const frmArray = this.insertForm?.get('sensors') as FormArray;
|
76
|
|
77
|
frmArray.controls.forEach(control => {
|
78
|
const sensor: InsertSensor = {
|
79
|
sensor_id: control.get('sensorId').value,
|
80
|
sensor_name: control.get('sensorName').value,
|
81
|
sensor_type: control.get('sensorType').value,
|
82
|
phenomenon: {
|
83
|
phenomenon_id: control.get('phenomenons').value
|
84
|
},
|
85
|
}
|
86
|
console.log(sensor);
|
87
|
sensors.push(sensor);
|
88
|
});
|
89
|
|
90
|
this.managementService.insertUnit({ body: { unit, sensors}}).toPromise();
|
91
|
}
|
92
|
}
|
93
|
}
|