(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('@angular/material/icon'), require('@angular/material/tooltip'), require('@angular/material/progress-spinner'), require('@angular/cdk/keycodes'), require('rxjs/operators'), require('uuid'), require('object-hash'), require('@angular/forms'), require('rxjs'), require('@angular/material/autocomplete'), require('@sd-angular/core/common'), require('@angular/material/input'), require('@angular/material/form-field'), require('@sd-angular/core/translate'), require('@angular/material/chips')) :
    typeof define === 'function' && define.amd ? define('@sd-angular/core/chip', ['exports', '@angular/core', '@angular/common', '@angular/material/icon', '@angular/material/tooltip', '@angular/material/progress-spinner', '@angular/cdk/keycodes', 'rxjs/operators', 'uuid', 'object-hash', '@angular/forms', 'rxjs', '@angular/material/autocomplete', '@sd-angular/core/common', '@angular/material/input', '@angular/material/form-field', '@sd-angular/core/translate', '@angular/material/chips'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global['sd-angular'] = global['sd-angular'] || {}, global['sd-angular'].core = global['sd-angular'].core || {}, global['sd-angular'].core.chip = {}), global.ng.core, global.ng.common, global.ng.material.icon, global.ng.material.tooltip, global.ng.material.progressSpinner, global.ng.cdk.keycodes, global.rxjs.operators, global.uuid, global.hash, global.ng.forms, global.rxjs, global.ng.material.autocomplete, global['sd-angular'].core.common, global.ng.material.input, global.ng.material.formField, global['sd-angular'].core.translate, global.ng.material.chips));
}(this, (function (exports, core, common$1, icon, tooltip, progressSpinner, keycodes, operators, uuid, hash, forms, rxjs, autocomplete, common, input, formField, translate, chips) { 'use strict';

    function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

    var hash__default = /*#__PURE__*/_interopDefaultLegacy(hash);

    /*! *****************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */
    /* global Reflect, Promise */
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b)
                if (Object.prototype.hasOwnProperty.call(b, p))
                    d[p] = b[p]; };
        return extendStatics(d, b);
    };
    function __extends(d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    var __assign = function () {
        __assign = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s)
                    if (Object.prototype.hasOwnProperty.call(s, p))
                        t[p] = s[p];
            }
            return t;
        };
        return __assign.apply(this, arguments);
    };
    function __rest(s, e) {
        var t = {};
        for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
                t[p] = s[p];
        if (s != null && typeof Object.getOwnPropertySymbols === "function")
            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                    t[p[i]] = s[p[i]];
            }
        return t;
    }
    function __decorate(decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
            r = Reflect.decorate(decorators, target, key, desc);
        else
            for (var i = decorators.length - 1; i >= 0; i--)
                if (d = decorators[i])
                    r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    }
    function __param(paramIndex, decorator) {
        return function (target, key) { decorator(target, key, paramIndex); };
    }
    function __metadata(metadataKey, metadataValue) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
            return Reflect.metadata(metadataKey, metadataValue);
    }
    function __awaiter(thisArg, _arguments, P, generator) {
        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try {
                step(generator.next(value));
            }
            catch (e) {
                reject(e);
            } }
            function rejected(value) { try {
                step(generator["throw"](value));
            }
            catch (e) {
                reject(e);
            } }
            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }
    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function () { if (t[0] & 1)
                throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f)
                throw new TypeError("Generator is already executing.");
            while (_)
                try {
                    if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
                        return t;
                    if (y = 0, t)
                        op = [op[0] & 2, t.value];
                    switch (op[0]) {
                        case 0:
                        case 1:
                            t = op;
                            break;
                        case 4:
                            _.label++;
                            return { value: op[1], done: false };
                        case 5:
                            _.label++;
                            y = op[1];
                            op = [0];
                            continue;
                        case 7:
                            op = _.ops.pop();
                            _.trys.pop();
                            continue;
                        default:
                            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                                _ = 0;
                                continue;
                            }
                            if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
                                _.label = op[1];
                                break;
                            }
                            if (op[0] === 6 && _.label < t[1]) {
                                _.label = t[1];
                                t = op;
                                break;
                            }
                            if (t && _.label < t[2]) {
                                _.label = t[2];
                                _.ops.push(op);
                                break;
                            }
                            if (t[2])
                                _.ops.pop();
                            _.trys.pop();
                            continue;
                    }
                    op = body.call(thisArg, _);
                }
                catch (e) {
                    op = [6, e];
                    y = 0;
                }
                finally {
                    f = t = 0;
                }
            if (op[0] & 5)
                throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
        }
    }
    var __createBinding = Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    });
    function __exportStar(m, o) {
        for (var p in m)
            if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
                __createBinding(o, m, p);
    }
    function __values(o) {
        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        if (m)
            return m.call(o);
        if (o && typeof o.length === "number")
            return {
                next: function () {
                    if (o && i >= o.length)
                        o = void 0;
                    return { value: o && o[i++], done: !o };
                }
            };
        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __read(o, n) {
        var m = typeof Symbol === "function" && o[Symbol.iterator];
        if (!m)
            return o;
        var i = m.call(o), r, ar = [], e;
        try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
                ar.push(r.value);
        }
        catch (error) {
            e = { error: error };
        }
        finally {
            try {
                if (r && !r.done && (m = i["return"]))
                    m.call(i);
            }
            finally {
                if (e)
                    throw e.error;
            }
        }
        return ar;
    }
    /** @deprecated */
    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }
    /** @deprecated */
    function __spreadArrays() {
        for (var s = 0, i = 0, il = arguments.length; i < il; i++)
            s += arguments[i].length;
        for (var r = Array(s), k = 0, i = 0; i < il; i++)
            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
                r[k] = a[j];
        return r;
    }
    function __spreadArray(to, from, pack) {
        if (pack || arguments.length === 2)
            for (var i = 0, l = from.length, ar; i < l; i++) {
                if (ar || !(i in from)) {
                    if (!ar)
                        ar = Array.prototype.slice.call(from, 0, i);
                    ar[i] = from[i];
                }
            }
        return to.concat(ar || Array.prototype.slice.call(from));
    }
    function __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
    }
    function __asyncGenerator(thisArg, _arguments, generator) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var g = generator.apply(thisArg, _arguments || []), i, q = [];
        return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
        function verb(n) { if (g[n])
            i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
        function resume(n, v) { try {
            step(g[n](v));
        }
        catch (e) {
            settle(q[0][3], e);
        } }
        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
        function fulfill(value) { resume("next", value); }
        function reject(value) { resume("throw", value); }
        function settle(f, v) { if (f(v), q.shift(), q.length)
            resume(q[0][0], q[0][1]); }
    }
    function __asyncDelegator(o) {
        var i, p;
        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
    }
    function __asyncValues(o) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var m = o[Symbol.asyncIterator], i;
        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
    }
    function __makeTemplateObject(cooked, raw) {
        if (Object.defineProperty) {
            Object.defineProperty(cooked, "raw", { value: raw });
        }
        else {
            cooked.raw = raw;
        }
        return cooked;
    }
    ;
    var __setModuleDefault = Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    };
    function __importStar(mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k in mod)
                if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    }
    function __importDefault(mod) {
        return (mod && mod.__esModule) ? mod : { default: mod };
    }
    function __classPrivateFieldGet(receiver, state, kind, f) {
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a getter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot read private member from an object whose class did not declare it");
        return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    }
    function __classPrivateFieldSet(receiver, state, value, kind, f) {
        if (kind === "m")
            throw new TypeError("Private method is not writable");
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a setter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot write private member to an object whose class did not declare it");
        return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
    }

    var SdChipDisplayDef = /** @class */ (function () {
        function SdChipDisplayDef(templateRef) {
            this.templateRef = templateRef;
        }
        return SdChipDisplayDef;
    }());
    SdChipDisplayDef.decorators = [
        { type: core.Directive, args: [{
                    selector: '[sdChipDisplayDef]'
                },] }
    ];
    SdChipDisplayDef.ctorParameters = function () { return [
        { type: core.TemplateRef }
    ]; };

    var _name, _form, _addable, _allItems, _allItem, _cache, _delay, _itemsChanges, _selectedItems, _filteredItems, _subscription, _updateValidator, _loadItems, _loadSelectedItems;
    var SdChipErrotStateMatcher = /** @class */ (function () {
        function SdChipErrotStateMatcher(formControl) {
            this.formControl = formControl;
        }
        SdChipErrotStateMatcher.prototype.isErrorState = function (control, form) {
            var _a, _b, _c;
            var isSubmitted = form && form.submitted;
            return !!(((_a = this.formControl) === null || _a === void 0 ? void 0 : _a.invalid) && (((_b = this.formControl) === null || _b === void 0 ? void 0 : _b.dirty) || ((_c = this.formControl) === null || _c === void 0 ? void 0 : _c.touched) || isSubmitted));
        };
        return SdChipErrotStateMatcher;
    }());
    var SdChip = /** @class */ (function () {
        function SdChip(ref, formConfig) {
            var _this = this;
            this.ref = ref;
            this.formConfig = formConfig;
            _name.set(this, uuid.v4());
            this.separatorKeysCodes = [keycodes.ENTER, keycodes.COMMA];
            this.selectable = true;
            _form.set(this, void 0);
            _addable.set(this, void 0);
            this.removable = true;
            this.disableErrorMessage = false;
            // Server search
            this.loading = false;
            _allItems.set(this, void 0);
            _allItem.set(this, {});
            _cache.set(this, {});
            _delay.set(this, 200); // 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
            _itemsChanges.set(this, new rxjs.BehaviorSubject([]));
            this.limit = 50;
            _selectedItems.set(this, []);
            _filteredItems.set(this, void 0);
            // Validator
            this.required = false;
            this.modelChange = new core.EventEmitter();
            this.sdChange = new core.EventEmitter();
            this.sdUpdate = new core.EventEmitter();
            this.chipSelected = new core.EventEmitter();
            this.isBluring = false;
            this.isFocused = false;
            this.inputControl = new forms.FormControl();
            this.formControl = new common.SdFormControl();
            this.matcher = new SdChipErrotStateMatcher(this.formControl);
            _subscription.set(this, new rxjs.Subscription());
            _updateValidator.set(this, function () {
                _this.formControl.clearValidators();
                _this.formControl.clearAsyncValidators();
                var validators = [];
                var asyncValidators = [];
                if (_this.required) {
                    validators.push(forms.Validators.required);
                }
                if (_this.min > 0) {
                    validators.push(forms.Validators.minLength(_this.min));
                }
                if (_this.max > 0) {
                    validators.push(forms.Validators.maxLength(_this.max));
                }
                _this.formControl.setValidators(validators);
                _this.formControl.setAsyncValidators(asyncValidators);
                _this.formControl.updateValueAndValidity();
            });
            _loadItems.set(this, function (searchText, items) { return __awaiter(_this, void 0, void 0, function () {
                var key, results, objItem, selectedItems;
                var _this = this;
                return __generator(this, function (_f) {
                    switch (_f.label) {
                        case 0:
                            searchText = (searchText === null || searchText === void 0 ? void 0 : searchText.toString()) || '';
                            key = hash__default['default']({
                                checksum: this.cacheChecksum || null,
                                searchText: searchText
                            });
                            if (!(__classPrivateFieldGet(this, _cache)[key] === undefined)) return [3 /*break*/, 2];
                            this.loading = true;
                            return [4 /*yield*/, items(searchText).catch(function () { return []; }).finally(function () { return _this.loading = false; })];
                        case 1:
                            results = _f.sent();
                            objItem = Array.toObject(results, this.valueField);
                            __classPrivateFieldSet(this, _allItem, Object.assign(Object.assign({}, __classPrivateFieldGet(this, _allItem)), objItem));
                            __classPrivateFieldGet(this, _cache)[key] = results.union(this.valueField);
                            _f.label = 2;
                        case 2: return [4 /*yield*/, __classPrivateFieldGet(this, _loadSelectedItems).call(this, this.formControl.value, items)];
                        case 3:
                            selectedItems = _f.sent();
                            // Đưa những selectedItems lên đầu nếu không mat-select-trigger sẽ không work
                            return [2 /*return*/, __spread(selectedItems, __classPrivateFieldGet(this, _cache)[key]).union(this.valueField)];
                    }
                });
            }); });
            _loadSelectedItems.set(this, function (value, items) { return __awaiter(_this, void 0, void 0, function () {
                var values, results, objItem, objValue;
                var _this = this;
                return __generator(this, function (_f) {
                    switch (_f.label) {
                        case 0:
                            if (!(value === null || value === void 0 ? void 0 : value.toString())) {
                                return [2 /*return*/, []];
                            }
                            values = Array.isArray(value) ? value : [value];
                            if (!this.valueField && !this.displayField) {
                                return [2 /*return*/, values];
                            }
                            this.loading = true;
                            if (!values.some(function (val) { return __classPrivateFieldGet(_this, _allItem)[val] === undefined; })) return [3 /*break*/, 2];
                            return [4 /*yield*/, items(value, true).catch(function () { return []; }).finally(function () { return _this.loading = false; })];
                        case 1:
                            results = _f.sent();
                            objItem = Array.toObject(results, this.valueField);
                            objValue = Array.toObject(values.map(function (val) {
                                var _f, _g;
                                return (_f = {}, _f[val === null || val === void 0 ? void 0 : val.toString()] = (_g = {}, _g[_this.valueField] = val, _g[_this.displayField] = val, _g), _f);
                            }), this.valueField);
                            __classPrivateFieldSet(this, _allItem, Object.assign(Object.assign(Object.assign({}, objValue), __classPrivateFieldGet(this, _allItem)), objItem));
                            _f.label = 2;
                        case 2: return [2 /*return*/, values.map(function (val) {
                                var _f;
                                var _a;
                                return (_a = __classPrivateFieldGet(_this, _allItem)[val === null || val === void 0 ? void 0 : val.toString()]) !== null && _a !== void 0 ? _a : (_f = {}, _f[_this.valueField] = val, _f[_this.displayField] = val, _f);
                            })];
                    }
                });
            }); });
            this.onAdd = function (event) {
                var _a, _b, _c, _d, _e;
                // Add item only when MatAutocomplete is not open
                // To make sure this does not conflict with OptionSelected Event
                // if (!this.matAutocomplete.isOpen) {
                //   const value = (event.value ?? '').toString().trim();
                //   if (value) {
                //     if (this.valueField && this.displayField) {
                //       const item = this.#filteredItems.find(e => e[this.displayField] === value);
                //       if (item) {
                //         const values: (string | number)[] = this.formControl.value ?? [];
                //         values.push(item[this.valueField]);
                //         this.formControl.setValue(values);
                //       } else if (this.#addable) {
                //         const values: (string | number)[] = this.formControl.value ?? [];
                //         values.push(value);
                //         this.formControl.setValue(values);
                //       }
                //     } else {
                //       console.log(value);
                //       console.log(this.#filteredItems);
                //       const item = this.#filteredItems.find(item => item === value);
                //       if (item) {
                //         const values: (string | number)[] = this.formControl.value ?? [];
                //         values.push(item);
                //         this.formControl.setValue(values);
                //       } else if (this.#addable) {
                //         const values: (string | number)[] = this.formControl.value ?? [];
                //         values.push(value);
                //         this.formControl.setValue(values);
                //       }
                //     }
                //   }
                //   this.inputControl.setValue('');
                // }
                var value = ((_a = event.value) !== null && _a !== void 0 ? _a : '').toString().trim();
                if (value) {
                    if (_this.valueField && _this.displayField) {
                        var item = __classPrivateFieldGet(_this, _filteredItems).find(function (e) { return e[_this.displayField] === value; });
                        if (item) {
                            var values = (_b = _this.formControl.value) !== null && _b !== void 0 ? _b : [];
                            values.push(item[_this.valueField]);
                            _this.formControl.setValue(values);
                            _this.modelChange.emit(_this.formControl.value);
                            _this.sdChange.emit(_this.formControl.value);
                        }
                        else if (__classPrivateFieldGet(_this, _addable)) {
                            var values = (_c = _this.formControl.value) !== null && _c !== void 0 ? _c : [];
                            values.push(value);
                            _this.formControl.setValue(values);
                            _this.modelChange.emit(_this.formControl.value);
                            _this.sdChange.emit(_this.formControl.value);
                        }
                    }
                    else {
                        var item = __classPrivateFieldGet(_this, _filteredItems).find(function (item) { return item === value; });
                        if (item) {
                            var values = (_d = _this.formControl.value) !== null && _d !== void 0 ? _d : [];
                            values.push(item);
                            _this.formControl.setValue(values);
                            _this.modelChange.emit(_this.formControl.value);
                            _this.sdChange.emit(_this.formControl.value);
                        }
                        else if (__classPrivateFieldGet(_this, _addable)) {
                            var values = (_e = _this.formControl.value) !== null && _e !== void 0 ? _e : [];
                            values.push(value);
                            _this.formControl.setValue(values);
                            _this.modelChange.emit(_this.formControl.value);
                            _this.sdChange.emit(_this.formControl.value);
                        }
                    }
                }
                _this.input.nativeElement.value = '';
                _this.inputControl.setValue('');
            };
            // andn1 viết để xử lý tạm us B2B1D-18289 ở S69
            this.onAdd2 = function (event) {
                var _a, _b;
                var value = ((_a = event.value) !== null && _a !== void 0 ? _a : '').toString().toLowerCase().trim();
                if (value) {
                    var item = __classPrivateFieldGet(_this, _filteredItems).find(function (e) { return e[_this.valueField]
                        && e[_this.valueField].toString().toLowerCase().trim() === value; });
                    if (item) {
                        var values = (_b = _this.formControl.value) !== null && _b !== void 0 ? _b : [];
                        if (!values.includes(item[_this.valueField])) {
                            values.push(item[_this.valueField]);
                        }
                        _this.formControl.setValue(values);
                    }
                }
                _this.inputControl.setValue('');
            };
            this.onClickChip = function ($event, item) {
                $event.stopPropagation();
                $event.stopImmediatePropagation();
                if (!_this.formControl.disabled) {
                    item.isSelected = !item.isSelected;
                    _this.focus();
                }
            };
            this.onRemove = function (item) {
                var _a;
                var values = (_a = _this.formControl.value) !== null && _a !== void 0 ? _a : [];
                if (typeof (item) === 'string' || typeof (item) === 'number') {
                    _this.formControl.setValue(values.filter(function (value) { return item !== value; }));
                    _this.modelChange.emit(_this.formControl.value);
                    _this.sdChange.emit(_this.formControl.value);
                }
                else if (_this.valueField) {
                    _this.formControl.setValue(values.filter(function (value) { return (item === null || item === void 0 ? void 0 : item[_this.valueField]) !== value; }));
                    _this.modelChange.emit(_this.formControl.value);
                    _this.sdChange.emit(_this.formControl.value);
                }
                _this.inputControl.setValue('');
                _this.focus();
            };
            this.select = function (item) {
                _this.chipSelected.emit(item);
                _this.focus();
            };
            // onSelect = (event: MatAutocompleteSelectedEvent) => {
            //   const value = (event.option.value?.[this.valueField] ?? '').toString().trim();
            //   if (value) {
            //     const item = this.#items.find(e => e[this.valueField]
            //       && e[this.valueField].toString().trim() === value);
            //     if (item) {
            //       const values: (string | number)[] = this.formControl.value ?? [];
            //       values.push(item[this.valueField]);
            //       this.formControl.setValue(values);
            //       this.input.nativeElement.value = '';
            //       this.inputControl.setValue('');
            //       setTimeout(() => {
            //         this.autocompleteTrigger?.openPanel();
            //       }, 0);
            //     }
            //   }
            // }
            this.onSelect = function (event) {
                var _a;
                var item = event.option.value;
                var values = (_a = _this.formControl.value) !== null && _a !== void 0 ? _a : [];
                if (item) {
                    if (typeof (item) === 'string' || typeof (item) === 'number') {
                        if (!values.includes(item)) {
                            values.push(item);
                            _this.formControl.setValue(values);
                            _this.modelChange.emit(_this.formControl.value);
                            _this.sdChange.emit(_this.formControl.value);
                            setTimeout(function () {
                                var _a;
                                (_a = _this.autocompleteTrigger) === null || _a === void 0 ? void 0 : _a.openPanel();
                            }, 0);
                        }
                    }
                    else if (_this.valueField) {
                        var val = (item === null || item === void 0 ? void 0 : item[_this.valueField]) || null;
                        if (!values.includes(val)) {
                            values.push(val);
                            _this.formControl.setValue(values);
                            _this.modelChange.emit(_this.formControl.value);
                            _this.sdChange.emit(_this.formControl.value);
                            setTimeout(function () {
                                var _a;
                                (_a = _this.autocompleteTrigger) === null || _a === void 0 ? void 0 : _a.openPanel();
                            }, 0);
                        }
                    }
                    _this.input.nativeElement.value = '';
                    _this.inputControl.setValue('', {
                        emitEvent: false
                    });
                }
            };
            // displayFn = (value: string | { [key: string]: string }): string | undefined => {
            //   if (typeof value === 'string') {
            //     if (!this.#items) {
            //       return undefined;
            //     }
            //     const selectedItem = this.#items.find(item => item[this.valueField] === value);
            //     if (selectedItem) {
            //       return selectedItem[this.displayField];
            //     }
            //     if (this.#items.some(item => item[this.displayField].toLowerCase().indexOf(value.toLowerCase()) !== -1)) {
            //       return value;
            //     } else {
            //       return undefined;
            //     }
            //   } else {
            //     return value ? value[this.displayField] : undefined;
            //   }
            // }
            this.onFocus = function () {
                _this.isFocused = true;
                _this.isBluring = false;
                _this.inputControl.setValue('');
                // this.inputControl.updateValueAndValidity();
            };
            this.onBlur = function () {
                _this.isBluring = true;
                setTimeout(function () {
                    if (_this.isBluring) {
                        _this.isFocused = false;
                        _this.inputControl.setValue('', {
                            emitEvent: false
                        });
                    }
                }, 100);
            };
            this.onClick = function () {
                var _a;
                if ((_a = _this.sdView) === null || _a === void 0 ? void 0 : _a.templateRef) {
                    if (!_this.formControl.disabled && !_this.isFocused) {
                        _this.focus();
                    }
                }
            };
            this.focus = function () {
                _this.isFocused = true;
                _this.isBluring = false;
                setTimeout(function () {
                    var _a, _b, _c;
                    (_a = _this.autocompleteTrigger) === null || _a === void 0 ? void 0 : _a.openPanel();
                    (_c = (_b = _this.input) === null || _b === void 0 ? void 0 : _b.nativeElement) === null || _c === void 0 ? void 0 : _c.focus();
                }, 100);
            };
            this.onClear = function ($event) {
                var _a;
                $event === null || $event === void 0 ? void 0 : $event.stopPropagation();
                _this.inputControl.setValue('');
                _this.formControl.setValue([]);
                _this.modelChange.emit(_this.formControl.value);
                _this.sdChange.emit(_this.formControl.value);
                (_a = _this.autocompleteTrigger) === null || _a === void 0 ? void 0 : _a.openPanel();
                _this.ref.detectChanges();
            };
            this.getSelectedItems = function () { return __classPrivateFieldGet(_this, _selectedItems); };
        }
        Object.defineProperty(SdChip.prototype, "name", {
            set: function (val) {
                if (val) {
                    __classPrivateFieldSet(this, _name, val);
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdChip.prototype, "form", {
            set: function (val) {
                if (val) {
                    if (val instanceof forms.NgForm) {
                        __classPrivateFieldSet(this, _form, val.form);
                    }
                    else {
                        __classPrivateFieldSet(this, _form, val);
                    }
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdChip.prototype, "addable", {
            set: function (val) {
                __classPrivateFieldSet(this, _addable, (val === '') || val);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdChip.prototype, "_removable", {
            set: function (val) {
                this.removable = (val === '') || val;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdChip.prototype, "_disableErrorMessage", {
            set: function (val) {
                this.disableErrorMessage = (val === '') || val;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdChip.prototype, "items", {
            set: function (items) {
                __classPrivateFieldSet(this, _delay, 0);
                if (!items) {
                    __classPrivateFieldGet(this, _itemsChanges).next([]);
                }
                else if (Array.isArray(items)) {
                    __classPrivateFieldGet(this, _itemsChanges).next(items.filter(function (e) { return e !== null && e !== undefined; }));
                }
                else {
                    __classPrivateFieldSet(this, _delay, 500);
                    __classPrivateFieldGet(this, _itemsChanges).next(items);
                }
                this.formControl.updateValueAndValidity();
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdChip.prototype, "model", {
            // model
            set: function (values) {
                if (!Array.isArray(values)) {
                    values = [];
                }
                this.formControl.setValue(values);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdChip.prototype, "_required", {
            set: function (val) {
                this.required = (val === '') || val;
                __classPrivateFieldGet(this, _updateValidator).call(this);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdChip.prototype, "pMin", {
            set: function (val) {
                this.min = +val || 0;
                __classPrivateFieldGet(this, _updateValidator).call(this);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdChip.prototype, "pMax", {
            set: function (val) {
                this.max = +val || 0;
                __classPrivateFieldGet(this, _updateValidator).call(this);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SdChip.prototype, "disabled", {
            // Optional
            set: function (val) {
                val = (val === '') || val;
                if (val) {
                    this.formControl.disable();
                    this.inputControl.disable();
                }
                else {
                    this.formControl.enable();
                    this.inputControl.enable();
                }
            },
            enumerable: false,
            configurable: true
        });
        SdChip.prototype.ngOnInit = function () {
            var _a;
            this.appearance = this.appearance || ((_a = this.formConfig) === null || _a === void 0 ? void 0 : _a.appearance);
        };
        SdChip.prototype.ngAfterViewInit = function () {
            var _this = this;
            var _a;
            __classPrivateFieldGet(this, _subscription).add(this.formControl.sdChanges.subscribe(function () {
                _this.ref.markForCheck();
            }));
            __classPrivateFieldSet(this, _allItems, rxjs.combineLatest([
                __classPrivateFieldGet(this, _itemsChanges).asObservable(),
                this.inputControl.valueChanges.pipe(operators.startWith(''), operators.debounceTime(__classPrivateFieldGet(this, _delay))),
                this.formControl.valueChanges.pipe(operators.startWith(this.formControl.value))
            ]).pipe(operators.switchMap(function (_f) {
                var _g = __read(_f, 1), items = _g[0];
                return __awaiter(_this, void 0, void 0, function () {
                    var val, values, hasFields;
                    var _this = this;
                    return __generator(this, function (_f) {
                        switch (_f.label) {
                            case 0:
                                val = this.inputControl.value;
                                values = this.formControl.value || [];
                                if (!(typeof (items) === 'function')) return [3 /*break*/, 2];
                                return [4 /*yield*/, __classPrivateFieldGet(this, _loadItems).call(this, val, items)];
                            case 1: return [2 /*return*/, _f.sent()];
                            case 2:
                                __classPrivateFieldSet(this, _allItem, items.toObject(this.valueField));
                                hasFields = !!this.valueField && !!this.displayField;
                                __classPrivateFieldSet(this, _filteredItems, items.filter(function (item) {
                                    var value = hasFields ? item[_this.valueField] : item;
                                    var display = hasFields ? item[_this.displayField] : item;
                                    if (String.aliasIncludes(value, val) || String.aliasIncludes(display, val)) {
                                        return true;
                                    }
                                    return values.some(function (e) { return e === value; });
                                }));
                                return [2 /*return*/, __classPrivateFieldGet(this, _filteredItems)];
                        }
                    });
                });
            })));
            this.selectedItems = rxjs.combineLatest([
                __classPrivateFieldGet(this, _itemsChanges).asObservable(),
                this.formControl.valueChanges.pipe(operators.startWith(this.formControl.value))
            ])
                .pipe(operators.switchMap(function (_f) {
                var _g = __read(_f, 2), items = _g[0], val = _g[1];
                return __awaiter(_this, void 0, void 0, function () {
                    var _b, _f, _g;
                    var _this = this;
                    return __generator(this, function (_h) {
                        switch (_h.label) {
                            case 0:
                                // 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;
                                val = this.formControl.value;
                                if (!this.valueField) {
                                    __classPrivateFieldSet(this, _selectedItems, this.formControl.value);
                                    return [2 /*return*/, __classPrivateFieldGet(this, _selectedItems)];
                                }
                                if (!(typeof (items) === 'function')) return [3 /*break*/, 2];
                                _f = __classPrivateFieldSet;
                                _g = [this, _selectedItems];
                                return [4 /*yield*/, __classPrivateFieldGet(this, _loadSelectedItems).call(this, val, items)];
                            case 1:
                                _f.apply(void 0, _g.concat([_h.sent()]));
                                return [2 /*return*/, __classPrivateFieldGet(this, _selectedItems)];
                            case 2:
                                __classPrivateFieldSet(this, _selectedItems, (_b = (this.formControl.value || [])) === null || _b === void 0 ? void 0 : _b.map(function (value) {
                                    var _f;
                                    return (items === null || items === void 0 ? void 0 : items.find(function (item) { return item[_this.valueField] === value; })) || (_f = {},
                                        _f[_this.valueField] = value,
                                        _f[_this.displayField] = value,
                                        _f);
                                }));
                                return [2 /*return*/, __classPrivateFieldGet(this, _selectedItems)];
                        }
                    });
                });
            }));
            this.filteredItems = __classPrivateFieldGet(this, _allItems).pipe(operators.map(function (allItems) { return allItems.filter(function (item) {
                var values = _this.formControl.value || [];
                if (_this.valueField) {
                    return !values.includes(item === null || item === void 0 ? void 0 : item[_this.valueField]);
                }
                return !values.includes(item);
            }).paging(_this.limit); }));
            // this.display = this.selectedItems.pipe(
            //   map(selectedItems => selectedItems?.map(item => this.displayField ? item[this.displayField] : item)?.join(', ')));
            // this.#subscription.add(this.formControl.valueChanges.subscribe(() => {
            //   const values: (string | number)[] = this.formControl.value || [];
            //   this.selectedItems = this.#items.filter(item => values.findIndex(value => value === item?.[this.valueField]) !== -1);
            //   this.modelChange.emit(values);
            //   this.sdChange.emit(values);
            //   setTimeout(() => {
            //     this.#form?.markAsDirty();
            //   }, 0);
            // }));
            // this.#subscription.add(this.#itemChanges.pipe(startWith(this.#items)).subscribe(() => {
            //   const values: (string | number)[] = this.formControl.value || [];
            //   this.selectedItems = [];
            //   for (const value of values) {
            //     const item = this.#items.find(e => e?.[this.valueField] === value) || {};
            //     this.selectedItems.push({
            //       ...item,
            //       [this.valueField]: value
            //     });
            //   }
            // }));
            (_a = __classPrivateFieldGet(this, _form)) === null || _a === void 0 ? void 0 : _a.addControl(__classPrivateFieldGet(this, _name), this.formControl);
        };
        SdChip.prototype.ngOnDestroy = function () {
            var _a;
            (_a = __classPrivateFieldGet(this, _form)) === null || _a === void 0 ? void 0 : _a.removeControl(__classPrivateFieldGet(this, _name));
            __classPrivateFieldGet(this, _subscription).unsubscribe();
        };
        return SdChip;
    }());
    _name = new WeakMap(), _form = new WeakMap(), _addable = new WeakMap(), _allItems = new WeakMap(), _allItem = new WeakMap(), _cache = new WeakMap(), _delay = new WeakMap(), _itemsChanges = new WeakMap(), _selectedItems = new WeakMap(), _filteredItems = new WeakMap(), _subscription = new WeakMap(), _updateValidator = new WeakMap(), _loadItems = new WeakMap(), _loadSelectedItems = new WeakMap();
    SdChip.decorators = [
        { type: core.Component, args: [{
                    selector: 'sd-chip',
                    template: "<ng-container *ngIf=\"!appearance && sdLabelDef?.templateRef\">\r\n  <ng-container *ngTemplateOutlet=\"sdLabelDef.templateRef\">\r\n  </ng-container>\r\n</ng-container>\r\n<label *ngIf=\"!appearance && label && !sdLabelDef?.templateRef\" class=\"d-block mb-0 T14M\">{{label}} <span class=\"text-danger mb-2\"\r\n    *ngIf=\"required\">*</span></label>\r\n<div class=\"d-flex align-items-center\" [class.sd-view]=\"sdView?.templateRef\" [class.c-focused]=\"isFocused\"\r\n  [class.c-disabled]=\"formControl.disabled\" (click)=\"onClick()\">\r\n  <ng-container *ngIf=\"sdView?.templateRef && !autocompleteTrigger?.panelOpen && !isFocused; else default\">\r\n    <ng-container *ngTemplateOutlet=\"sdView.templateRef;context: { value: formControl.value}\">\r\n    </ng-container>\r\n  </ng-container>\r\n  <ng-template #default>\r\n    <mat-form-field class=\"c-md\" [ngClass]=\"{'c-sm': size === 'sm', 'no-padding-wrapper': disableErrorMessage}\"\r\n      [appearance]=\"appearance || 'outline'\">\r\n      <mat-label *ngIf=\"appearance && label\">{{ label }}</mat-label>\r\n      <mat-chip-list [formControl]=\"formControl\" #chipList>\r\n        <ng-container *ngFor=\"let item of selectedItems | async\">\r\n          <mat-chip *ngIf=\"item\" [selectable]=\"selectable\" [removable]=\"removable\" (removed)=\"onRemove(item)\"\r\n            [selected]=\"item.isSelected\" (selectionChange)=\"select(item)\" [disabled]=\"inputControl.disabled\"\r\n            (click)=\"onClickChip($event, item)\">\r\n            <span>{{item[displayField] || item[valueField] || item}}</span>\r\n            <mat-icon *ngIf=\"!inputControl.disabled && item | sdRemovableChip:removable\" matChipRemove>cancel</mat-icon>\r\n          </mat-chip>\r\n        </ng-container>\r\n        <input #autocompleteTrigger [formControl]=\"inputControl\" [placeholder]=\"placeholder || (appearance ? label : '')\"\r\n          [matAutocomplete]=\"auto\" [matChipInputFor]=\"chipList\" [matChipInputSeparatorKeyCodes]=\"separatorKeysCodes\"\r\n          (matChipInputTokenEnd)=\"onAdd($event)\" autocomplete=\"off\" [errorStateMatcher]=\"matcher\" (focus)=\"onFocus()\"\r\n          (blur)=\"onBlur()\" [required]=\"required\" matInput #input>\r\n      </mat-chip-list>\r\n      <mat-autocomplete #auto=\"matAutocomplete\" (optionSelected)=\"onSelect($event)\">\r\n        <mat-option *ngFor=\"let item of filteredItems | async\" [value]=\"item\" matTooltipPosition=\"above\"\r\n          [matTooltip]=\"displayField ? item[displayField] : item\">\r\n          <ng-container *ngIf=\"sdChipDisplay?.templateRef\">\r\n            <ng-container *ngTemplateOutlet=\"sdChipDisplay.templateRef;context:{item: item}\">\r\n            </ng-container>\r\n          </ng-container>\r\n          <ng-container *ngIf=\"!sdChipDisplay?.templateRef\">\r\n            {{ displayField ? item[displayField] : item }}\r\n          </ng-container>\r\n        </mat-option>\r\n      </mat-autocomplete>\r\n      <mat-error *ngIf=\"formControl?.errors?.required\">\r\n        <ng-container *ngIf=\"!disableErrorMessage\">{{ \"This field is required\" | sdTranslate }}</ng-container>\r\n      </mat-error>\r\n    </mat-form-field>\r\n  </ng-template>\r\n</div>",
                    changeDetection: core.ChangeDetectionStrategy.OnPush,
                    styles: [":host{display:block;padding-top:5px}:host ::ng-deep .mat-form-field.no-padding-wrapper .mat-form-field-wrapper{padding-bottom:0}:host ::ng-deep mat-form-field.c-md .mat-form-field-infix{min-height:43.5px;padding:2px 0}:host ::ng-deep mat-form-field.c-md .mat-standard-chip{min-height:26px;padding:7px 10px}:host ::ng-deep mat-form-field.c-md .mat-standard-chip.mat-chip-with-trailing-icon{padding:7px 7px 7px 10px}.sd-view:not(.c-focused):not(.c-disabled):hover{background-color:#ebecf0}"]
                },] }
    ];
    SdChip.ctorParameters = function () { return [
        { type: core.ChangeDetectorRef },
        { type: undefined, decorators: [{ type: core.Inject, args: [common.FORM_CONFIG,] }, { type: core.Optional }] }
    ]; };
    SdChip.propDecorators = {
        name: [{ type: core.Input }],
        appearance: [{ type: core.Input }],
        size: [{ type: core.Input }],
        form: [{ type: core.Input }],
        addable: [{ type: core.Input }],
        label: [{ type: core.Input }],
        valueField: [{ type: core.Input }],
        displayField: [{ type: core.Input }],
        placeholder: [{ type: core.Input }],
        _removable: [{ type: core.Input, args: ['removable',] }],
        _disableErrorMessage: [{ type: core.Input, args: ['disableErrorMessage',] }],
        items: [{ type: core.Input }],
        limit: [{ type: core.Input }],
        cacheChecksum: [{ type: core.Input }],
        model: [{ type: core.Input }],
        _required: [{ type: core.Input, args: ['required',] }],
        pMin: [{ type: core.Input, args: ['min',] }],
        pMax: [{ type: core.Input, args: ['max',] }],
        modelChange: [{ type: core.Output }],
        disabled: [{ type: core.Input }],
        sdChange: [{ type: core.Output }],
        sdUpdate: [{ type: core.Output }],
        chipSelected: [{ type: core.Output }],
        input: [{ type: core.ViewChild, args: ['input',] }],
        matAutocomplete: [{ type: core.ViewChild, args: ['auto',] }],
        chipList: [{ type: core.ViewChild, args: ['chipList', { static: true },] }],
        autocompleteTrigger: [{ type: core.ViewChild, args: [autocomplete.MatAutocompleteTrigger, { read: autocomplete.MatAutocompleteTrigger },] }],
        sdView: [{ type: core.ContentChild, args: [common.SdViewDefDirective,] }],
        sdChipDisplay: [{ type: core.ContentChild, args: [SdChipDisplayDef,] }],
        sdLabelDef: [{ type: core.ContentChild, args: [common.SdLabelDefDirective,] }]
    };

    var SdRemovableChipPipe = /** @class */ (function () {
        function SdRemovableChipPipe() {
        }
        SdRemovableChipPipe.prototype.transform = function (item, removable) {
            if (typeof (removable) === 'boolean') {
                return removable;
            }
            return removable(item);
        };
        return SdRemovableChipPipe;
    }());
    SdRemovableChipPipe.decorators = [
        { type: core.Pipe, args: [{
                    name: 'sdRemovableChip'
                },] }
    ];
    SdRemovableChipPipe.ctorParameters = function () { return []; };

    var SdChipModule = /** @class */ (function () {
        function SdChipModule() {
        }
        return SdChipModule;
    }());
    SdChipModule.decorators = [
        { type: core.NgModule, args: [{
                    imports: [
                        common$1.CommonModule,
                        forms.FormsModule,
                        forms.ReactiveFormsModule,
                        input.MatInputModule,
                        tooltip.MatTooltipModule,
                        formField.MatFormFieldModule,
                        autocomplete.MatAutocompleteModule,
                        icon.MatIconModule,
                        progressSpinner.MatProgressSpinnerModule,
                        chips.MatChipsModule,
                        translate.SdTranslateModule,
                        common.SdCommonModule
                    ],
                    declarations: [
                        SdChip,
                        SdChipDisplayDef,
                        SdRemovableChipPipe
                    ],
                    exports: [
                        common.SdCommonModule,
                        SdChip,
                        SdChipDisplayDef,
                    ]
                },] }
    ];

    /*
     * Public API Surface of superdev-angular-core
     */

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

    exports.SdChip = SdChip;
    exports.SdChipDisplayDef = SdChipDisplayDef;
    exports.SdChipModule = SdChipModule;
    exports.ɵa = SdRemovableChipPipe;

    Object.defineProperty(exports, '__esModule', { value: true });

})));
//# sourceMappingURL=sd-angular-core-chip.umd.js.map
