import * as i0 from '@angular/core';
import { EventEmitter, ContentChild, ViewChild, Input, Output, Inject, Optional, ChangeDetectionStrategy, Component } from '@angular/core';
import { debounceTime, switchMap, map, catchError, finalize, startWith } from 'rxjs/operators';
import * as i1 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i2 from '@angular/forms';
import { NgForm, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';
import * as i5 from '@angular/material/autocomplete';
import { MatAutocompleteModule, MatAutocompleteTrigger } from '@angular/material/autocomplete';
import { MatFormFieldModule } from '@angular/material/form-field';
import * as i6 from '@angular/material/icon';
import { MatIconModule } from '@angular/material/icon';
import * as i3 from '@angular/material/input';
import { MatInputModule } from '@angular/material/input';
import * as i7 from '@angular/material/progress-spinner';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import * as i4 from '@angular/material/tooltip';
import { MatTooltipModule } from '@angular/material/tooltip';
import { SdItemDefDefDirective, SdLabelDefDirective, SdViewDefDirective } from '@sd-angular/core/forms/directives';
import { SdFormControl, HandleSdCustomValidator, SD_FORM_CONFIGURATION } from '@sd-angular/core/forms/models';
import { ArrayUtilities, SdUtilities } from '@sd-angular/core/utilities/extensions';
import { BehaviorSubject, Subscription, combineLatest, of, defer, from } from 'rxjs';
import * as uuid from 'uuid';
import { SdLabel } from '@sd-angular/core/forms/label';
import { SdEmptyPipe } from '@sd-angular/core/pipes';

/* eslint-disable @angular-eslint/component-class-suffix */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @angular-eslint/no-input-rename */
class SdAutocompleteErrotStateMatcher {
    formControl;
    constructor(formControl) {
        this.formControl = formControl;
    }
    isErrorState(control, form) {
        const isSubmitted = form && form.submitted;
        return !!(this.formControl?.invalid && (this.formControl?.dirty || this.formControl?.touched || isSubmitted));
    }
}
class SdAutocomplete {
    ref;
    formConfig;
    id = `I${uuid.v4()}`;
    autoId;
    set _autoId(val) {
        if (!val) {
            return;
        }
        this.autoId = `forms-autocomplete-${val}`;
    }
    // @Input() set key(value: any) {
    //   this.#cache = {};
    //   this.#item = {};
    // }
    autocompleteTrigger;
    #model;
    #delay = 0; // Sau khoảng thời gian delay nếu không có thay đổi thì thì mới bắt đầu thực hiện gọi hàm
    #name = uuid.v4();
    set name(val) {
        if (val) {
            this.#name = val;
        }
    }
    appearance = 'outline';
    loading = false;
    inputControl = new SdFormControl();
    formControl = new SdFormControl();
    matcher = new SdAutocompleteErrotStateMatcher(this.formControl);
    size = 'md';
    #form;
    set form(val) {
        if (val) {
            if (val instanceof NgForm) {
                this.#form = val.form;
            }
            else {
                this.#form = val;
            }
        }
    }
    label;
    set _label(val) {
        this.label = val;
    }
    helperText;
    set _helperText(val) {
        this.helperText = val;
    }
    valueField;
    displayField;
    disabledField = '';
    placeholder;
    #itemsChanges = new BehaviorSubject([]);
    set items(items) {
        this.#delay = 0;
        // Mỗi lần items được set lại phải clear cache
        this.#cache = {};
        if (!items) {
            this.#itemsChanges.next([]);
        }
        else if (Array.isArray(items)) {
            this.#itemsChanges.next(items.filter(e => e !== null && e !== undefined));
        }
        else {
            this.#itemsChanges.next(items);
            this.#delay = 500;
        }
        this.formControl.updateValueAndValidity();
    }
    limit = 100;
    filteredItems;
    // Nếu items là 1 function gọi về server và có những tham số bên ngoài tác động đến kết quả trả về thì truyền thêm
    // Ví dụ: [cacheCheckSum]="{a: aValue, b: bValue}"
    cacheChecksum;
    controlPlaceHolder;
    set model(value) {
        if (this.#model !== value) {
            this.#model = value;
            this.formControl.setValue(value);
        }
    }
    addable = false;
    set _addable(addable) {
        this.addable = addable === '' || !!addable;
    }
    itemDef;
    sdLabelDef;
    modelChange = new EventEmitter();
    sdChange = new EventEmitter();
    sdSelection = new EventEmitter();
    sdAdd = new EventEmitter();
    // Optional
    set disabled(val) {
        val = val === '' || val || !!val;
        if (val) {
            this.inputControl.disable();
            this.formControl.disable();
        }
        else {
            this.inputControl.enable();
            this.formControl.enable();
        }
    }
    viewed = false;
    set _viewed(val) {
        this.viewed = val === '' || !!val;
    }
    hyperlink;
    required = false;
    set _required(val) {
        this.required = val === '' || !!val;
        this.#updateValidator();
    }
    #validator;
    set _validator(value) {
        this.#validator = value;
        this.#updateValidator();
    }
    inlineError;
    set _inlineError(val) {
        this.inlineError = val;
        this.#updateValidator();
    }
    hideInlineError = false;
    set _hideInlineError(val) {
        this.hideInlineError = val === '' || val;
        val = val === '' || val;
    }
    #subscription = new Subscription();
    input;
    sdViewDef;
    isFocused = false;
    selected;
    display;
    #cache = {};
    #item = {};
    isTyping = false;
    constructor(ref, formConfig) {
        this.ref = ref;
        this.formConfig = formConfig;
    }
    ngOnInit() {
        this.appearance = this.appearance || this.formConfig?.appearance;
        this.#subscription.add(this.inputControl.touchChanges.subscribe(() => {
            this.formControl.markAsTouched();
            this.ref.markForCheck();
        }));
        this.#subscription.add(this.formControl.sdChanges.subscribe(() => {
            this.ref.markForCheck();
        }));
        this.#subscription.add(this.inputControl.sdChanges.subscribe(() => {
            this.ref.markForCheck();
        }));
        this.#subscription.add(this.inputControl.valueChanges.subscribe(() => {
            this.isTyping = true;
        }));
        this.filteredItems = combineLatest([
            this.#itemsChanges.asObservable(),
            this.inputControl.valueChanges.pipe(debounceTime(this.#delay)),
        ]).pipe(switchMap(([items, searchText]) => {
            this.isTyping = false;
            searchText = searchText || '';
            if (typeof items !== 'function') {
                return of(ArrayUtilities.paging(ArrayUtilities.search(items, searchText, [this.valueField, this.displayField]), this.limit));
            }
            const key = SdUtilities.hash({
                checksum: this.cacheChecksum || null,
                searchText,
            });
            if (this.#cache[key] !== undefined) {
                this.isTyping = false;
                return of(this.#cache[key]);
            }
            let obs;
            const func = items({ type: 'SEARCH', searchText });
            if (func instanceof Promise) {
                obs = defer(() => from(func));
            }
            else {
                obs = func;
            }
            this.loading = true;
            this.ref.markForCheck();
            return obs.pipe(map(data => {
                this.#cache[key] = data || [];
                Object.assign(this.#item, ArrayUtilities.toObject(this.valueField, this.#cache[key]));
                return this.#cache[key];
            }), catchError(() => of([])), finalize(() => {
                this.loading = false;
                this.ref.markForCheck();
            }));
        }));
        this.selected = combineLatest([
            this.#itemsChanges.asObservable(),
            this.formControl.valueChanges.pipe(startWith(this.formControl.value)),
        ]).pipe(switchMap(([items]) => {
            // Vì một số lý do chưa xác định mà khi sử dụng sdViewDef thì khi chuyển sang dạng view sẽ trigger val = null
            // Nhưng formControl.value vẫn có giá trị đúng nên thực hiện gán val = this.formControl.value;
            const val = this.formControl.value;
            if (!this.valueField) {
                return of(val);
            }
            if (val || val === 0) {
                if (typeof items === 'function') {
                    if (this.#item[val]) {
                        return of(this.#item[val]);
                    }
                    let obs;
                    const func = items({ type: 'VALUE', value: val });
                    if (func instanceof Promise) {
                        obs = defer(() => from(func));
                    }
                    else {
                        obs = func;
                    }
                    return obs.pipe(map(data => {
                        Object.assign(this.#item, ArrayUtilities.toObject(this.valueField, data));
                        return (this.#item[val] || {
                            [this.valueField]: val,
                            [this.displayField]: val,
                        });
                    }), catchError(() => {
                        return of({
                            [this.valueField]: val,
                            [this.displayField]: val,
                        });
                    }), finalize(() => {
                        this.loading = false;
                        this.ref.markForCheck();
                    }));
                }
                return of(items.find((e) => e[this.valueField] === val));
            }
            return of('');
        }));
        this.controlPlaceHolder = this.selected.pipe(map((item) => {
            return item?.[this.displayField] ?? item ?? this.placeholder ?? (this.appearance ? this.label : '');
        }));
        this.display = this.selected.pipe(map((item) => {
            if (this.disabledField && typeof item === 'object' && !!item) {
                return item?.[this.disabledField] ?? '';
            }
            if (typeof item === 'string' || typeof item === 'number') {
                return item;
            }
            return '';
        }));
    }
    ngAfterViewInit() {
        this.#form?.addControl(this.#name, this.formControl);
    }
    ngOnDestroy() {
        this.#subscription.unsubscribe();
        this.#form?.removeControl(this.#name);
    }
    onSelect = (item) => {
        if (item) {
            if (typeof item === 'string' || typeof item === 'number') {
                if (this.formControl.value !== item) {
                    this.formControl.setValue(item);
                    this.modelChange.emit(item);
                    this.sdChange.emit(item);
                    this.sdSelection.emit({
                        values: [item],
                        selectedItems: [item],
                        value: item,
                        selectedItem: item,
                    });
                }
            }
            else if (this.valueField && this.displayField) {
                const val = item?.[this.valueField] || null;
                if (this.formControl.value !== val) {
                    this.formControl.setValue(val);
                    this.modelChange.emit(val);
                    this.sdChange.emit(val);
                    this.sdSelection.emit({
                        values: [val],
                        selectedItems: [item],
                        value: val,
                        selectedItem: item,
                    });
                }
            }
            this.inputControl.setValue('', {
                emitEvent: false,
            });
        }
    };
    onFocus = () => {
        this.isFocused = true;
        this.inputControl.setValue('');
        // this.inputControl.updateValueAndValidity();
    };
    onBlur = () => {
        this.isFocused = false;
        this.inputControl.setValue('', {
            emitEvent: false,
        });
    };
    onClick = () => {
        if (this.sdViewDef?.templateRef) {
            if (!this.formControl.disabled && !this.isFocused) {
                this.focus();
            }
        }
    };
    blur = () => {
        this.input?.nativeElement?.blur();
    };
    focus = () => {
        this.isFocused = true;
        setTimeout(() => {
            this.autocompleteTrigger?.openPanel();
            this.input?.nativeElement?.focus();
        }, 100);
    };
    clear = ($event) => {
        $event?.stopPropagation();
        this.inputControl?.setValue('');
        if (this.#model) {
            this.formControl.setValue(null);
            this.modelChange.emit(null);
            this.sdChange.emit(null);
            this.sdSelection.emit({
                values: [null],
                selectedItems: [],
                value: null,
                selectedItem: null,
            });
        }
    };
    onAdd = ($event) => {
        $event.stopPropagation();
        $event?.preventDefault();
        this.sdAdd.emit();
    };
    reValidate = () => {
        this.inputControl.updateValueAndValidity({ emitEvent: true });
    };
    #updateValidator = () => {
        this.formControl.clearValidators();
        this.formControl.clearAsyncValidators();
        const validators = [];
        const asyncValidators = [];
        // const asyncValidators: AsyncValidatorFn[] = [];
        if (this.required) {
            validators.push(Validators.required);
        }
        if (this.#validator) {
            asyncValidators.push(HandleSdCustomValidator(this.#validator));
        }
        if (this.inlineError) {
            validators.push(this.customInlineErrorValidator());
        }
        this.formControl.setValidators(validators);
        this.formControl.setAsyncValidators(asyncValidators);
        this.formControl.updateValueAndValidity();
    };
    // Hàm tạo Validators tùy chỉnh cho inlineError
    customInlineErrorValidator() {
        return () => {
            return { inlineError: true };
        };
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdAutocomplete, deps: [{ token: i0.ChangeDetectorRef }, { token: SD_FORM_CONFIGURATION, optional: true }], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.17", type: SdAutocomplete, isStandalone: true, selector: "sd-autocomplete", inputs: { _autoId: ["autoId", "_autoId"], name: "name", appearance: "appearance", size: "size", form: "form", _label: ["label", "_label"], _helperText: ["helperText", "_helperText"], valueField: "valueField", displayField: "displayField", disabledField: "disabledField", placeholder: "placeholder", items: "items", limit: "limit", cacheChecksum: "cacheChecksum", model: "model", _addable: ["addable", "_addable"], disabled: "disabled", _viewed: ["viewed", "_viewed"], hyperlink: "hyperlink", _required: ["required", "_required"], _validator: ["validator", "_validator"], _inlineError: ["inlineError", "_inlineError"], _hideInlineError: ["hideInlineError", "_hideInlineError"] }, outputs: { modelChange: "modelChange", sdChange: "sdChange", sdSelection: "sdSelection", sdAdd: "sdAdd" }, queries: [{ propertyName: "itemDef", first: true, predicate: SdItemDefDefDirective, descendants: true }, { propertyName: "sdLabelDef", first: true, predicate: SdLabelDefDirective, descendants: true }, { propertyName: "sdViewDef", first: true, predicate: SdViewDefDirective, descendants: true }], viewQueries: [{ propertyName: "autocompleteTrigger", first: true, predicate: MatAutocompleteTrigger, descendants: true, read: MatAutocompleteTrigger }, { propertyName: "input", first: true, predicate: ["input"], descendants: true }], ngImport: i0, template: "@if (viewed) {\r\n  @if (sdLabelDef?.templateRef) {\r\n    <ng-container *ngTemplateOutlet=\"sdLabelDef!.templateRef\"> </ng-container>\r\n  } @else if (label) {\r\n    <div class=\"T14R text-black400\">{{ label }}</div>\r\n  }\r\n  @if (hyperlink) {\r\n    <!-- N\u1EBFu c\u00F3 hyperlink th\u00EC d\u00F9ng th\u1EBB a -->\r\n    <a [href]=\"hyperlink\">{{ display | async }}</a>\r\n  } @else {\r\n    <!-- Ngo\u00E0i ra d\u00F9ng th\u1EBB m\u1EB7c \u0111\u1ECBnh -->\r\n    <div class=\"T14M\">{{ display | async | sdEmpty }}</div>\r\n  }\r\n} @else {\r\n  @if (!appearance && sdLabelDef?.templateRef) {\r\n    <ng-container *ngTemplateOutlet=\"sdLabelDef?.templateRef!\"> </ng-container>\r\n  }\r\n  @if (!appearance && label && !sdLabelDef?.templateRef) {\r\n    <sd-label [label]=\"label\" [required]=\"required\"></sd-label>\r\n  }\r\n  <div\r\n    class=\"d-flex align-items-center\"\r\n    [class.sd-view]=\"sdViewDef?.templateRef\"\r\n    [class.c-focused]=\"isFocused\"\r\n    [class.c-disabled]=\"formControl.disabled\"\r\n    (click)=\"onClick()\"\r\n    aria-hidden=\"true\">\r\n    @if (sdViewDef?.templateRef && !autocompleteTrigger?.panelOpen && !isFocused) {\r\n      <ng-container\r\n        *ngTemplateOutlet=\"\r\n          sdViewDef!.templateRef;\r\n          context: {\r\n            value: formControl.value,\r\n            selectedItem: selected | async,\r\n          }\r\n        \">\r\n      </ng-container>\r\n    } @else {\r\n      <mat-form-field\r\n        [class.sd-md]=\"size === 'md'\"\r\n        [class.sd-sm]=\"size === 'sm'\"\r\n        [class.hide-inline-error]=\"hideInlineError\"\r\n        [floatLabel]=\"formControl.value ? 'always' : 'auto'\"\r\n        [appearance]=\"appearance || 'outline'\">\r\n        @if (appearance && label) {\r\n          <mat-label style=\"display: inline-block\">\r\n            <div style=\"display: flex; align-items: center; gap: 4px\">\r\n              <span>{{ label }}</span>\r\n              @if (helperText) {\r\n                <mat-icon [matTooltip]=\"helperText\" matTooltipPosition=\"below\">info_outline</mat-icon>\r\n              }\r\n            </div>\r\n          </mat-label>\r\n        }\r\n        <input\r\n          [id]=\"id\"\r\n          [formControl]=\"inputControl\"\r\n          [placeholder]=\"(controlPlaceHolder | async) || ''\"\r\n          [class.c-selected]=\"formControl.value\"\r\n          [matAutocomplete]=\"auto\"\r\n          (focus)=\"onFocus()\"\r\n          (blur)=\"onBlur()\"\r\n          matInput\r\n          [autocomplete]=\"id\"\r\n          autocorrect=\"off\"\r\n          [errorStateMatcher]=\"matcher\"\r\n          [required]=\"required\"\r\n          #input\r\n          #autocompleteTrigger\r\n          [attr.data-autoId]=\"autoId\"\r\n          aria-hidden=\"true\" />\r\n        @if (!loading && formControl.value && !inputControl.disabled) {\r\n          <mat-icon class=\"pointer sd-suffix-icon\" (click)=\"clear($event)\" matSuffix>cancel</mat-icon>\r\n        } @else if (loading) {\r\n          <mat-spinner [diameter]=\"20\" matSuffix></mat-spinner>\r\n        } @else {\r\n          <mat-icon class=\"pointer sd-suffix-icon\" matSuffix>search</mat-icon>\r\n        }\r\n        <!-- <i [class.d-none]=\"!loading\" class=\"fa fa-spinner fa-pulse c-loading-icon\"></i> -->\r\n        <mat-autocomplete #auto=\"matAutocomplete\" (optionSelected)=\"onSelect($event.option.value)\" class=\"sd-autocomplete-panel\">\r\n          @let items = filteredItems | async;\r\n          @if (items?.length) {\r\n            <mat-option\r\n              *ngFor=\"let item of items\"\r\n              [value]=\"item\"\r\n              matTooltipPosition=\"above\"\r\n              [matTooltip]=\"displayField ? item[displayField] : item\"\r\n              [disabled]=\"item[disabledField]\">\r\n              <ng-container *ngIf=\"itemDef?.templateRef\">\r\n                <ng-container *ngTemplateOutlet=\"itemDef?.templateRef ?? null; context: { item: item }\"> </ng-container>\r\n              </ng-container>\r\n              <ng-container *ngIf=\"!itemDef?.templateRef\">\r\n                {{ displayField ? item[displayField] : item }}\r\n              </ng-container>\r\n            </mat-option>\r\n          } @else if (!items?.length && inputControl.value && !isTyping && !loading) {}\r\n          @if (addable && sdAdd.observers.length) {\r\n            <mat-option class=\"sd__option--add\" (keyup.Space)=\"$event.stopPropagation()\" disabled=\"true\">\r\n              <div (click)=\"onAdd($event)\">\r\n                <mat-icon class=\"mr-1\">add</mat-icon>\r\n                {{ 'New item' }}\r\n              </div>\r\n            </mat-option>\r\n          }\r\n        </mat-autocomplete>\r\n        @if (formControl.errors?.['required']) {\r\n          <mat-error>\r\n            @if (!hideInlineError) {\r\n              Vui l\u00F2ng nh\u1EADp th\u00F4ng tin\r\n            }\r\n          </mat-error>\r\n        }\r\n        @if (formControl.errors?.['customValidator']) {\r\n          <mat-error>\r\n            @if (!hideInlineError) {\r\n              {{ formControl.errors?.['customValidator'] }}\r\n            }\r\n          </mat-error>\r\n        }\r\n      </mat-form-field>\r\n    }\r\n  </div>\r\n}\r\n", styles: [".text-primary{color:var(--sd-primary)!important}.bg-primary{background:var(--sd-primary)!important}.border-primary{border-color:var(--sd-primary)!important}.text-primary-light{color:var(--sd-primary-light)!important}.bg-primary-light{background:var(--sd-primary-light)!important}.border-primary-light{border-color:var(--sd-primary-light)!important}.text-primary-dark{color:var(--sd-primary-dark)!important}.bg-primary-dark{background:var(--sd-primary-dark)!important}.border-primary-dark{border-color:var(--sd-primary-dark)!important}.text-info{color:var(--sd-info)!important}.bg-info{background:var(--sd-info)!important}.border-info{border-color:var(--sd-info)!important}.text-info-light{color:var(--sd-info-light)!important}.bg-info-light{background:var(--sd-info-light)!important}.border-info-light{border-color:var(--sd-info-light)!important}.text-info-dark{color:var(--sd-info-dark)!important}.bg-info-dark{background:var(--sd-info-dark)!important}.border-info-dark{border-color:var(--sd-info-dark)!important}.text-success{color:var(--sd-success)!important}.bg-success{background:var(--sd-success)!important}.border-success{border-color:var(--sd-success)!important}.text-success-light{color:var(--sd-success-light)!important}.bg-success-light{background:var(--sd-success-light)!important}.border-success-light{border-color:var(--sd-success-light)!important}.text-success-dark{color:var(--sd-success-dark)!important}.bg-success-dark{background:var(--sd-success-dark)!important}.border-success-dark{border-color:var(--sd-success-dark)!important}.text-warning{color:var(--sd-warning)!important}.bg-warning{background:var(--sd-warning)!important}.border-warning{border-color:var(--sd-warning)!important}.text-warning-light{color:var(--sd-warning-light)!important}.bg-warning-light{background:var(--sd-warning-light)!important}.border-warning-light{border-color:var(--sd-warning-light)!important}.text-warning-dark{color:var(--sd-warning-dark)!important}.bg-warning-dark{background:var(--sd-warning-dark)!important}.border-warning-dark{border-color:var(--sd-warning-dark)!important}.text-error{color:var(--sd-error)!important}.bg-error{background:var(--sd-error)!important}.border-error{border-color:var(--sd-error)!important}.text-error-light{color:var(--sd-error-light)!important}.bg-error-light{background:var(--sd-error-light)!important}.border-error-light{border-color:var(--sd-error-light)!important}.text-error-dark{color:var(--sd-error-dark)!important}.bg-error-dark{background:var(--sd-error-dark)!important}.border-error-dark{border-color:var(--sd-error-dark)!important}.text-secondary{color:var(--sd-secondary)!important}.bg-secondary{background:var(--sd-secondary)!important}.border-secondary{border-color:var(--sd-secondary)!important}.text-secondary-light{color:var(--sd-secondary-light)!important}.bg-secondary-light{background:var(--sd-secondary-light)!important}.border-secondary-light{border-color:var(--sd-secondary-light)!important}.text-secondary-dark{color:var(--sd-secondary-dark)!important}.bg-secondary-dark{background:var(--sd-secondary-dark)!important}.border-secondary-dark{border-color:var(--sd-secondary-dark)!important}.text-light{color:var(--sd-light)!important}.bg-light{background:var(--sd-light)!important}.border-light{border-color:var(--sd-light)!important}.text-dark{color:var(--sd-dark)!important}.bg-dark{background:var(--sd-dark)!important}.border-dark{border-color:var(--sd-dark)!important}.text-black500{color:var(--sd-black500)!important}.bg-black500{background:var(--sd-black500)!important}.border-black500{border-color:var(--sd-black500)!important}.text-black400{color:var(--sd-black400)!important}.bg-black400{background:var(--sd-black400)!important}.border-black400{border-color:var(--sd-black400)!important}.text-black300{color:var(--sd-black300)!important}.bg-black300{background:var(--sd-black300)!important}.border-black300{border-color:var(--sd-black300)!important}.text-black200{color:var(--sd-black200)!important}.bg-black200{background:var(--sd-black200)!important}.border-black200{border-color:var(--sd-black200)!important}.text-black100{color:var(--sd-black100)!important}.bg-black100{background:var(--sd-black100)!important}.border-black100{border-color:var(--sd-black100)!important}.text-white{color:#fff!important}.bg-white{background:#fff!important}.border-white{border-color:#fff!important}.text-black{color:#000!important}.bg-black{background:#000!important}.border-black{border-color:#000!important}:host{padding-top:5px;display:block}:host ::ng-deep .mat-mdc-form-field.mat-form-field-appearance-outline.mat-form-field-disabled .mat-mdc-text-field-wrapper{background:var(--sd-black100)}:host ::ng-deep .mat-mdc-form-field input.c-selected::placeholder{color:#000;opacity:1}:host ::ng-deep .mat-mdc-form-field input.c-selected:-ms-input-placeholder{color:#000}:host ::ng-deep .mat-mdc-form-field input.c-selected::-ms-input-placeholder{color:#000}:host ::ng-deep .mat-mdc-form-field input.mat-mdc-input-element:disabled{color:var(--sd-black400)!important}:host ::ng-deep .mat-mdc-form-field input.mat-mdc-input-element:disabled.c-selected::placeholder{color:var(--sd-black400)!important}:host ::ng-deep .mat-mdc-form-field input.mat-mdc-input-element:disabled.c-selected:-ms-input-placeholder{color:var(--sd-black400)!important}:host ::ng-deep .mat-mdc-form-field input.mat-mdc-input-element:disabled.c-selected::-ms-input-placeholder{color:var(--sd-black400)!important}:host ::ng-deep .mat-mdc-form-field .mat-mdc-placeholder-required{color:var(--sd-error)}:host ::ng-deep .mat-mdc-form-field:hover .icon-copy{opacity:1}:host ::ng-deep .mat-mdc-form-field .icon-copy{cursor:pointer;width:.9em;height:.9em;fill:#00000080;transition:opacity .2s linear;opacity:0}::ng-deep .sd-autocomplete-panel .mat-mdc-option{min-height:36px!important;height:36px!important;padding-left:12px!important;padding-right:12px!important}::ng-deep .sd-autocomplete-panel .mdc-list-item__primary-text{font-size:14px!important;line-height:normal}::ng-deep .sd-autocomplete-panel .mat-pseudo-checkbox{transform:scale(.75);margin-right:8px!important}.sd-view:not(.c-focused):not(.c-disabled):hover{background-color:#ebecf0}.sd__option--add{position:sticky;bottom:0;background-color:#fff;z-index:10;color:#000000de;cursor:pointer!important}.c-loading-icon{position:absolute;right:5px;top:5px}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "pipe", type: i1.AsyncPipe, name: "async" }, { kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i2.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i2.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i2.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "ngmodule", type: MatInputModule }, { kind: "directive", type: i3.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl],      input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly", "disabledInteractive"], exportAs: ["matInput"] }, { kind: "component", type: i3.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i3.MatLabel, selector: "mat-label" }, { kind: "directive", type: i3.MatError, selector: "mat-error, [matError]", inputs: ["id"] }, { kind: "directive", type: i3.MatSuffix, selector: "[matSuffix], [matIconSuffix], [matTextSuffix]", inputs: ["matTextSuffix"] }, { kind: "ngmodule", type: MatTooltipModule }, { kind: "directive", type: i4.MatTooltip, selector: "[matTooltip]", inputs: ["matTooltipPosition", "matTooltipPositionAtOrigin", "matTooltipDisabled", "matTooltipShowDelay", "matTooltipHideDelay", "matTooltipTouchGestures", "matTooltip", "matTooltipClass"], exportAs: ["matTooltip"] }, { kind: "ngmodule", type: MatFormFieldModule }, { kind: "ngmodule", type: MatAutocompleteModule }, { kind: "component", type: i5.MatAutocomplete, selector: "mat-autocomplete", inputs: ["aria-label", "aria-labelledby", "displayWith", "autoActiveFirstOption", "autoSelectActiveOption", "requireSelection", "panelWidth", "disableRipple", "class", "hideSingleSelectionIndicator"], outputs: ["optionSelected", "opened", "closed", "optionActivated"], exportAs: ["matAutocomplete"] }, { kind: "component", type: i5.MatOption, selector: "mat-option", inputs: ["value", "id", "disabled"], outputs: ["onSelectionChange"], exportAs: ["matOption"] }, { kind: "directive", type: i5.MatAutocompleteTrigger, selector: "input[matAutocomplete], textarea[matAutocomplete]", inputs: ["matAutocomplete", "matAutocompletePosition", "matAutocompleteConnectedTo", "autocomplete", "matAutocompleteDisabled"], exportAs: ["matAutocompleteTrigger"] }, { kind: "ngmodule", type: MatIconModule }, { kind: "component", type: i6.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "ngmodule", type: MatProgressSpinnerModule }, { kind: "component", type: i7.MatProgressSpinner, selector: "mat-progress-spinner, mat-spinner", inputs: ["color", "mode", "value", "diameter", "strokeWidth"], exportAs: ["matProgressSpinner"] }, { kind: "component", type: SdLabel, selector: "sd-label", inputs: ["label", "description", "required", "helperText"] }, { kind: "pipe", type: SdEmptyPipe, name: "sdEmpty" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdAutocomplete, decorators: [{
            type: Component,
            args: [{ selector: 'sd-autocomplete', changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [
                        CommonModule,
                        FormsModule,
                        ReactiveFormsModule,
                        MatInputModule,
                        MatTooltipModule,
                        MatFormFieldModule,
                        MatAutocompleteModule,
                        MatIconModule,
                        MatProgressSpinnerModule,
                        SdLabel,
                        SdEmptyPipe
                    ], template: "@if (viewed) {\r\n  @if (sdLabelDef?.templateRef) {\r\n    <ng-container *ngTemplateOutlet=\"sdLabelDef!.templateRef\"> </ng-container>\r\n  } @else if (label) {\r\n    <div class=\"T14R text-black400\">{{ label }}</div>\r\n  }\r\n  @if (hyperlink) {\r\n    <!-- N\u1EBFu c\u00F3 hyperlink th\u00EC d\u00F9ng th\u1EBB a -->\r\n    <a [href]=\"hyperlink\">{{ display | async }}</a>\r\n  } @else {\r\n    <!-- Ngo\u00E0i ra d\u00F9ng th\u1EBB m\u1EB7c \u0111\u1ECBnh -->\r\n    <div class=\"T14M\">{{ display | async | sdEmpty }}</div>\r\n  }\r\n} @else {\r\n  @if (!appearance && sdLabelDef?.templateRef) {\r\n    <ng-container *ngTemplateOutlet=\"sdLabelDef?.templateRef!\"> </ng-container>\r\n  }\r\n  @if (!appearance && label && !sdLabelDef?.templateRef) {\r\n    <sd-label [label]=\"label\" [required]=\"required\"></sd-label>\r\n  }\r\n  <div\r\n    class=\"d-flex align-items-center\"\r\n    [class.sd-view]=\"sdViewDef?.templateRef\"\r\n    [class.c-focused]=\"isFocused\"\r\n    [class.c-disabled]=\"formControl.disabled\"\r\n    (click)=\"onClick()\"\r\n    aria-hidden=\"true\">\r\n    @if (sdViewDef?.templateRef && !autocompleteTrigger?.panelOpen && !isFocused) {\r\n      <ng-container\r\n        *ngTemplateOutlet=\"\r\n          sdViewDef!.templateRef;\r\n          context: {\r\n            value: formControl.value,\r\n            selectedItem: selected | async,\r\n          }\r\n        \">\r\n      </ng-container>\r\n    } @else {\r\n      <mat-form-field\r\n        [class.sd-md]=\"size === 'md'\"\r\n        [class.sd-sm]=\"size === 'sm'\"\r\n        [class.hide-inline-error]=\"hideInlineError\"\r\n        [floatLabel]=\"formControl.value ? 'always' : 'auto'\"\r\n        [appearance]=\"appearance || 'outline'\">\r\n        @if (appearance && label) {\r\n          <mat-label style=\"display: inline-block\">\r\n            <div style=\"display: flex; align-items: center; gap: 4px\">\r\n              <span>{{ label }}</span>\r\n              @if (helperText) {\r\n                <mat-icon [matTooltip]=\"helperText\" matTooltipPosition=\"below\">info_outline</mat-icon>\r\n              }\r\n            </div>\r\n          </mat-label>\r\n        }\r\n        <input\r\n          [id]=\"id\"\r\n          [formControl]=\"inputControl\"\r\n          [placeholder]=\"(controlPlaceHolder | async) || ''\"\r\n          [class.c-selected]=\"formControl.value\"\r\n          [matAutocomplete]=\"auto\"\r\n          (focus)=\"onFocus()\"\r\n          (blur)=\"onBlur()\"\r\n          matInput\r\n          [autocomplete]=\"id\"\r\n          autocorrect=\"off\"\r\n          [errorStateMatcher]=\"matcher\"\r\n          [required]=\"required\"\r\n          #input\r\n          #autocompleteTrigger\r\n          [attr.data-autoId]=\"autoId\"\r\n          aria-hidden=\"true\" />\r\n        @if (!loading && formControl.value && !inputControl.disabled) {\r\n          <mat-icon class=\"pointer sd-suffix-icon\" (click)=\"clear($event)\" matSuffix>cancel</mat-icon>\r\n        } @else if (loading) {\r\n          <mat-spinner [diameter]=\"20\" matSuffix></mat-spinner>\r\n        } @else {\r\n          <mat-icon class=\"pointer sd-suffix-icon\" matSuffix>search</mat-icon>\r\n        }\r\n        <!-- <i [class.d-none]=\"!loading\" class=\"fa fa-spinner fa-pulse c-loading-icon\"></i> -->\r\n        <mat-autocomplete #auto=\"matAutocomplete\" (optionSelected)=\"onSelect($event.option.value)\" class=\"sd-autocomplete-panel\">\r\n          @let items = filteredItems | async;\r\n          @if (items?.length) {\r\n            <mat-option\r\n              *ngFor=\"let item of items\"\r\n              [value]=\"item\"\r\n              matTooltipPosition=\"above\"\r\n              [matTooltip]=\"displayField ? item[displayField] : item\"\r\n              [disabled]=\"item[disabledField]\">\r\n              <ng-container *ngIf=\"itemDef?.templateRef\">\r\n                <ng-container *ngTemplateOutlet=\"itemDef?.templateRef ?? null; context: { item: item }\"> </ng-container>\r\n              </ng-container>\r\n              <ng-container *ngIf=\"!itemDef?.templateRef\">\r\n                {{ displayField ? item[displayField] : item }}\r\n              </ng-container>\r\n            </mat-option>\r\n          } @else if (!items?.length && inputControl.value && !isTyping && !loading) {}\r\n          @if (addable && sdAdd.observers.length) {\r\n            <mat-option class=\"sd__option--add\" (keyup.Space)=\"$event.stopPropagation()\" disabled=\"true\">\r\n              <div (click)=\"onAdd($event)\">\r\n                <mat-icon class=\"mr-1\">add</mat-icon>\r\n                {{ 'New item' }}\r\n              </div>\r\n            </mat-option>\r\n          }\r\n        </mat-autocomplete>\r\n        @if (formControl.errors?.['required']) {\r\n          <mat-error>\r\n            @if (!hideInlineError) {\r\n              Vui l\u00F2ng nh\u1EADp th\u00F4ng tin\r\n            }\r\n          </mat-error>\r\n        }\r\n        @if (formControl.errors?.['customValidator']) {\r\n          <mat-error>\r\n            @if (!hideInlineError) {\r\n              {{ formControl.errors?.['customValidator'] }}\r\n            }\r\n          </mat-error>\r\n        }\r\n      </mat-form-field>\r\n    }\r\n  </div>\r\n}\r\n", styles: [".text-primary{color:var(--sd-primary)!important}.bg-primary{background:var(--sd-primary)!important}.border-primary{border-color:var(--sd-primary)!important}.text-primary-light{color:var(--sd-primary-light)!important}.bg-primary-light{background:var(--sd-primary-light)!important}.border-primary-light{border-color:var(--sd-primary-light)!important}.text-primary-dark{color:var(--sd-primary-dark)!important}.bg-primary-dark{background:var(--sd-primary-dark)!important}.border-primary-dark{border-color:var(--sd-primary-dark)!important}.text-info{color:var(--sd-info)!important}.bg-info{background:var(--sd-info)!important}.border-info{border-color:var(--sd-info)!important}.text-info-light{color:var(--sd-info-light)!important}.bg-info-light{background:var(--sd-info-light)!important}.border-info-light{border-color:var(--sd-info-light)!important}.text-info-dark{color:var(--sd-info-dark)!important}.bg-info-dark{background:var(--sd-info-dark)!important}.border-info-dark{border-color:var(--sd-info-dark)!important}.text-success{color:var(--sd-success)!important}.bg-success{background:var(--sd-success)!important}.border-success{border-color:var(--sd-success)!important}.text-success-light{color:var(--sd-success-light)!important}.bg-success-light{background:var(--sd-success-light)!important}.border-success-light{border-color:var(--sd-success-light)!important}.text-success-dark{color:var(--sd-success-dark)!important}.bg-success-dark{background:var(--sd-success-dark)!important}.border-success-dark{border-color:var(--sd-success-dark)!important}.text-warning{color:var(--sd-warning)!important}.bg-warning{background:var(--sd-warning)!important}.border-warning{border-color:var(--sd-warning)!important}.text-warning-light{color:var(--sd-warning-light)!important}.bg-warning-light{background:var(--sd-warning-light)!important}.border-warning-light{border-color:var(--sd-warning-light)!important}.text-warning-dark{color:var(--sd-warning-dark)!important}.bg-warning-dark{background:var(--sd-warning-dark)!important}.border-warning-dark{border-color:var(--sd-warning-dark)!important}.text-error{color:var(--sd-error)!important}.bg-error{background:var(--sd-error)!important}.border-error{border-color:var(--sd-error)!important}.text-error-light{color:var(--sd-error-light)!important}.bg-error-light{background:var(--sd-error-light)!important}.border-error-light{border-color:var(--sd-error-light)!important}.text-error-dark{color:var(--sd-error-dark)!important}.bg-error-dark{background:var(--sd-error-dark)!important}.border-error-dark{border-color:var(--sd-error-dark)!important}.text-secondary{color:var(--sd-secondary)!important}.bg-secondary{background:var(--sd-secondary)!important}.border-secondary{border-color:var(--sd-secondary)!important}.text-secondary-light{color:var(--sd-secondary-light)!important}.bg-secondary-light{background:var(--sd-secondary-light)!important}.border-secondary-light{border-color:var(--sd-secondary-light)!important}.text-secondary-dark{color:var(--sd-secondary-dark)!important}.bg-secondary-dark{background:var(--sd-secondary-dark)!important}.border-secondary-dark{border-color:var(--sd-secondary-dark)!important}.text-light{color:var(--sd-light)!important}.bg-light{background:var(--sd-light)!important}.border-light{border-color:var(--sd-light)!important}.text-dark{color:var(--sd-dark)!important}.bg-dark{background:var(--sd-dark)!important}.border-dark{border-color:var(--sd-dark)!important}.text-black500{color:var(--sd-black500)!important}.bg-black500{background:var(--sd-black500)!important}.border-black500{border-color:var(--sd-black500)!important}.text-black400{color:var(--sd-black400)!important}.bg-black400{background:var(--sd-black400)!important}.border-black400{border-color:var(--sd-black400)!important}.text-black300{color:var(--sd-black300)!important}.bg-black300{background:var(--sd-black300)!important}.border-black300{border-color:var(--sd-black300)!important}.text-black200{color:var(--sd-black200)!important}.bg-black200{background:var(--sd-black200)!important}.border-black200{border-color:var(--sd-black200)!important}.text-black100{color:var(--sd-black100)!important}.bg-black100{background:var(--sd-black100)!important}.border-black100{border-color:var(--sd-black100)!important}.text-white{color:#fff!important}.bg-white{background:#fff!important}.border-white{border-color:#fff!important}.text-black{color:#000!important}.bg-black{background:#000!important}.border-black{border-color:#000!important}:host{padding-top:5px;display:block}:host ::ng-deep .mat-mdc-form-field.mat-form-field-appearance-outline.mat-form-field-disabled .mat-mdc-text-field-wrapper{background:var(--sd-black100)}:host ::ng-deep .mat-mdc-form-field input.c-selected::placeholder{color:#000;opacity:1}:host ::ng-deep .mat-mdc-form-field input.c-selected:-ms-input-placeholder{color:#000}:host ::ng-deep .mat-mdc-form-field input.c-selected::-ms-input-placeholder{color:#000}:host ::ng-deep .mat-mdc-form-field input.mat-mdc-input-element:disabled{color:var(--sd-black400)!important}:host ::ng-deep .mat-mdc-form-field input.mat-mdc-input-element:disabled.c-selected::placeholder{color:var(--sd-black400)!important}:host ::ng-deep .mat-mdc-form-field input.mat-mdc-input-element:disabled.c-selected:-ms-input-placeholder{color:var(--sd-black400)!important}:host ::ng-deep .mat-mdc-form-field input.mat-mdc-input-element:disabled.c-selected::-ms-input-placeholder{color:var(--sd-black400)!important}:host ::ng-deep .mat-mdc-form-field .mat-mdc-placeholder-required{color:var(--sd-error)}:host ::ng-deep .mat-mdc-form-field:hover .icon-copy{opacity:1}:host ::ng-deep .mat-mdc-form-field .icon-copy{cursor:pointer;width:.9em;height:.9em;fill:#00000080;transition:opacity .2s linear;opacity:0}::ng-deep .sd-autocomplete-panel .mat-mdc-option{min-height:36px!important;height:36px!important;padding-left:12px!important;padding-right:12px!important}::ng-deep .sd-autocomplete-panel .mdc-list-item__primary-text{font-size:14px!important;line-height:normal}::ng-deep .sd-autocomplete-panel .mat-pseudo-checkbox{transform:scale(.75);margin-right:8px!important}.sd-view:not(.c-focused):not(.c-disabled):hover{background-color:#ebecf0}.sd__option--add{position:sticky;bottom:0;background-color:#fff;z-index:10;color:#000000de;cursor:pointer!important}.c-loading-icon{position:absolute;right:5px;top:5px}\n"] }]
        }], ctorParameters: () => [{ type: i0.ChangeDetectorRef }, { type: undefined, decorators: [{
                    type: Inject,
                    args: [SD_FORM_CONFIGURATION]
                }, {
                    type: Optional
                }] }], propDecorators: { _autoId: [{
                type: Input,
                args: ['autoId']
            }], autocompleteTrigger: [{
                type: ViewChild,
                args: [MatAutocompleteTrigger, { read: MatAutocompleteTrigger }]
            }], name: [{
                type: Input
            }], appearance: [{
                type: Input
            }], size: [{
                type: Input
            }], form: [{
                type: Input
            }], _label: [{
                type: Input,
                args: ['label']
            }], _helperText: [{
                type: Input,
                args: ['helperText']
            }], valueField: [{
                type: Input
            }], displayField: [{
                type: Input
            }], disabledField: [{
                type: Input
            }], placeholder: [{
                type: Input
            }], items: [{
                type: Input
            }], limit: [{
                type: Input
            }], cacheChecksum: [{
                type: Input
            }], model: [{
                type: Input
            }], _addable: [{
                type: Input,
                args: ['addable']
            }], itemDef: [{
                type: ContentChild,
                args: [SdItemDefDefDirective]
            }], sdLabelDef: [{
                type: ContentChild,
                args: [SdLabelDefDirective]
            }], modelChange: [{
                type: Output
            }], sdChange: [{
                type: Output
            }], sdSelection: [{
                type: Output
            }], sdAdd: [{
                type: Output
            }], disabled: [{
                type: Input
            }], _viewed: [{
                type: Input,
                args: ['viewed']
            }], hyperlink: [{
                type: Input
            }], _required: [{
                type: Input,
                args: ['required']
            }], _validator: [{
                type: Input,
                args: ['validator']
            }], _inlineError: [{
                type: Input,
                args: ['inlineError']
            }], _hideInlineError: [{
                type: Input,
                args: ['hideInlineError']
            }], input: [{
                type: ViewChild,
                args: ['input']
            }], sdViewDef: [{
                type: ContentChild,
                args: [SdViewDefDirective]
            }] } });

/**
 * Generated bundle index. Do not edit.
 */

export { SdAutocomplete };
//# sourceMappingURL=sd-angular-core-forms-autocomplete.mjs.map
