import {Component, Inject} from '@angular/core'; import {Observable, startWith} from "rxjs"; import {FormControl} from "@angular/forms"; import {HttpClient} from "@angular/common/http"; import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog"; import {ToastrService} from "ngx-toastr"; import {map} from "rxjs/operators"; @Component({ selector: 'app-add-clients-to-pxe', templateUrl: './add-clients-to-pxe.component.html', styleUrl: './add-clients-to-pxe.component.css' }) export class AddClientsToPxeComponent { baseUrl: string = import.meta.env.NG_APP_BASE_API_URL; clients: any[] = []; selectedClients: any[] = []; loading: boolean = true; filters: { [key: string]: string } = {}; filteredClients!: Observable; clientControl = new FormControl(); constructor( private http: HttpClient, public dialogRef: MatDialogRef, private toastService: ToastrService, @Inject(MAT_DIALOG_DATA) public data: { subnetUuid: string, subnetName: string } ) {} ngOnInit(): void { this.loading = true; this.loadClients(); this.filteredClients = this.clientControl.valueChanges.pipe( startWith(''), map(value => (typeof value === 'string' ? value : value?.name)), map(name => (name ? this._filterClients(name) : this.clients.slice())) ); } loadClients() { this.http.get( `${this.baseUrl}/clients?&page=1&itemsPerPage=10000&exists[template]=false`).subscribe( response => { this.clients = response['hydra:member']; this.loading = false; }, error => { console.error('Error fetching parent units:', error); this.loading = false; } ); } save() { const postData = { clients: this.selectedClients.map(client => client['@id']) }; this.http.post(`${this.baseUrl}/pxe-templates/${this.data.subnetUuid}/add-clients`, postData).subscribe( response => { this.toastService.success('Clientes asignados correctamente'); }, error => { this.toastService.error(error.error['hydra:description']); } ); this.dialogRef.close(this.selectedClients); } close() { this.dialogRef.close(); } removeClient(client: any) { const index = this.selectedClients.indexOf(client); if (index >= 0) { this.selectedClients.splice(index, 1); } } private _filterClients(name: string): any[] { const filterValue = name.toLowerCase(); return this.clients.filter(client => client.name.toLowerCase().includes(filterValue)); } displayFnClient(client: any): string { return client && client.name ? client.name : ''; } onOptionClientSelected(client: any) { if (!this.selectedClients.includes(client)) { this.selectedClients.push(client); } this.clientControl.setValue(''); } }