import { Component, EventEmitter, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'; import { MatChipListboxChange } from '@angular/material/chips'; import { IOption } from '../../interface/option.interface'; import { FormControl } from '@angular/forms'; import { AbmList } from '../../interface'; import { combineLatestWith, map, Observable, of, startWith } from 'rxjs'; @Component({ selector: 'kit-abm-chip-selector', templateUrl: './abm-chip-selector.component.html', }) export class AbmChipSelectorComponent implements OnInit, OnChanges { @Input() control!: FormControl; @Input() isFormDisabled: boolean = false; public filteredOptions$: Observable | undefined; private _abmListInput!: AbmList; multiple: boolean = false; public constructor() {} @Input() public set abmListInput(abmListInput: AbmList) { this._abmListInput = abmListInput; if (abmListInput && abmListInput.multiple !== undefined) { this.multiple = abmListInput.multiple; this.updateControlValueFormat(); } } public get abmListInput() { return this._abmListInput; } ngOnInit(): void { this.setFilterObservable(); } ngOnChanges(changes: SimpleChanges): void { if (changes['abmListInput']) { this.setFilterObservable(); } if (changes['multiple']) { this.updateControlValueFormat(); } } private updateControlValueFormat() { // Si cambia el modo multiple, ajustar el formato del valor del control if (this.multiple && this.control && !Array.isArray(this.control.value)) { // Convertir a array si el valor existe y no es ya un array this.control.setValue(this.control.value ? [this.control.value] : []); } else if (!this.multiple && this.control && Array.isArray(this.control.value)) { // Si cambia de mĂșltiple a simple, tomar el primer valor o null this.control.setValue(this.control.value.length > 0 ? this.control.value[0] : null); } } private setFilterObservable() { this.filteredOptions$ = this.control.valueChanges.pipe( startWith(this.control.value || ''), combineLatestWith(of(this._abmListInput?.values || [])), map(([selectedValue, optionslist]) => { // Siempre mostrar todas las opciones para el selector de chips return optionslist; }) ); } isSelected(optionValue: string): boolean { const currentValue = this.control.value; if (this.multiple && Array.isArray(currentValue)) { return currentValue.includes(optionValue); } return currentValue === optionValue; } onSelectionChange(event: MatChipListboxChange) { this.control.setValue(event.value); this.control.markAsDirty(); this.control.updateValueAndValidity(); } }