import * as i0 from '@angular/core';
import { Pipe, Injectable, EventEmitter, Output, ViewChild, Input, Component } from '@angular/core';
import * as i7 from '@angular/material/paginator';
import { MatPaginatorModule, MatPaginator } from '@angular/material/paginator';
import { Subscription } from 'rxjs';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import * as i6 from '@angular/material/tooltip';
import { MatTooltipModule } from '@angular/material/tooltip';
import * as i5 from '@angular/common';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { SdButton } from '@sd-angular/core/components/button';
import * as i8 from '@angular/material/icon';
import { MatIconModule } from '@angular/material/icon';
import * as i9 from '@angular/material/menu';
import { MatMenuModule } from '@angular/material/menu';
import { SdModal } from '@sd-angular/core/components/modal';
import { DateUtilities, NumberUtilities } from '@sd-angular/core/utilities';
import * as i1 from '@angular/platform-browser';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { SdBadge } from '@sd-angular/core/components/badge';
import * as i1$1 from '@sd-angular/core/services/excel';
import * as i2 from '@sd-angular/core/services/notify';
import * as i4 from '@sd-angular/core/services/loading';

// export type ExcelItem<T> = {
//   origin?: T;
//   excelIndex?: number;
//   validation: SdUploadExcelValidation;
// } & T;

class ColumnHiddenPipe {
    constructor() { }
    transform(column) {
        if (column.hidden === undefined) {
            return true;
        }
        if (typeof (column.hidden) === 'boolean') {
            return !column.hidden;
        }
        if (typeof (column.hidden) === 'function') {
            return !column.hidden();
        }
        return false;
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ColumnHiddenPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.2.17", ngImport: i0, type: ColumnHiddenPipe, isStandalone: true, name: "columnHidden" });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ColumnHiddenPipe });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ColumnHiddenPipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'columnHidden'
                }]
        }, {
            type: Injectable
        }], ctorParameters: () => [] });

class ColumnTransformPipe {
    sanitizer;
    constructor(sanitizer) {
        this.sanitizer = sanitizer;
    }
    // Chuyển thành async để hỗ trợ Promise từ bên ngoài
    async transform(item, column) {
        const { type, transform, field } = column;
        const value = item.data[field];
        // 1. Ưu tiên hiển thị dữ liệu gốc nếu có lỗi
        if (item.meta.error[field]) {
            return item.meta.origin[field] ?? value ?? '';
        }
        // 2. Custom Transform (Hỗ trợ cả Sync và Async)
        if (transform) {
            // await sẽ hoạt động đúng dù transform trả về value thường hay Promise
            const result = await transform(item.data, value);
            return result ?? '';
        }
        // 3. Xử lý logic hiển thị
        switch (type) {
            case 'number':
                return NumberUtilities.toVN(value) ?? '';
            case 'bool':
                if (typeof value === 'boolean') {
                    const html = `<div class="text-center"><input type="checkbox" ${value ? 'checked' : ''} disabled></div>`;
                    // Bắt buộc bypass security để hiển thị được input checkbox
                    return this.sanitizer.bypassSecurityTrustHtml(html);
                }
                return '';
            case 'date':
                return DateUtilities.toFormat(value, column.format || 'dd/MM/yyyy') ?? '';
            case 'datetime':
                return DateUtilities.toFormat(value, column.format || 'dd/MM/yyyy HH:mm') ?? '';
            default:
                return value ?? '';
        }
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ColumnTransformPipe, deps: [{ token: i1.DomSanitizer }], target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.2.17", ngImport: i0, type: ColumnTransformPipe, isStandalone: true, name: "columnTransform" });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ColumnTransformPipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'columnTransform',
                    standalone: true,
                }]
        }], ctorParameters: () => [{ type: i1.DomSanitizer }] });

class SdImportExcel {
    ref;
    excelService;
    notifyService;
    columnHiddenPipe;
    loadingService;
    option;
    modal;
    excelItems = [];
    // originItems: SdExcelItem[] = [];
    hasDescription = false;
    showing = 'ALL';
    filteredItems = [];
    viewItems = [];
    numberOfSuccess = 0;
    numberOfError = 0;
    numberOfWarning = 0;
    file;
    #paginator;
    #paginatorSub;
    set paginator(paginator) {
        if (paginator && this.#paginator !== paginator) {
            this.#paginator = paginator;
            this.#paginatorSub?.unsubscribe(); // Clear cũ
            this.#paginatorSub = paginator.page.subscribe(this.#reload);
            this.#subscription.add(this.#paginatorSub);
        }
    }
    #subscription = new Subscription();
    uploading = false;
    isUploaded = false;
    isDownloadTemplate = false;
    sdClosed = new EventEmitter();
    constructor(ref, excelService, notifyService, columnHiddenPipe, loadingService) {
        this.ref = ref;
        this.excelService = excelService;
        this.notifyService = notifyService;
        this.columnHiddenPipe = columnHiddenPipe;
        this.loadingService = loadingService;
    }
    ngOnInit() {
        this.isUploaded = false;
    }
    ngOnDestroy() {
        this.#subscription.unsubscribe();
    }
    open = () => {
        this.#reset();
        this.modal.open();
    };
    close = () => {
        this.modal.close();
    };
    #reset = () => {
        this.excelItems = [];
        this.filteredItems = [];
        this.viewItems = [];
        this.numberOfSuccess = 0;
        this.numberOfError = 0;
        this.numberOfWarning = 0;
        this.showing = 'ALL';
    };
    #reload = () => {
        const pageIndex = this.#paginator.pageIndex;
        const pageSize = this.#paginator.pageSize;
        this.filteredItems = this.excelItems.filter(item => {
            const { errorMessages, warningMessages } = item.meta;
            if (this.showing === 'SUCCESS') {
                return !errorMessages.length && !warningMessages.length;
            }
            else if (this.showing === 'WARNING') {
                return !!warningMessages.length && !errorMessages.length;
            }
            else if (this.showing === 'ERROR') {
                return !!errorMessages.length;
            }
            return true;
        });
        this.viewItems = this.filteredItems.filter((item, index) => index >= pageIndex * pageSize && index < (pageIndex + 1) * pageSize);
        this.numberOfSuccess = this.excelItems.filter(this.#filterSuccess).length;
        this.numberOfError = this.excelItems.filter(this.#filterError).length;
        this.numberOfWarning = this.excelItems.filter(this.#filterWarning).length;
    };
    #filterError = (item) => !!item.meta.errorMessages.length;
    #filterWarning = (item) => item.meta.warningMessages.length && !item.meta.errorMessages.length;
    #filterSuccess = (item) => !item.meta.errorMessages.length && !item.meta.warningMessages.length;
    upload = async () => {
        try {
            const { transform, validateItem, validateItems } = this.option;
            const { items, file } = await this.excelService.upload();
            this.hasDescription = this.option.columns.some(e => !!e.description);
            const offset = this.hasDescription ? 2 : 1;
            items.splice(0, offset);
            if (items.length === 0) {
                this.notifyService.warning(`Tệp tin không có dữ liệu`);
                return;
            }
            const limit = this.option.limit || 1000;
            if (items.length > limit) {
                this.notifyService.warning(`Giới hạn tải lên ${limit} dòng`);
                return;
            }
            this.#reset();
            this.excelItems = items.map((data, idx) => ({
                data,
                meta: {
                    excelIndex: idx + (this.hasDescription ? 4 : 3),
                    origin: { ...data },
                    error: {},
                    warning: {},
                    errorMessages: [],
                    warningMessages: [],
                },
            }));
            if (transform) {
                const mappedItems = transform(this.excelItems);
                if (mappedItems instanceof Promise) {
                    this.uploading = true;
                    this.excelItems = await mappedItems.finally(() => (this.uploading = false));
                }
                else {
                    this.excelItems = mappedItems || this.excelItems;
                }
            }
            this.file = file;
            this.loadingService.start();
            const validatePromises = this.excelItems.map((item, idx) => this.#validate(item, idx));
            await Promise.all(validatePromises);
            // Nếu không có error thì tiếp tục validate từ option validate truyền vào
            if (!this.excelItems.some(this.#filterError) && validateItems) {
                const results = await validateItems(this.excelItems.map(e => e.data));
                results
                    .filter(result => result.idx >= 0)
                    .forEach(result => {
                    if (result?.errorMessage) {
                        this.excelItems[result.idx].meta.errorMessages.push(result.errorMessage);
                    }
                    if (result?.warningMessage) {
                        this.excelItems[result.idx].meta.warningMessages.push(result.warningMessage);
                    }
                });
            }
            this.#paginator.pageIndex = 0;
            this.#reload();
            this.ref.detectChanges();
            this.isUploaded = false;
        }
        catch (err) {
            this.notifyService.error(err);
        }
        finally {
            this.loadingService.stop();
        }
    };
    #validate = async (excelItem, idx) => {
        const { data: item, meta: { error, errorMessages }, } = excelItem;
        const { validateItem } = this.option;
        for (const column of this.option.columns) {
            if (!this.columnHiddenPipe.transform(column)) {
                continue;
            }
            try {
                if (column.defaultValue !== undefined) {
                    item[column.field] = item[column.field] ?? column.defaultValue;
                }
                else if (column.required && !item[column.field] && item[column.field] !== 0) {
                    error[column.field] = `Dữ liệu bắt buộc`;
                    errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                    continue;
                }
                if (column.type === 'string') {
                    const value = (item[column.field] || '').toString();
                    if (column.minlength !== undefined && value.length < column.minlength) {
                        error[column.field] = `Độ dài chuỗi tối thiểu: ${column.minlength}`;
                        errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                        continue;
                    }
                    if (column.maxlength !== undefined && value.length > column.maxlength) {
                        error[column.field] = `Độ dài chuỗi tối đa: ${column.maxlength}`;
                        errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                        continue;
                    }
                    item[column.field] = value;
                }
                else if (column.type === 'number') {
                    if (item[column.field]) {
                        const value = +item[column.field];
                        if (!NumberUtilities.isNumber(item[column.field])) {
                            error[column.field] = `${item[column.field]} không phải số hợp lệ`;
                            errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                            continue;
                        }
                        item[column.field] = value;
                    }
                    if (!item[column.field] && item[column.field] !== 0) {
                        item[column.field] = undefined;
                    }
                    if (column.min !== undefined && item[column.field] < column.min) {
                        error[column.field] = `${item[column.field]} không thỏa giá trị tối thiểu: ${column.min}`;
                        errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                        continue;
                    }
                    if (column.max !== undefined && item[column.field] > column.max) {
                        error[column.field] = `${item[column.field]} không thỏa giá trị tối đa: ${column.max}`;
                        errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                        continue;
                    }
                }
                else if (column.type === 'bool') {
                    if (item[column.field] === 0 ||
                        item[column.field] === '0' ||
                        item[column.field] === false ||
                        item[column.field]?.toString()?.toLowerCase()?.trim() === 'false') {
                        item[column.field] = false;
                    }
                    else if (item[column.field] === 1 ||
                        item[column.field] === '1' ||
                        item[column.field] === true ||
                        item[column.field]?.toString()?.toLowerCase()?.trim() === 'true') {
                        item[column.field] = true;
                    }
                    else if (item[column.field] === '')
                        item[column.field] = undefined;
                    if (typeof item[column.field] !== 'boolean' && item[column.field] !== undefined && item[column.field] !== null) {
                        error[column.field] = `Vui lòng nhập giá trị hợp lệ true, false, 1, 0`;
                        errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                    }
                }
                else if (column.type === 'values') {
                    if (item[column.field] && typeof item[column.field] !== 'number' && typeof item[column.field] !== 'string') {
                        error[column.field] = `Giá trị ${item[column.field]} không hợp lệ`;
                        errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                        continue;
                    }
                    if (column.checkValueInArray && item[column.field] && !column.values.some(e => e.toString() === item[column.field].toString())) {
                        error[column.field] = `Giá trị ${item[column.field]} không thuộc danh sách cho phép [${column.values.join()}]`;
                        errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                        continue;
                    }
                }
                else if (column.type === 'date' || column.type === 'datetime' || column.type === 'time') {
                    const { type, format } = column;
                    const val = item[column.field];
                    if (val instanceof Date) {
                        item[column.field] = val.toISOString();
                        continue;
                    }
                    if (format && item[column.field]) {
                        if (typeof val !== 'string') {
                            error[column.field] = `Ngày ${val} không đúng định dạng ${column.format}`;
                            errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                            continue;
                        }
                        if (type === 'date' && !this.#isValidDate(format, val)) {
                            error[column.field] = `Ngày ${val} không đúng định dạng ${column.format}`;
                            errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                            continue;
                        }
                        if (type === 'time' && !this.#isValidTime(format, val)) {
                            error[column.field] = `Ngày ${val} không đúng định dạng ${column.format}`;
                            errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                            continue;
                        }
                        if (type === 'datetime' && !this.#isValidDateTime(format, val)) {
                            error[column.field] = `Ngày ${val} không đúng định dạng ${column.format}`;
                            errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                            continue;
                        }
                        item[column.field] = DateUtilities.parseFrom(val, format);
                    }
                    if (item[column.field] && !DateUtilities.isDate(item[column.field])) {
                        error[column.field] = `Ngày ${val} không đúng định dạng ${column.format}`;
                        errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                        continue;
                    }
                }
                // Nếu pass validation từng column, kiểm tra validation theo hàm validateItem
                if (!errorMessages.length && validateItem) {
                    const validation = await validateItem(item, idx, this.excelItems.map(e => e.data));
                    if (validation.errorMessage)
                        excelItem.meta.errorMessages.push(validation.errorMessage);
                    if (validation.warningMessage)
                        excelItem.meta.warningMessages.push(validation.warningMessage);
                }
            }
            catch (ex) {
                error[column.field] = `${ex?.message || ex?.error || ex || 'Có lỗi xảy ra'}`;
                errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
            }
        }
    };
    #mapItem = (item) => {
        const { data } = item;
        return data;
    };
    accept = () => {
        this.option.accept(this.excelItems.map(e => e.data), { file: this.file });
        this.isUploaded = true;
    };
    setValidation = (validations) => {
        this.excelItems.forEach(e => {
            e.meta.errorMessages = [];
            e.meta.warningMessages = [];
        });
        if (Array.isArray(validations)) {
            validations.forEach(validation => {
                if (validation.errorMessage) {
                    this.excelItems[validation.idx].meta.errorMessages = [validation.errorMessage];
                }
                if (validation.warningMessage) {
                    this.excelItems[validation.idx].meta.warningMessages = [validation.warningMessage];
                }
            });
        }
        this.#reload();
        this.ref.detectChanges();
    };
    view = (showing = 'ALL') => {
        this.showing = showing;
        this.#paginator.pageIndex = 0;
        this.#reload();
    };
    downloadTemplate = async () => {
        const sheets = [];
        if (Array.isArray(this.option?.sheets)) {
            for (const sheet of this.option.sheets) {
                if (sheet.name && sheet.items && sheet.headers) {
                    if (Array.isArray(sheet.items)) {
                        sheets.push({
                            name: sheet.name,
                            items: sheet.items,
                            headers: sheet.headers,
                        });
                    }
                    else {
                        sheets.push({
                            name: sheet.name,
                            items: await sheet.items(),
                            headers: sheet.headers,
                        });
                    }
                }
            }
        }
        const columnNotHiddens = this.option.columns.filter(column => this.columnHiddenPipe.transform(column));
        const excelTemplate = {
            fileName: this.option.fileName || 'Template',
            columns: columnNotHiddens.map(column => {
                return {
                    field: column.field,
                    title: column.title,
                    width: column.width,
                    required: column.required,
                    description: column.description,
                    fontColor: column.fontColor,
                    fill: column.fill,
                };
            }),
            sheets,
        };
        this.isDownloadTemplate = true;
        await this.excelService.generateTemplate(excelTemplate).finally(() => {
            this.isDownloadTemplate = false;
        });
    };
    export = async () => {
        this.loadingService.start();
        const columns = [
            {
                field: 'sdMessage',
                title: 'Thông báo',
                width: '250px',
                required: false,
            },
            ...this.option.columns.filter(column => this.columnHiddenPipe.transform(column)),
        ];
        await this.excelService
            .export({
            columns,
            items: this.filteredItems.map(e => {
                let result = {};
                for (const column of columns) {
                    result = {
                        ...result,
                        [column.field]: e.meta.origin?.[column.field],
                    };
                }
                return {
                    ...result,
                    sdMessage: (e.meta.errorMessages.join(', ') || e.meta.warningMessages.join(', ') || 'Thành công')
                        ?.replace(/<strong>/g, '')
                        .replace(/<\/strong>/g, '')
                        .replace(/<br>/g, '\n'),
                };
            }),
        })
            .finally(this.loadingService.stop);
    };
    #isValidDate = (format, value) => {
        if (value?.length !== format?.length) {
            return false;
        }
        const regex = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;
        return regex.test(value);
    };
    #isValidTime = (format, value) => {
        if (value?.length !== format?.length) {
            return false;
        }
        return true;
    };
    #isValidDateTime = (format, value) => {
        if (value?.length !== format?.length) {
            return false;
        }
        const dates = value?.split(' ');
        if (dates.length !== 2) {
            return false;
        }
        const date = dates[0];
        if (!this.#isValidDate('dd/MM/yyyy', date)) {
            return false;
        }
        const time = dates[1];
        const regex = /^(0[0-9]|1[0-9]|2[0-3])(\:)(0[0-9]|[0-5][0-9])$/;
        return regex.test(time);
    };
    onClosed = () => {
        this.sdClosed.emit();
    };
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdImportExcel, deps: [{ token: i0.ChangeDetectorRef }, { token: i1$1.SdExcelService }, { token: i2.SdNotifyService }, { token: ColumnHiddenPipe }, { token: i4.SdLoadingService }], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.17", type: SdImportExcel, isStandalone: true, selector: "sd-import-excel", inputs: { option: "option" }, outputs: { sdClosed: "sdClosed" }, providers: [
            ColumnHiddenPipe
        ], viewQueries: [{ propertyName: "modal", first: true, predicate: SdModal, descendants: true }, { propertyName: "paginator", first: true, predicate: MatPaginator, descendants: true }], ngImport: i0, template: "@if (option) {\r\n  <sd-modal [title]=\"option.title || 'Nh\u1EADp d\u1EEF li\u1EC7u Excel'\" (sdClosed)=\"onClosed()\" #modal>\r\n    <div class=\"row mx-0 mb-3 align-items-center\" style=\"min-height: 32px\">\r\n      @if (excelItems.length) {\r\n        <div class=\"d-flex\">\r\n          <sd-button class=\"mr-2\" (click)=\"view('ALL')\" icon=\"cached\" title=\"Xem t\u1EA5t c\u1EA3\" size=\"sm\" type=\"outline\"></sd-button>\r\n\r\n          <sd-button\r\n            class=\"mr-2\"\r\n            (click)=\"view('SUCCESS')\"\r\n            icon=\"done\"\r\n            title=\"{{ numberOfSuccess }}\"\r\n            tooltip=\"S\u1ED1 d\u00F2ng d\u1EEF li\u1EC7u h\u1EE3p l\u1EC7\"\r\n            size=\"sm\"\r\n            color=\"success\">\r\n          </sd-button>\r\n\r\n          <sd-button\r\n            class=\"mr-2\"\r\n            (click)=\"view('WARNING')\"\r\n            icon=\"warning\"\r\n            title=\"{{ numberOfWarning }}\"\r\n            tooltip=\"S\u1ED1 d\u00F2ng d\u1EEF li\u1EC7u c\u00F3 l\u1ED7i\"\r\n            size=\"sm\"\r\n            color=\"warning\">\r\n          </sd-button>\r\n\r\n          <sd-button\r\n            (click)=\"view('ERROR')\"\r\n            icon=\"error\"\r\n            title=\"{{ numberOfError }}\"\r\n            color=\"error\"\r\n            tooltip=\"S\u1ED1 d\u00F2ng d\u1EEF li\u1EC7u c\u00F3 c\u1EA3nh b\u00E1o\"\r\n            size=\"sm\">\r\n          </sd-button>\r\n        </div>\r\n      }\r\n    </div>\r\n\r\n    <div class=\"sd-box border rounded\">\r\n      <div class=\"sd-box-body p-0\">\r\n        <div class=\"table-responsive\">\r\n          <table class=\"table table-striped table-sm table-hover table-bordered mb-0\">\r\n            <thead class=\"thead-light\">\r\n              <tr>\r\n                <th class=\"text-center c-sticky-left\" style=\"width: 50px\">#</th>\r\n                @if (filteredItems.length) {\r\n                  <th class=\"text-center\" style=\"min-width: 250px; width: 250px\">Tr\u1EA1ng th\u00E1i</th>\r\n                }\r\n                @for (column of option.columns; track column.field) {\r\n                  @if (column | columnHidden) {\r\n                    <th [ngStyle]=\"{ 'min-width': column.width || '300px', width: column.width || '300px' }\" [matTooltip]=\"column.title\">\r\n                      <span class=\"c-ellipsis\">\r\n                        {{ column.title }}\r\n                      </span>\r\n                    </th>\r\n                  }\r\n                }\r\n              </tr>\r\n            </thead>\r\n\r\n            <tbody>\r\n              @if (viewItems.length) {\r\n                @for (item of viewItems; track item.meta.excelIndex) {\r\n                  <tr>\r\n                    <td class=\"text-center c-sticky-left px-4\">\r\n                      <sd-badge\r\n                        type=\"tag\"\r\n                        [title]=\"item.meta.excelIndex\"\r\n                        [success]=\"!item.meta.warningMessages.length && !item.meta.errorMessages.length\"\r\n                        [warning]=\"!!item.meta.warningMessages.length && !item.meta.errorMessages.length\"\r\n                        [error]=\"!!item.meta.errorMessages.length\" />\r\n                    </td>\r\n\r\n                    <td style=\"min-width: 250px; width: 250px\">\r\n                      <div\r\n                        class=\"text-wrap\"\r\n                        [innerHTML]=\"\r\n                          item.meta.errorMessages[0] || item.meta.warningMessages[0] || '<span class=\\'text-success\\'>D\u1EEF li\u1EC7u h\u1EE3p l\u1EC7</span>'\r\n                        \"></div>\r\n                    </td>\r\n\r\n                    @for (column of option.columns; track column.field) {\r\n                      @if (column | columnHidden) {\r\n                        <td\r\n                          class=\"align-middle\"\r\n                          [ngClass]=\"{\r\n                            'bg-warning-light': item.meta.warning[column.field] && !item.meta.error[column.field],\r\n                            'bg-error-light': item.meta.error[column.field]\r\n                          }\"\r\n                          [matTooltip]=\"item.meta.error[column.field] || item.meta.warning[column.field]\"\r\n                          [ngStyle]=\"{ 'min-width': column.width || '300px' }\"\r\n                          matTooltipPosition=\"above\">\r\n                          <div class=\"c-ellipsis\">\r\n                            @if (column.type !== 'array') {\r\n                              <span [innerHTML]=\"item | columnTransform: column | async\"></span>\r\n                            }\r\n\r\n                            @if (column.type === 'array') {\r\n                              @let arrayItems = item.data[column.field]?.split(column.divideString);\r\n\r\n                              <div class=\"d-flex align-items-center justify-content-between\">\r\n                                <span>{{ arrayItems?.length || 0 }} {{ column.unitString }}</span>\r\n\r\n                                @if (arrayItems?.length) {\r\n                                  <button\r\n                                    mat-icon-button\r\n                                    [matMenuTriggerFor]=\"menu\"\r\n                                    class=\"c-mat-menu\"\r\n                                    style=\"width: 24px; height: 24px; line-height: 24px\">\r\n                                    <mat-icon style=\"font-size: 18px\">open_in_new</mat-icon>\r\n                                  </button>\r\n\r\n                                  <mat-menu #menu=\"matMenu\">\r\n                                    <div\r\n                                      class=\"px-3 py-2\"\r\n                                      style=\"max-width: 300px; max-height: 250px; overflow: auto\"\r\n                                      (click)=\"$event.stopPropagation()\"\r\n                                      aria-hidden=\"true\">\r\n                                      @for (val of arrayItems; track $index) {\r\n                                        <div class=\"border-bottom py-2 text-wrap\" [innerHTML]=\"val\"></div>\r\n                                      }\r\n                                    </div>\r\n                                  </mat-menu>\r\n                                }\r\n                              </div>\r\n                            }\r\n                          </div>\r\n                        </td>\r\n                      }\r\n                    }\r\n                  </tr>\r\n                }\r\n              } @else {\r\n                <tr>\r\n                  <td [attr.colspan]=\"option.columns.length + 2\" class=\"p-0 border-0 bg-white\">\r\n                    <div\r\n                      class=\"empty-state-wrapper\"\r\n                      (click)=\"downloadTemplate()\"\r\n                      matTooltip=\"Nh\u1EA5n \u0111\u1EC3 t\u1EA3i t\u1EC7p m\u1EABu v\u1EC1 m\u00E1y\"\r\n                      aria-hidden=\"true\">\r\n                      <mat-icon class=\"empty-icon\">cloud_download</mat-icon>\r\n\r\n                      <h4>Ch\u01B0a c\u00F3 d\u1EEF li\u1EC7u t\u1EA3i l\u00EAn</h4>\r\n                      <span class=\"text-small text-link\"> Nh\u1EA5n v\u00E0o \u0111\u00E2y \u0111\u1EC3 t\u1EA3i t\u1EC7p m\u1EABu </span>\r\n\r\n                      @if (isDownloadTemplate) {\r\n                        <div class=\"mt-3\">\r\n                          <mat-spinner diameter=\"24\" mode=\"indeterminate\"></mat-spinner>\r\n                        </div>\r\n                      }\r\n                    </div>\r\n                  </td>\r\n                </tr>\r\n              }\r\n            </tbody>\r\n          </table>\r\n        </div>\r\n      </div>\r\n\r\n      <div class=\"sd-box-footer border-top\">\r\n        <div class=\"d-flex align-items-center justify-content-end\">\r\n          <mat-paginator [length]=\"filteredItems.length || 0\" hidePageSize showFirstLastButtons></mat-paginator>\r\n        </div>\r\n      </div>\r\n    </div>\r\n    <sd-button sdFooterLeft (click)=\"upload()\" prefixIcon=\"file_upload\" title=\"T\u1EA3i l\u00EAn\" size=\"sm\" color=\"info\" [loading]=\"uploading\">\r\n    </sd-button>\r\n    <div class=\"d-flex align-items-center\" sdFooter>\r\n      @if (filteredItems.length) {\r\n        <sd-button class=\"mr-4\" (click)=\"export()\" prefixIcon=\"get_app\" title=\"T\u1EA3i v\u1EC1\" size=\"sm\" color=\"success\" type=\"outline\">\r\n        </sd-button>\r\n      }\r\n      <sd-button\r\n        (click)=\"accept()\"\r\n        title=\"X\u00E1c nh\u1EADn & L\u01B0u\"\r\n        [disabled]=\"(numberOfSuccess === 0 && numberOfWarning === 0) || numberOfError > 0 || isUploaded\"\r\n        color=\"primary\"\r\n        type=\"fill\"\r\n        size=\"sm\">\r\n      </sd-button>\r\n    </div>\r\n  </sd-modal>\r\n}\r\n", styles: [".table-responsive{position:relative;min-height:50vh;height:50vh;overflow:auto;border:1px solid #dee2e6}.table{margin-bottom:0}.table thead th{position:sticky;top:0;background-color:#f8f9fa;border-bottom:2px solid #dee2e6;padding-top:8px;padding-bottom:8px;white-space:nowrap;z-index:10}.table thead th.c-sticky-left{z-index:20}.table tbody td{vertical-align:middle;padding-top:6px;padding-bottom:6px}.c-sticky-left{position:sticky;left:0;border-right:1px solid #dee2e6!important;border-left:none!important;z-index:5}.table-striped tbody tr:nth-of-type(odd) .c-sticky-left{background-color:#f2f2f2}.table-striped tbody tr:nth-of-type(2n) .c-sticky-left{background-color:#fff}.table-hover tbody tr:hover .c-sticky-left{background-color:#ececec}.table-striped tbody tr:nth-of-type(odd){background-color:#0000000d}.table-striped tbody tr:nth-of-type(2n){background-color:#fff}.empty-state-wrapper{height:100%;min-height:40vh;display:flex;flex-direction:column;align-items:center;justify-content:center;cursor:pointer;background-color:#f8f9fa;border:2px dashed #cbd5e0;border-radius:8px;margin:16px;transition:all .2s ease-in-out;color:#6c757d}.empty-state-wrapper:hover{background-color:#e3f2fd;border-color:#2196f3;color:#1976d2}.empty-state-wrapper:hover .empty-icon{transform:scale(1.1);color:#1976d2}.empty-state-wrapper:hover .text-link{text-decoration:underline}.empty-state-wrapper .empty-icon{font-size:64px;height:64px;width:64px;margin-bottom:16px;color:#a0aec0;transition:transform .2s}.empty-state-wrapper h4{font-weight:500;margin-bottom:4px}.c-ellipsis{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;padding:0 4px}.c-mat-menu{border:none;min-width:unset;padding:0 8px}.c-mat-menu mat-icon{font-size:18px;width:18px;height:18px;line-height:18px;vertical-align:middle}.cursor-pointer{cursor:pointer}:host ::ng-deep .mat-paginator-container{min-height:36px;height:36px;padding:0 8px}:host ::ng-deep .mat-paginator-range-label{margin:0 10px}:host ::ng-deep .mat-icon-button{width:32px;height:32px;line-height:32px}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i5.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i5.NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }, { kind: "pipe", type: i5.AsyncPipe, name: "async" }, { kind: "ngmodule", type: FormsModule }, { kind: "ngmodule", type: MatSlideToggleModule }, { kind: "ngmodule", type: MatTooltipModule }, { kind: "directive", type: i6.MatTooltip, selector: "[matTooltip]", inputs: ["matTooltipPosition", "matTooltipPositionAtOrigin", "matTooltipDisabled", "matTooltipShowDelay", "matTooltipHideDelay", "matTooltipTouchGestures", "matTooltip", "matTooltipClass"], exportAs: ["matTooltip"] }, { kind: "ngmodule", type: MatPaginatorModule }, { kind: "component", type: i7.MatPaginator, selector: "mat-paginator", inputs: ["color", "pageIndex", "length", "pageSize", "pageSizeOptions", "hidePageSize", "showFirstLastButtons", "selectConfig", "disabled"], outputs: ["page"], exportAs: ["matPaginator"] }, { kind: "component", type: SdButton, selector: "sd-button", inputs: ["autoId", "type", "color", "title", "width", "size", "tooltip", "prefixIcon", "suffixIcon", "fontSet", "disabled", "loading"], outputs: ["click"] }, { kind: "component", type: SdModal, selector: "sd-modal", inputs: ["title", "color", "width", "height", "view", "lazyLoadContent"], outputs: ["sdClosed"] }, { kind: "pipe", type: ColumnTransformPipe, name: "columnTransform" }, { kind: "pipe", type: ColumnHiddenPipe, name: "columnHidden" }, { kind: "ngmodule", type: MatIconModule }, { kind: "component", type: i8.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "ngmodule", type: MatMenuModule }, { kind: "component", type: i9.MatMenu, selector: "mat-menu", inputs: ["backdropClass", "aria-label", "aria-labelledby", "aria-describedby", "xPosition", "yPosition", "overlapTrigger", "hasBackdrop", "class", "classList"], outputs: ["closed", "close"], exportAs: ["matMenu"] }, { kind: "directive", type: i9.MatMenuTrigger, selector: "[mat-menu-trigger-for], [matMenuTriggerFor]", inputs: ["mat-menu-trigger-for", "matMenuTriggerFor", "matMenuTriggerData", "matMenuTriggerRestoreFocus"], outputs: ["menuOpened", "onMenuOpen", "menuClosed", "onMenuClose"], exportAs: ["matMenuTrigger"] }, { kind: "component", type: MatProgressSpinner, selector: "mat-progress-spinner, mat-spinner", inputs: ["color", "mode", "value", "diameter", "strokeWidth"], exportAs: ["matProgressSpinner"] }, { kind: "component", type: SdBadge, selector: "sd-badge", inputs: ["type", "color", "primary", "secondary", "success", "info", "warning", "error", "fontSet", "title", "description", "tooltip", "icon", "size"], outputs: ["sdClick"] }] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdImportExcel, decorators: [{
            type: Component,
            args: [{ selector: 'sd-import-excel', imports: [
                        CommonModule,
                        FormsModule,
                        MatSlideToggleModule,
                        MatTooltipModule,
                        MatPaginatorModule,
                        MatSlideToggleModule,
                        SdButton,
                        SdModal,
                        ColumnTransformPipe,
                        ColumnHiddenPipe,
                        MatIconModule,
                        MatMenuModule,
                        MatProgressSpinner,
                        SdBadge
                    ], providers: [
                        ColumnHiddenPipe
                    ], template: "@if (option) {\r\n  <sd-modal [title]=\"option.title || 'Nh\u1EADp d\u1EEF li\u1EC7u Excel'\" (sdClosed)=\"onClosed()\" #modal>\r\n    <div class=\"row mx-0 mb-3 align-items-center\" style=\"min-height: 32px\">\r\n      @if (excelItems.length) {\r\n        <div class=\"d-flex\">\r\n          <sd-button class=\"mr-2\" (click)=\"view('ALL')\" icon=\"cached\" title=\"Xem t\u1EA5t c\u1EA3\" size=\"sm\" type=\"outline\"></sd-button>\r\n\r\n          <sd-button\r\n            class=\"mr-2\"\r\n            (click)=\"view('SUCCESS')\"\r\n            icon=\"done\"\r\n            title=\"{{ numberOfSuccess }}\"\r\n            tooltip=\"S\u1ED1 d\u00F2ng d\u1EEF li\u1EC7u h\u1EE3p l\u1EC7\"\r\n            size=\"sm\"\r\n            color=\"success\">\r\n          </sd-button>\r\n\r\n          <sd-button\r\n            class=\"mr-2\"\r\n            (click)=\"view('WARNING')\"\r\n            icon=\"warning\"\r\n            title=\"{{ numberOfWarning }}\"\r\n            tooltip=\"S\u1ED1 d\u00F2ng d\u1EEF li\u1EC7u c\u00F3 l\u1ED7i\"\r\n            size=\"sm\"\r\n            color=\"warning\">\r\n          </sd-button>\r\n\r\n          <sd-button\r\n            (click)=\"view('ERROR')\"\r\n            icon=\"error\"\r\n            title=\"{{ numberOfError }}\"\r\n            color=\"error\"\r\n            tooltip=\"S\u1ED1 d\u00F2ng d\u1EEF li\u1EC7u c\u00F3 c\u1EA3nh b\u00E1o\"\r\n            size=\"sm\">\r\n          </sd-button>\r\n        </div>\r\n      }\r\n    </div>\r\n\r\n    <div class=\"sd-box border rounded\">\r\n      <div class=\"sd-box-body p-0\">\r\n        <div class=\"table-responsive\">\r\n          <table class=\"table table-striped table-sm table-hover table-bordered mb-0\">\r\n            <thead class=\"thead-light\">\r\n              <tr>\r\n                <th class=\"text-center c-sticky-left\" style=\"width: 50px\">#</th>\r\n                @if (filteredItems.length) {\r\n                  <th class=\"text-center\" style=\"min-width: 250px; width: 250px\">Tr\u1EA1ng th\u00E1i</th>\r\n                }\r\n                @for (column of option.columns; track column.field) {\r\n                  @if (column | columnHidden) {\r\n                    <th [ngStyle]=\"{ 'min-width': column.width || '300px', width: column.width || '300px' }\" [matTooltip]=\"column.title\">\r\n                      <span class=\"c-ellipsis\">\r\n                        {{ column.title }}\r\n                      </span>\r\n                    </th>\r\n                  }\r\n                }\r\n              </tr>\r\n            </thead>\r\n\r\n            <tbody>\r\n              @if (viewItems.length) {\r\n                @for (item of viewItems; track item.meta.excelIndex) {\r\n                  <tr>\r\n                    <td class=\"text-center c-sticky-left px-4\">\r\n                      <sd-badge\r\n                        type=\"tag\"\r\n                        [title]=\"item.meta.excelIndex\"\r\n                        [success]=\"!item.meta.warningMessages.length && !item.meta.errorMessages.length\"\r\n                        [warning]=\"!!item.meta.warningMessages.length && !item.meta.errorMessages.length\"\r\n                        [error]=\"!!item.meta.errorMessages.length\" />\r\n                    </td>\r\n\r\n                    <td style=\"min-width: 250px; width: 250px\">\r\n                      <div\r\n                        class=\"text-wrap\"\r\n                        [innerHTML]=\"\r\n                          item.meta.errorMessages[0] || item.meta.warningMessages[0] || '<span class=\\'text-success\\'>D\u1EEF li\u1EC7u h\u1EE3p l\u1EC7</span>'\r\n                        \"></div>\r\n                    </td>\r\n\r\n                    @for (column of option.columns; track column.field) {\r\n                      @if (column | columnHidden) {\r\n                        <td\r\n                          class=\"align-middle\"\r\n                          [ngClass]=\"{\r\n                            'bg-warning-light': item.meta.warning[column.field] && !item.meta.error[column.field],\r\n                            'bg-error-light': item.meta.error[column.field]\r\n                          }\"\r\n                          [matTooltip]=\"item.meta.error[column.field] || item.meta.warning[column.field]\"\r\n                          [ngStyle]=\"{ 'min-width': column.width || '300px' }\"\r\n                          matTooltipPosition=\"above\">\r\n                          <div class=\"c-ellipsis\">\r\n                            @if (column.type !== 'array') {\r\n                              <span [innerHTML]=\"item | columnTransform: column | async\"></span>\r\n                            }\r\n\r\n                            @if (column.type === 'array') {\r\n                              @let arrayItems = item.data[column.field]?.split(column.divideString);\r\n\r\n                              <div class=\"d-flex align-items-center justify-content-between\">\r\n                                <span>{{ arrayItems?.length || 0 }} {{ column.unitString }}</span>\r\n\r\n                                @if (arrayItems?.length) {\r\n                                  <button\r\n                                    mat-icon-button\r\n                                    [matMenuTriggerFor]=\"menu\"\r\n                                    class=\"c-mat-menu\"\r\n                                    style=\"width: 24px; height: 24px; line-height: 24px\">\r\n                                    <mat-icon style=\"font-size: 18px\">open_in_new</mat-icon>\r\n                                  </button>\r\n\r\n                                  <mat-menu #menu=\"matMenu\">\r\n                                    <div\r\n                                      class=\"px-3 py-2\"\r\n                                      style=\"max-width: 300px; max-height: 250px; overflow: auto\"\r\n                                      (click)=\"$event.stopPropagation()\"\r\n                                      aria-hidden=\"true\">\r\n                                      @for (val of arrayItems; track $index) {\r\n                                        <div class=\"border-bottom py-2 text-wrap\" [innerHTML]=\"val\"></div>\r\n                                      }\r\n                                    </div>\r\n                                  </mat-menu>\r\n                                }\r\n                              </div>\r\n                            }\r\n                          </div>\r\n                        </td>\r\n                      }\r\n                    }\r\n                  </tr>\r\n                }\r\n              } @else {\r\n                <tr>\r\n                  <td [attr.colspan]=\"option.columns.length + 2\" class=\"p-0 border-0 bg-white\">\r\n                    <div\r\n                      class=\"empty-state-wrapper\"\r\n                      (click)=\"downloadTemplate()\"\r\n                      matTooltip=\"Nh\u1EA5n \u0111\u1EC3 t\u1EA3i t\u1EC7p m\u1EABu v\u1EC1 m\u00E1y\"\r\n                      aria-hidden=\"true\">\r\n                      <mat-icon class=\"empty-icon\">cloud_download</mat-icon>\r\n\r\n                      <h4>Ch\u01B0a c\u00F3 d\u1EEF li\u1EC7u t\u1EA3i l\u00EAn</h4>\r\n                      <span class=\"text-small text-link\"> Nh\u1EA5n v\u00E0o \u0111\u00E2y \u0111\u1EC3 t\u1EA3i t\u1EC7p m\u1EABu </span>\r\n\r\n                      @if (isDownloadTemplate) {\r\n                        <div class=\"mt-3\">\r\n                          <mat-spinner diameter=\"24\" mode=\"indeterminate\"></mat-spinner>\r\n                        </div>\r\n                      }\r\n                    </div>\r\n                  </td>\r\n                </tr>\r\n              }\r\n            </tbody>\r\n          </table>\r\n        </div>\r\n      </div>\r\n\r\n      <div class=\"sd-box-footer border-top\">\r\n        <div class=\"d-flex align-items-center justify-content-end\">\r\n          <mat-paginator [length]=\"filteredItems.length || 0\" hidePageSize showFirstLastButtons></mat-paginator>\r\n        </div>\r\n      </div>\r\n    </div>\r\n    <sd-button sdFooterLeft (click)=\"upload()\" prefixIcon=\"file_upload\" title=\"T\u1EA3i l\u00EAn\" size=\"sm\" color=\"info\" [loading]=\"uploading\">\r\n    </sd-button>\r\n    <div class=\"d-flex align-items-center\" sdFooter>\r\n      @if (filteredItems.length) {\r\n        <sd-button class=\"mr-4\" (click)=\"export()\" prefixIcon=\"get_app\" title=\"T\u1EA3i v\u1EC1\" size=\"sm\" color=\"success\" type=\"outline\">\r\n        </sd-button>\r\n      }\r\n      <sd-button\r\n        (click)=\"accept()\"\r\n        title=\"X\u00E1c nh\u1EADn & L\u01B0u\"\r\n        [disabled]=\"(numberOfSuccess === 0 && numberOfWarning === 0) || numberOfError > 0 || isUploaded\"\r\n        color=\"primary\"\r\n        type=\"fill\"\r\n        size=\"sm\">\r\n      </sd-button>\r\n    </div>\r\n  </sd-modal>\r\n}\r\n", styles: [".table-responsive{position:relative;min-height:50vh;height:50vh;overflow:auto;border:1px solid #dee2e6}.table{margin-bottom:0}.table thead th{position:sticky;top:0;background-color:#f8f9fa;border-bottom:2px solid #dee2e6;padding-top:8px;padding-bottom:8px;white-space:nowrap;z-index:10}.table thead th.c-sticky-left{z-index:20}.table tbody td{vertical-align:middle;padding-top:6px;padding-bottom:6px}.c-sticky-left{position:sticky;left:0;border-right:1px solid #dee2e6!important;border-left:none!important;z-index:5}.table-striped tbody tr:nth-of-type(odd) .c-sticky-left{background-color:#f2f2f2}.table-striped tbody tr:nth-of-type(2n) .c-sticky-left{background-color:#fff}.table-hover tbody tr:hover .c-sticky-left{background-color:#ececec}.table-striped tbody tr:nth-of-type(odd){background-color:#0000000d}.table-striped tbody tr:nth-of-type(2n){background-color:#fff}.empty-state-wrapper{height:100%;min-height:40vh;display:flex;flex-direction:column;align-items:center;justify-content:center;cursor:pointer;background-color:#f8f9fa;border:2px dashed #cbd5e0;border-radius:8px;margin:16px;transition:all .2s ease-in-out;color:#6c757d}.empty-state-wrapper:hover{background-color:#e3f2fd;border-color:#2196f3;color:#1976d2}.empty-state-wrapper:hover .empty-icon{transform:scale(1.1);color:#1976d2}.empty-state-wrapper:hover .text-link{text-decoration:underline}.empty-state-wrapper .empty-icon{font-size:64px;height:64px;width:64px;margin-bottom:16px;color:#a0aec0;transition:transform .2s}.empty-state-wrapper h4{font-weight:500;margin-bottom:4px}.c-ellipsis{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;padding:0 4px}.c-mat-menu{border:none;min-width:unset;padding:0 8px}.c-mat-menu mat-icon{font-size:18px;width:18px;height:18px;line-height:18px;vertical-align:middle}.cursor-pointer{cursor:pointer}:host ::ng-deep .mat-paginator-container{min-height:36px;height:36px;padding:0 8px}:host ::ng-deep .mat-paginator-range-label{margin:0 10px}:host ::ng-deep .mat-icon-button{width:32px;height:32px;line-height:32px}\n"] }]
        }], ctorParameters: () => [{ type: i0.ChangeDetectorRef }, { type: i1$1.SdExcelService }, { type: i2.SdNotifyService }, { type: ColumnHiddenPipe }, { type: i4.SdLoadingService }], propDecorators: { option: [{
                type: Input,
                args: [{ required: true }]
            }], modal: [{
                type: ViewChild,
                args: [SdModal]
            }], paginator: [{
                type: ViewChild,
                args: [MatPaginator]
            }], sdClosed: [{
                type: Output
            }] } });

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

export { SdImportExcel };
//# sourceMappingURL=sd-angular-core-components-import-excel.mjs.map
