import * as i0 from '@angular/core';
import { Pipe, Injectable, EventEmitter, inject, 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 '@sdcorejs/angular/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 '@sdcorejs/angular/components/modal';
import { DateUtilities, NumberUtilities } from '@sdcorejs/angular/utilities';
import * as i1 from '@angular/platform-browser';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { SdBadge } from '@sdcorejs/angular/components/badge';
import { I18nService, TranslatePipe } from '@sdcorejs/angular/i18n';
import * as i1$1 from '@sdcorejs/angular/services/excel';
import * as i2 from '@sdcorejs/angular/services/notify';
import * as i4 from '@sdcorejs/angular/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: "20.3.24", ngImport: i0, type: ColumnHiddenPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "20.3.24", ngImport: i0, type: ColumnHiddenPipe, isStandalone: true, name: "columnHidden" });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.24", ngImport: i0, type: ColumnHiddenPipe });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.24", 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: "20.3.24", ngImport: i0, type: ColumnTransformPipe, deps: [{ token: i1.DomSanitizer }], target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "20.3.24", ngImport: i0, type: ColumnTransformPipe, isStandalone: true, name: "columnTransform" });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.24", 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();
    #i18n = inject(I18nService);
    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(this.#i18n.t('core.component.import-excel.no-data-in-file'));
                return;
            }
            const limit = this.option.limit || 1000;
            if (items.length > limit) {
                this.notifyService.warning(this.#i18n.t('core.component.import-excel.row-limit', { limit }));
                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] = this.#i18n.t('core.component.import-excel.required');
                    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] = this.#i18n.t('core.component.import-excel.min-length', { min: 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] = this.#i18n.t('core.component.import-excel.max-length', { max: 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] = this.#i18n.t('core.component.import-excel.not-a-number', { value: item[column.field] });
                            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] = this.#i18n.t('core.component.import-excel.below-min', { value: item[column.field], min: 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] = this.#i18n.t('core.component.import-excel.above-max', { value: item[column.field], max: 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] = this.#i18n.t('core.component.import-excel.invalid-bool');
                        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] = this.#i18n.t('core.component.import-excel.invalid-value', { value: item[column.field] });
                        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] = this.#i18n.t('core.component.import-excel.value-not-in-list', { value: item[column.field], list: 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] = this.#i18n.t('core.component.import-excel.invalid-date-format', { value: val ?? '', format: column.format ?? '' });
                            errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                            continue;
                        }
                        if (type === 'date' && !this.#isValidDate(format, val)) {
                            error[column.field] = this.#i18n.t('core.component.import-excel.invalid-date-format', { value: val ?? '', format: column.format ?? '' });
                            errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                            continue;
                        }
                        if (type === 'time' && !this.#isValidTime(format, val)) {
                            error[column.field] = this.#i18n.t('core.component.import-excel.invalid-date-format', { value: val ?? '', format: column.format ?? '' });
                            errorMessages.push(`<strong>[${column.title || column.field}]</strong> ${error[column.field]}`);
                            continue;
                        }
                        if (type === 'datetime' && !this.#isValidDateTime(format, val)) {
                            error[column.field] = this.#i18n.t('core.component.import-excel.invalid-date-format', { value: val ?? '', format: 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] = this.#i18n.t('core.component.import-excel.invalid-date-format', { value: val ?? '', format: 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 || this.#i18n.t('core.component.import-excel.generic-error')}`;
                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: this.#i18n.t('core.component.import-excel.message-column'),
                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(', ') || this.#i18n.t('core.component.import-excel.success'))
                        ?.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: "20.3.24", 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: "20.3.24", 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) {\n  <sd-modal [title]=\"option.title || ('core.component.import-excel.title' | translate)\" (sdClosed)=\"onClosed()\" #modal>\n    <div class=\"d-flex align-items-center mb-12\" style=\"min-height: 32px\">\n      @if (excelItems.length) {\n        <div class=\"d-flex\">\n          <sd-button class=\"mr-2\" (click)=\"view('ALL')\" icon=\"cached\" [title]=\"'core.component.import-excel.see-all' | translate\" size=\"sm\" type=\"outline\"></sd-button>\n\n          <sd-button\n            class=\"mr-2\"\n            (click)=\"view('SUCCESS')\"\n            icon=\"done\"\n            title=\"{{ numberOfSuccess }}\"\n            [tooltip]=\"'core.component.import-excel.valid-rows' | translate\"\n            size=\"sm\"\n            color=\"success\">\n          </sd-button>\n\n          <sd-button\n            class=\"mr-2\"\n            (click)=\"view('WARNING')\"\n            icon=\"warning\"\n            title=\"{{ numberOfWarning }}\"\n            [tooltip]=\"'core.component.import-excel.error-rows' | translate\"\n            size=\"sm\"\n            color=\"warning\">\n          </sd-button>\n\n          <sd-button\n            (click)=\"view('ERROR')\"\n            icon=\"error\"\n            title=\"{{ numberOfError }}\"\n            color=\"error\"\n            [tooltip]=\"'core.component.import-excel.warning-rows' | translate\"\n            size=\"sm\">\n          </sd-button>\n        </div>\n      }\n    </div>\n\n    <div class=\"sd-box border rounded\">\n      <div class=\"sd-box-body p-0\">\n        <div class=\"table-responsive\">\n          <table class=\"sd-table\">\n            <thead>\n              <tr>\n                <th class=\"text-center c-sticky-left\" style=\"width: 50px\">#</th>\n                @if (filteredItems.length) {\n                  <th class=\"text-center\" style=\"min-width: 250px; width: 250px\">{{ 'core.component.import-excel.status' | translate }}</th>\n                }\n                @for (column of option.columns; track column.field) {\n                  @if (column | columnHidden) {\n                    <th [ngStyle]=\"{ 'min-width': column.width || '300px', width: column.width || '300px' }\" [matTooltip]=\"column.title\">\n                      <span class=\"c-ellipsis\">\n                        {{ column.title }}\n                      </span>\n                    </th>\n                  }\n                }\n              </tr>\n            </thead>\n\n            <tbody>\n              @if (viewItems.length) {\n                @for (item of viewItems; track item.meta.excelIndex) {\n                  <tr>\n                    <td class=\"text-center c-sticky-left px-4\">\n                      <sd-badge\n                        type=\"tag\"\n                        [title]=\"item.meta.excelIndex\"\n                        [success]=\"!item.meta.warningMessages.length && !item.meta.errorMessages.length\"\n                        [warning]=\"!!item.meta.warningMessages.length && !item.meta.errorMessages.length\"\n                        [error]=\"!!item.meta.errorMessages.length\" />\n                    </td>\n\n                    <td style=\"min-width: 250px; width: 250px\">\n                      <div\n                        class=\"text-wrap\"\n                        [innerHTML]=\"\n                          item.meta.errorMessages[0] || item.meta.warningMessages[0] || ('<span class=\\'text-success\\'>' + ('core.component.import-excel.valid-data' | translate) + '</span>')\n                        \"></div>\n                    </td>\n\n                    @for (column of option.columns; track column.field) {\n                      @if (column | columnHidden) {\n                        <td\n                          class=\"align-middle\"\n                          [ngClass]=\"{\n                            'bg-warning-light': item.meta.warning[column.field] && !item.meta.error[column.field],\n                            'bg-error-light': item.meta.error[column.field]\n                          }\"\n                          [matTooltip]=\"item.meta.error[column.field] || item.meta.warning[column.field]\"\n                          [ngStyle]=\"{ 'min-width': column.width || '300px' }\"\n                          matTooltipPosition=\"above\">\n                          <div class=\"c-ellipsis\">\n                            @if (column.type !== 'array') {\n                              <span [innerHTML]=\"item | columnTransform: column | async\"></span>\n                            }\n\n                            @if (column.type === 'array') {\n                              @let arrayItems = item.data[column.field]?.split(column.divideString);\n\n                              <div class=\"d-flex align-items-center justify-content-between\">\n                                <span>{{ arrayItems?.length || 0 }} {{ column.unitString }}</span>\n\n                                @if (arrayItems?.length) {\n                                  <button\n                                    mat-icon-button\n                                    [matMenuTriggerFor]=\"menu\"\n                                    class=\"c-mat-menu\"\n                                    style=\"width: 24px; height: 24px; line-height: 24px\">\n                                    <mat-icon style=\"font-size: 18px\">open_in_new</mat-icon>\n                                  </button>\n\n                                  <mat-menu #menu=\"matMenu\">\n                                    <div\n                                      class=\"px-3 py-2\"\n                                      style=\"max-width: 300px; max-height: 250px; overflow: auto\"\n                                      (click)=\"$event.stopPropagation()\"\n                                      aria-hidden=\"true\">\n                                      @for (val of arrayItems; track $index) {\n                                        <div class=\"border-bottom py-2 text-wrap\" [innerHTML]=\"val\"></div>\n                                      }\n                                    </div>\n                                  </mat-menu>\n                                }\n                              </div>\n                            }\n                          </div>\n                        </td>\n                      }\n                    }\n                  </tr>\n                }\n              } @else {\n                <tr>\n                  <td [attr.colspan]=\"option.columns.length + 2\" class=\"p-0 border-0 bg-white\">\n                    <div\n                      class=\"empty-state-wrapper\"\n                      (click)=\"downloadTemplate()\"\n                      [matTooltip]=\"'core.component.import-excel.download-template-tooltip' | translate\"\n                      aria-hidden=\"true\">\n                      <mat-icon class=\"empty-icon\">cloud_download</mat-icon>\n\n                      <h4>{{ 'core.component.import-excel.no-data-upload' | translate }}</h4>\n                      <span class=\"text-small text-link\"> {{ 'core.component.import-excel.click-here-template' | translate }} </span>\n\n                      @if (isDownloadTemplate) {\n                        <div class=\"mt-3\">\n                          <mat-spinner diameter=\"24\" mode=\"indeterminate\"></mat-spinner>\n                        </div>\n                      }\n                    </div>\n                  </td>\n                </tr>\n              }\n            </tbody>\n          </table>\n        </div>\n      </div>\n\n      <div class=\"sd-box-footer border-top\">\n        <div class=\"d-flex align-items-center justify-content-end\">\n          <mat-paginator [length]=\"filteredItems.length || 0\" hidePageSize showFirstLastButtons></mat-paginator>\n        </div>\n      </div>\n    </div>\n    <sd-button sdFooterLeft (click)=\"upload()\" prefixIcon=\"file_upload\" [title]=\"'core.component.import-excel.upload' | translate\" size=\"sm\" color=\"info\" [loading]=\"uploading\">\n    </sd-button>\n    <div class=\"d-flex align-items-center\" sdFooter>\n      @if (filteredItems.length) {\n        <sd-button class=\"mr-4\" (click)=\"export()\" prefixIcon=\"get_app\" [title]=\"'core.component.import-excel.download' | translate\" size=\"sm\" color=\"success\" type=\"outline\">\n        </sd-button>\n      }\n      <sd-button\n        (click)=\"accept()\"\n        [title]=\"'core.component.import-excel.confirm-save' | translate\"\n        [disabled]=\"(numberOfSuccess === 0 && numberOfWarning === 0) || numberOfError > 0 || isUploaded\"\n        color=\"primary\"\n        type=\"fill\"\n        size=\"sm\">\n      </sd-button>\n    </div>\n  </sd-modal>\n}\n", styles: [".table-responsive{position:relative;min-height:50vh;height:50vh;overflow:auto;border:1px solid #dee2e6}.sd-table{width:100%;border-collapse:collapse;margin-bottom:0;font-size:14px}.sd-table thead th{position:sticky;top:0;background-color:#f8f9fa;border-bottom:2px solid #dee2e6;border-top:1px solid #dee2e6;padding:8px 6px;white-space:nowrap;z-index:10;font-weight:600}.sd-table thead th.c-sticky-left{z-index:20}.sd-table tbody td{vertical-align:middle;padding:6px;border-top:1px solid #dee2e6}.sd-table tbody tr:nth-of-type(odd){background-color:#0000000a}.sd-table tbody tr:nth-of-type(2n){background-color:#fff}.sd-table tbody tr:hover,.sd-table tbody tr:hover .c-sticky-left{background-color:#ececec}.sd-table tbody tr:nth-of-type(odd) .c-sticky-left{background-color:#f2f2f2}.sd-table tbody tr:nth-of-type(2n) .c-sticky-left{background-color:#fff}.c-sticky-left{position:sticky;left:0;border-right:1px solid #dee2e6!important;border-left:none!important;z-index:5}.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: "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", "size", "fontSet", "title", "width", "tooltip", "prefixIcon", "suffixIcon", "disabled", "loading", "block", "htmlType"], outputs: ["click"] }, { kind: "component", type: SdModal, selector: "sd-modal", inputs: ["autoId", "title", "color", "width", "height", "view", "modalClass", "lazyLoadContent", "hideClose", "disableBackdropClose"], outputs: ["sdClosed"] }, { 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: ["click"] }, { kind: "pipe", type: i5.AsyncPipe, name: "async" }, { kind: "pipe", type: ColumnTransformPipe, name: "columnTransform" }, { kind: "pipe", type: ColumnHiddenPipe, name: "columnHidden" }, { kind: "pipe", type: TranslatePipe, name: "translate" }] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.24", 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, TranslatePipe
                    ], providers: [
                        ColumnHiddenPipe
                    ], template: "@if (option) {\n  <sd-modal [title]=\"option.title || ('core.component.import-excel.title' | translate)\" (sdClosed)=\"onClosed()\" #modal>\n    <div class=\"d-flex align-items-center mb-12\" style=\"min-height: 32px\">\n      @if (excelItems.length) {\n        <div class=\"d-flex\">\n          <sd-button class=\"mr-2\" (click)=\"view('ALL')\" icon=\"cached\" [title]=\"'core.component.import-excel.see-all' | translate\" size=\"sm\" type=\"outline\"></sd-button>\n\n          <sd-button\n            class=\"mr-2\"\n            (click)=\"view('SUCCESS')\"\n            icon=\"done\"\n            title=\"{{ numberOfSuccess }}\"\n            [tooltip]=\"'core.component.import-excel.valid-rows' | translate\"\n            size=\"sm\"\n            color=\"success\">\n          </sd-button>\n\n          <sd-button\n            class=\"mr-2\"\n            (click)=\"view('WARNING')\"\n            icon=\"warning\"\n            title=\"{{ numberOfWarning }}\"\n            [tooltip]=\"'core.component.import-excel.error-rows' | translate\"\n            size=\"sm\"\n            color=\"warning\">\n          </sd-button>\n\n          <sd-button\n            (click)=\"view('ERROR')\"\n            icon=\"error\"\n            title=\"{{ numberOfError }}\"\n            color=\"error\"\n            [tooltip]=\"'core.component.import-excel.warning-rows' | translate\"\n            size=\"sm\">\n          </sd-button>\n        </div>\n      }\n    </div>\n\n    <div class=\"sd-box border rounded\">\n      <div class=\"sd-box-body p-0\">\n        <div class=\"table-responsive\">\n          <table class=\"sd-table\">\n            <thead>\n              <tr>\n                <th class=\"text-center c-sticky-left\" style=\"width: 50px\">#</th>\n                @if (filteredItems.length) {\n                  <th class=\"text-center\" style=\"min-width: 250px; width: 250px\">{{ 'core.component.import-excel.status' | translate }}</th>\n                }\n                @for (column of option.columns; track column.field) {\n                  @if (column | columnHidden) {\n                    <th [ngStyle]=\"{ 'min-width': column.width || '300px', width: column.width || '300px' }\" [matTooltip]=\"column.title\">\n                      <span class=\"c-ellipsis\">\n                        {{ column.title }}\n                      </span>\n                    </th>\n                  }\n                }\n              </tr>\n            </thead>\n\n            <tbody>\n              @if (viewItems.length) {\n                @for (item of viewItems; track item.meta.excelIndex) {\n                  <tr>\n                    <td class=\"text-center c-sticky-left px-4\">\n                      <sd-badge\n                        type=\"tag\"\n                        [title]=\"item.meta.excelIndex\"\n                        [success]=\"!item.meta.warningMessages.length && !item.meta.errorMessages.length\"\n                        [warning]=\"!!item.meta.warningMessages.length && !item.meta.errorMessages.length\"\n                        [error]=\"!!item.meta.errorMessages.length\" />\n                    </td>\n\n                    <td style=\"min-width: 250px; width: 250px\">\n                      <div\n                        class=\"text-wrap\"\n                        [innerHTML]=\"\n                          item.meta.errorMessages[0] || item.meta.warningMessages[0] || ('<span class=\\'text-success\\'>' + ('core.component.import-excel.valid-data' | translate) + '</span>')\n                        \"></div>\n                    </td>\n\n                    @for (column of option.columns; track column.field) {\n                      @if (column | columnHidden) {\n                        <td\n                          class=\"align-middle\"\n                          [ngClass]=\"{\n                            'bg-warning-light': item.meta.warning[column.field] && !item.meta.error[column.field],\n                            'bg-error-light': item.meta.error[column.field]\n                          }\"\n                          [matTooltip]=\"item.meta.error[column.field] || item.meta.warning[column.field]\"\n                          [ngStyle]=\"{ 'min-width': column.width || '300px' }\"\n                          matTooltipPosition=\"above\">\n                          <div class=\"c-ellipsis\">\n                            @if (column.type !== 'array') {\n                              <span [innerHTML]=\"item | columnTransform: column | async\"></span>\n                            }\n\n                            @if (column.type === 'array') {\n                              @let arrayItems = item.data[column.field]?.split(column.divideString);\n\n                              <div class=\"d-flex align-items-center justify-content-between\">\n                                <span>{{ arrayItems?.length || 0 }} {{ column.unitString }}</span>\n\n                                @if (arrayItems?.length) {\n                                  <button\n                                    mat-icon-button\n                                    [matMenuTriggerFor]=\"menu\"\n                                    class=\"c-mat-menu\"\n                                    style=\"width: 24px; height: 24px; line-height: 24px\">\n                                    <mat-icon style=\"font-size: 18px\">open_in_new</mat-icon>\n                                  </button>\n\n                                  <mat-menu #menu=\"matMenu\">\n                                    <div\n                                      class=\"px-3 py-2\"\n                                      style=\"max-width: 300px; max-height: 250px; overflow: auto\"\n                                      (click)=\"$event.stopPropagation()\"\n                                      aria-hidden=\"true\">\n                                      @for (val of arrayItems; track $index) {\n                                        <div class=\"border-bottom py-2 text-wrap\" [innerHTML]=\"val\"></div>\n                                      }\n                                    </div>\n                                  </mat-menu>\n                                }\n                              </div>\n                            }\n                          </div>\n                        </td>\n                      }\n                    }\n                  </tr>\n                }\n              } @else {\n                <tr>\n                  <td [attr.colspan]=\"option.columns.length + 2\" class=\"p-0 border-0 bg-white\">\n                    <div\n                      class=\"empty-state-wrapper\"\n                      (click)=\"downloadTemplate()\"\n                      [matTooltip]=\"'core.component.import-excel.download-template-tooltip' | translate\"\n                      aria-hidden=\"true\">\n                      <mat-icon class=\"empty-icon\">cloud_download</mat-icon>\n\n                      <h4>{{ 'core.component.import-excel.no-data-upload' | translate }}</h4>\n                      <span class=\"text-small text-link\"> {{ 'core.component.import-excel.click-here-template' | translate }} </span>\n\n                      @if (isDownloadTemplate) {\n                        <div class=\"mt-3\">\n                          <mat-spinner diameter=\"24\" mode=\"indeterminate\"></mat-spinner>\n                        </div>\n                      }\n                    </div>\n                  </td>\n                </tr>\n              }\n            </tbody>\n          </table>\n        </div>\n      </div>\n\n      <div class=\"sd-box-footer border-top\">\n        <div class=\"d-flex align-items-center justify-content-end\">\n          <mat-paginator [length]=\"filteredItems.length || 0\" hidePageSize showFirstLastButtons></mat-paginator>\n        </div>\n      </div>\n    </div>\n    <sd-button sdFooterLeft (click)=\"upload()\" prefixIcon=\"file_upload\" [title]=\"'core.component.import-excel.upload' | translate\" size=\"sm\" color=\"info\" [loading]=\"uploading\">\n    </sd-button>\n    <div class=\"d-flex align-items-center\" sdFooter>\n      @if (filteredItems.length) {\n        <sd-button class=\"mr-4\" (click)=\"export()\" prefixIcon=\"get_app\" [title]=\"'core.component.import-excel.download' | translate\" size=\"sm\" color=\"success\" type=\"outline\">\n        </sd-button>\n      }\n      <sd-button\n        (click)=\"accept()\"\n        [title]=\"'core.component.import-excel.confirm-save' | translate\"\n        [disabled]=\"(numberOfSuccess === 0 && numberOfWarning === 0) || numberOfError > 0 || isUploaded\"\n        color=\"primary\"\n        type=\"fill\"\n        size=\"sm\">\n      </sd-button>\n    </div>\n  </sd-modal>\n}\n", styles: [".table-responsive{position:relative;min-height:50vh;height:50vh;overflow:auto;border:1px solid #dee2e6}.sd-table{width:100%;border-collapse:collapse;margin-bottom:0;font-size:14px}.sd-table thead th{position:sticky;top:0;background-color:#f8f9fa;border-bottom:2px solid #dee2e6;border-top:1px solid #dee2e6;padding:8px 6px;white-space:nowrap;z-index:10;font-weight:600}.sd-table thead th.c-sticky-left{z-index:20}.sd-table tbody td{vertical-align:middle;padding:6px;border-top:1px solid #dee2e6}.sd-table tbody tr:nth-of-type(odd){background-color:#0000000a}.sd-table tbody tr:nth-of-type(2n){background-color:#fff}.sd-table tbody tr:hover,.sd-table tbody tr:hover .c-sticky-left{background-color:#ececec}.sd-table tbody tr:nth-of-type(odd) .c-sticky-left{background-color:#f2f2f2}.sd-table tbody tr:nth-of-type(2n) .c-sticky-left{background-color:#fff}.c-sticky-left{position:sticky;left:0;border-right:1px solid #dee2e6!important;border-left:none!important;z-index:5}.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=sdcorejs-angular-components-import-excel.mjs.map
