import { __classPrivateFieldGet, __awaiter, __classPrivateFieldSet } from 'tslib';
import { Pipe, Injectable, EventEmitter, Component, ChangeDetectorRef, Input, ViewChild, Output, NgModule } from '@angular/core';
import { v4 } from 'uuid';
import { SdNotifyService, SdNotifyModule } from '@sd-angular/core/notify';
import { SdLoadingService } from '@sd-angular/core/loading';
import { MatPaginator, MatPaginatorModule } from '@angular/material/paginator';
import { SdExportService } from '@sd-angular/core/export';
import { SdTranslateService, SdTranslateModule } from '@sd-angular/core/translate';
import { Subscription } from 'rxjs';
import { DecimalPipe, CommonModule } from '@angular/common';
import { DeviceDetectorModule } from 'ngx-device-detector';
import { SdButtonModule } from '@sd-angular/core/button';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { SdModalModule } from '@sd-angular/core/modal';
import { MatTooltipModule } from '@angular/material/tooltip';
import { FormsModule } from '@angular/forms';
import { SdInputModule } from '@sd-angular/core/input';
import { SdUtilityModule } from '@sd-angular/core/utility';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';

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

class SdColumnHiddenPipe {
    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;
    }
}
SdColumnHiddenPipe.decorators = [
    { type: Pipe, args: [{
                name: 'columnHidden'
            },] },
    { type: Injectable }
];
SdColumnHiddenPipe.ctorParameters = () => [];

var _paginator, _subscription, _reset, _reload, _isError, _isWarning, _isSuccess, _parse, _mapItem, _isValidDate, _isValidTime, _isValidDateTime;
class SdUploadExcel {
    constructor(ref, exportService, translateService, notifyService, sdColumnHidden, loadingService) {
        this.ref = ref;
        this.exportService = exportService;
        this.translateService = translateService;
        this.notifyService = notifyService;
        this.sdColumnHidden = sdColumnHidden;
        this.loadingService = loadingService;
        this.importId = 'I' + v4();
        this.items = [];
        // originItems: SdExcelItem[] = [];
        this.hasDescription = false;
        this.showing = 'ALL';
        this.filteredItems = [];
        this.viewItems = [];
        this.numberOfSuccess = 0;
        this.numberOfError = 0;
        this.numberOfWarning = 0;
        _paginator.set(this, void 0);
        _subscription.set(this, new Subscription());
        this.isDownloadTemplate = false;
        this.sdClosed = new EventEmitter();
        this.open = () => {
            __classPrivateFieldGet(this, _reset).call(this);
            this.modal.open();
        };
        this.close = () => {
            this.modal.close();
        };
        _reset.set(this, () => {
            this.items = [];
            this.filteredItems = [];
            this.viewItems = [];
            this.numberOfSuccess = 0;
            this.numberOfError = 0;
            this.numberOfWarning = 0;
            this.showing = 'ALL';
        });
        _reload.set(this, () => {
            const pageIndex = __classPrivateFieldGet(this, _paginator).pageIndex;
            const pageSize = __classPrivateFieldGet(this, _paginator).pageSize;
            this.filteredItems = this.items.filter((item) => {
                const { validation } = item.sd;
                if (this.showing === 'SUCCESS') {
                    return !(validation === null || validation === void 0 ? void 0 : validation.error) && !(validation === null || validation === void 0 ? void 0 : validation.warning);
                }
                else if (this.showing === 'WARNING') {
                    return !!(validation === null || validation === void 0 ? void 0 : validation.warning) && !(validation === null || validation === void 0 ? void 0 : validation.error);
                }
                else if (this.showing === 'ERROR') {
                    return !!(validation === null || validation === void 0 ? void 0 : validation.error);
                }
                return true;
            });
            this.viewItems = this.filteredItems
                .filter((item, index) => index >= pageIndex * pageSize && index < (pageIndex + 1) * pageSize);
            this.numberOfSuccess = this.items.filter(__classPrivateFieldGet(this, _isSuccess)).length;
            this.numberOfError = this.items.filter(__classPrivateFieldGet(this, _isError)).length;
            this.numberOfWarning = this.items.filter(__classPrivateFieldGet(this, _isWarning)).length;
        });
        _isError.set(this, (item) => !!item.sd.validation.error);
        _isWarning.set(this, (item) => { var _a, _b; return ((_a = item.sd.validation) === null || _a === void 0 ? void 0 : _a.warning) && !((_b = item.sd.validation) === null || _b === void 0 ? void 0 : _b.error); });
        _isSuccess.set(this, (item) => { var _a, _b; return !((_a = item.sd.validation) === null || _a === void 0 ? void 0 : _a.error) && !((_b = item.sd.validation) === null || _b === void 0 ? void 0 : _b.warning); });
        this.upload = () => __awaiter(this, void 0, void 0, function* () {
            try {
                const { mappingItems, errorValidation, warningValidation } = this.option;
                const { translate } = this.translateService;
                const { items, file } = yield this.exportService.uploadXlsx();
                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.notify.warning(`${translate(`No data to import`)}`);
                    return;
                }
                if (items.length > this.option.limit) {
                    this.notifyService.notify.warning(`${translate(`Limit rows`)}: ${this.option.limit}`);
                    return;
                }
                __classPrivateFieldGet(this, _reset).call(this);
                // this.originItems = items.map(data => ({
                //   data,
                //   sd: {}
                // }));
                this.items = items.map((data, idx) => ({
                    data,
                    sd: {
                        excelIndex: idx + (this.hasDescription ? 4 : 3),
                        validation: {
                            data: {}
                        },
                        origin: Object.assign({}, data)
                    }
                }));
                if (mappingItems) {
                    const mappedItems = mappingItems(this.items);
                    if (mappedItems instanceof Promise) {
                        this.uploading = true;
                        this.items = (yield mappedItems.finally(() => this.uploading = false));
                    }
                    else {
                        this.items = (mappedItems || this.items);
                    }
                }
                this.file = file;
                this.loadingService.start();
                for (const [idx, item] of this.items.entries()) {
                    yield this.validate(item, idx);
                }
                // Nếu không có error thì tiếp tục validate từ option validate truyền vào
                if (!this.items.some(__classPrivateFieldGet(this, _isError)) && errorValidation) {
                    const results = yield errorValidation(this.items.map(e => e.data));
                    results.forEach(result => this.items[result.idx].sd.validation.error = result.message);
                }
                // Nếu không có warning thì tiếp tục validate từ option validate truyền vào
                if (!this.items.some(__classPrivateFieldGet(this, _isWarning)) && warningValidation) {
                    const results = yield warningValidation(this.items.map(e => e.data));
                    results.forEach(result => this.items[result.idx].sd.validation.warning = result.message);
                }
                __classPrivateFieldGet(this, _paginator).pageIndex = 0;
                __classPrivateFieldGet(this, _reload).call(this);
                this.ref.detectChanges();
                this.isUploaded = false;
            }
            catch (err) {
                this.notifyService.handle.error(err);
            }
            finally {
                this.loadingService.stop();
            }
        });
        this.validate = (excelItem, idx) => __awaiter(this, void 0, void 0, function* () {
            var _a;
            const { data: item, sd: { validation } } = excelItem;
            const { translate } = this.translateService;
            const errors = [];
            for (const column of this.option.columns) {
                validation.data[column.field] = {};
                if (!this.sdColumnHidden.transform(column)) {
                    continue;
                }
                try {
                    if (column.defaultValue !== undefined) {
                        item[column.field] = (_a = item[column.field]) !== null && _a !== void 0 ? _a : column.defaultValue;
                    }
                    else if (column.required && !item[column.field] && item[column.field] !== 0) {
                        validation.data[column.field].error = `${translate('required')}`;
                        errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                        continue;
                    }
                    if (column.type === 'string') {
                        const value = (item[column.field] || '').toString();
                        if (column.minLength !== undefined && value.length < column.minLength) {
                            validation.data[column.field].error = `${translate('Min length')}: ${column.minLength}`;
                            errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                            continue;
                        }
                        if (column.maxLength !== undefined && value.length > column.maxLength) {
                            validation.data[column.field].error = `${translate('Max length')}: ${column.maxLength}`;
                            errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                            continue;
                        }
                        item[column.field] = value;
                    }
                    else if (column.type === 'number') {
                        if (item[column.field]) {
                            const value = +item[column.field];
                            if (Number.isNaN(value)) {
                                validation.data[column.field].error = `${item[column.field]} ${translate('is not a number')}`;
                                errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                                continue;
                            }
                            item[column.field] = value;
                        }
                        if (!item[column.field] && item[column.field] !== 0) {
                            item[column.field] = undefined;
                        }
                        if (column.minValue !== undefined && item[column.field] < column.minValue) {
                            validation.data[column.field].error = `${item[column.field]} ${translate('Min value')}: ${column.minValue}`;
                            errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                            continue;
                        }
                        if (column.maxValue !== undefined && item[column.field] > column.maxValue) {
                            validation.data[column.field].error = `${item[column.field]} ${translate('Max value')}: ${column.maxValue}`;
                            errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                            continue;
                        }
                    }
                    else if (column.type === 'bool') {
                        if (item[column.field] === 0 || item[column.field] === false) {
                            item[column.field] = '0';
                        }
                        if (item[column.field] === 1 || item[column.field] === true) {
                            item[column.field] = '1';
                        }
                        if (item[column.field]) {
                            const value = +item[column.field];
                            if (Number.isNaN(value) || (value !== 0 && value !== 1)) {
                                validation.data[column.field].error = `${translate('Value shoud be 0 or 1')}`;
                                errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                            }
                            else {
                                if (column.parseToBool) {
                                    item[column.field] = item[column.field] === '1';
                                }
                            }
                        }
                    }
                    else if (column.type === 'values') {
                        if (item[column.field] && typeof (item[column.field]) !== 'number' && typeof (item[column.field]) !== 'string') {
                            validation.data[column.field].error = `${item[column.field]} ${translate('Invalid data type')}`;
                            errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                            continue;
                        }
                        if (column.checkValueInArray && item[column.field] && !column.values.some(e => e.toString() === item[column.field].toString())) {
                            validation.data[column.field].error = `${item[column.field]} ${translate('Value not in')} [${column.values.join()}]`;
                            errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                            continue;
                        }
                    }
                    else if (column.type === 'date' || column.type === 'datetime' || column.type === 'time') {
                        const { type, format } = column;
                        const val = item[column.field];
                        if (format && item[column.field]) {
                            if (typeof (val) !== 'string') {
                                validation.data[column.field].error = `${translate('Invalid format')} ${column.format}: ${val}`;
                                errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                                continue;
                            }
                            if (type === 'date' && !__classPrivateFieldGet(this, _isValidDate).call(this, format, val)) {
                                validation.data[column.field].error = `${translate('Invalid format')} ${column.format}: ${val}`;
                                errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                                continue;
                            }
                            if (type === 'time' && !__classPrivateFieldGet(this, _isValidTime).call(this, format, val)) {
                                validation.data[column.field].error = `${translate('Invalid format')} ${column.format}: ${val}`;
                                errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                                continue;
                            }
                            if (type === 'datetime' && !__classPrivateFieldGet(this, _isValidDateTime).call(this, format, val)) {
                                validation.data[column.field].error = `${translate('Invalid format')} ${column.format}: ${val}`;
                                errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                                continue;
                            }
                            item[column.field] = Date.parseFrom(val, column.format).toFormat('MM/dd/yyyy HH:mm:ss');
                        }
                        if (item[column.field] && !Date.isDate(item[column.field])) {
                            validation.data[column.field].error = `${translate('Invalid date')}: ${item[column.field]}`;
                            errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                            continue;
                        }
                    }
                    if (!validation.data[column.field].error && column.errorValidation) {
                        const error = yield column.errorValidation(item, item[column.field], idx);
                        if (error) {
                            validation.data[column.field].error = `${error}`;
                            errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                        }
                    }
                    if (!validation.data[column.field].warning && column.warningValidation) {
                        const warning = yield column.warningValidation(item, item[column.field], idx);
                        if (warning) {
                            validation.data[column.field].warning = `${warning}`;
                            validation.warning += `<strong>[${column.title || column.field}]</strong> ${warning}<br>`;
                        }
                    }
                }
                catch (ex) {
                    validation.data[column.field].error = `${(ex === null || ex === void 0 ? void 0 : ex.message) || (ex === null || ex === void 0 ? void 0 : ex.error) || ex || 'Có lỗi xảy ra'}`;
                    errors.push(`<strong>[${column.title || column.field}]</strong> ${validation.data[column.field].error}`);
                }
            }
            validation.error = errors.join('<br>');
        });
        _parse.set(this, (item) => {
            const { data } = item;
            return data;
        });
        _mapItem.set(this, (item) => {
            const { data } = item;
            return data;
        });
        this.accept = () => {
            var _a;
            const successItems = this.items.filter(__classPrivateFieldGet(this, _isSuccess)).map(__classPrivateFieldGet(this, _mapItem));
            const errorItems = this.items.filter(__classPrivateFieldGet(this, _isError)).map(__classPrivateFieldGet(this, _mapItem));
            const warningItems = this.items.filter(__classPrivateFieldGet(this, _isWarning)).map(__classPrivateFieldGet(this, _mapItem));
            (_a = this.option) === null || _a === void 0 ? void 0 : _a.onAccept(this.items.map(__classPrivateFieldGet(this, _mapItem)), successItems, errorItems, warningItems, this.file);
            this.isUploaded = true;
        };
        this.setValidation = (validates) => {
            if (Array.isArray(validates)) {
                validates.forEach(validate => {
                    this.items[validate.idx].sd.validation.error = validate.messageError;
                    this.items[validate.idx].sd.validation.warning = validate.messageWarning;
                    this.items[validate.idx].sd.validation.success = validate.messageSuccess;
                });
            }
            __classPrivateFieldGet(this, _reload).call(this);
            this.ref.detectChanges();
        };
        this.view = (showing = 'ALL') => {
            this.showing = showing;
            __classPrivateFieldGet(this, _paginator).pageIndex = 0;
            __classPrivateFieldGet(this, _reload).call(this);
        };
        this.downloadTemplate = () => __awaiter(this, void 0, void 0, function* () {
            var _b;
            const sheets = [];
            if (Array.isArray((_b = this.option) === null || _b === void 0 ? void 0 : _b.sheets)) {
                for (const sheet of this.option.sheets) {
                    if (sheet.name && sheet.items && sheet.fields) {
                        if (Array.isArray(sheet.items)) {
                            sheets.push({
                                name: sheet.name,
                                items: sheet.items,
                                fields: sheet.fields
                            });
                        }
                        else {
                            sheets.push({
                                name: sheet.name,
                                items: yield sheet.items(),
                                fields: sheet.fields
                            });
                        }
                    }
                }
            }
            const columnNotHiddens = this.option.columns.filter(column => this.sdColumnHidden.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;
            yield this.exportService.generateTemplate(excelTemplate).finally(() => {
                this.isDownloadTemplate = false;
            });
        });
        this.export = () => __awaiter(this, void 0, void 0, function* () {
            this.loadingService.start();
            const columns = [{
                    field: 'sdMessage',
                    title: this.translateService.translate('Upload message'),
                    width: '250px',
                    required: false
                }, ...this.option.columns.filter(column => this.sdColumnHidden.transform(column))];
            yield this.exportService.export({
                columns,
                items: this.filteredItems.map(e => {
                    var _a, _b, _c, _d, _e;
                    let result = {};
                    for (const column of columns) {
                        result = Object.assign(Object.assign({}, result), { [column.field]: (_a = e.sd.origin) === null || _a === void 0 ? void 0 : _a[column.field] });
                    }
                    return Object.assign(Object.assign({}, result), { sdMessage: (_e = (((_b = e.sd.validation) === null || _b === void 0 ? void 0 : _b.error) || ((_c = e.sd.validation) === null || _c === void 0 ? void 0 : _c.warning) || ((_d = e.sd.validation) === null || _d === void 0 ? void 0 : _d.success))) === null || _e === void 0 ? void 0 : _e.replace(/<strong>/g, '').replace(/<\/strong>/g, '').replace(/<br>/g, '\n') });
                })
            }).finally(this.loadingService.stop);
        });
        _isValidDate.set(this, (format, value) => {
            if ((value === null || value === void 0 ? void 0 : value.length) !== (format === null || format === void 0 ? void 0 : 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.set(this, (format, value) => {
            if ((value === null || value === void 0 ? void 0 : value.length) !== (format === null || format === void 0 ? void 0 : format.length)) {
                return false;
            }
            return true;
        });
        _isValidDateTime.set(this, (format, value) => {
            if ((value === null || value === void 0 ? void 0 : value.length) !== (format === null || format === void 0 ? void 0 : format.length)) {
                return false;
            }
            const dates = value === null || value === void 0 ? void 0 : value.split(' ');
            if (dates.length !== 2) {
                return false;
            }
            const date = dates[0];
            if (!__classPrivateFieldGet(this, _isValidDate).call(this, '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);
        });
        this.onClosed = () => {
            this.sdClosed.emit();
        };
    }
    set paginator(paginator) {
        if (paginator && __classPrivateFieldGet(this, _paginator) !== paginator) {
            __classPrivateFieldSet(this, _paginator, paginator);
            __classPrivateFieldGet(this, _subscription).add(paginator.page.subscribe(__classPrivateFieldGet(this, _reload)));
        }
    }
    ngOnInit() {
        this.isUploaded = false;
    }
    ngOnDestroy() {
        __classPrivateFieldGet(this, _subscription).unsubscribe();
    }
}
_paginator = new WeakMap(), _subscription = new WeakMap(), _reset = new WeakMap(), _reload = new WeakMap(), _isError = new WeakMap(), _isWarning = new WeakMap(), _isSuccess = new WeakMap(), _parse = new WeakMap(), _mapItem = new WeakMap(), _isValidDate = new WeakMap(), _isValidTime = new WeakMap(), _isValidDateTime = new WeakMap();
SdUploadExcel.decorators = [
    { type: Component, args: [{
                selector: 'sd-upload-excel',
                template: "<sd-modal [title]=\"(option?.title || 'Import Excel')| sdTranslate\" (sdClosed)=\"onClosed()\" #modal>\r\n  <sd-modal-body background=\"#F0F8FF\">\r\n    <div class=\"row mx-0 mb-10\">\r\n      <sd-button *ngIf=\"items?.length\" class=\"mr-5\" (action)=\"view('ALL')\" icon=\"cached\"\r\n        [title]=\"'View all' | sdTranslate\" size=\"sm\"></sd-button>\r\n      <sd-button *ngIf=\"numberOfSuccess\" class=\"mr-5\" (action)=\"view('SUCCESS')\" icon=\"done\" [title]=\"numberOfSuccess\"\r\n        [tooltip]=\"'Number of success rows' | sdTranslate\" size=\"sm\" color=\"success\"></sd-button>\r\n      <sd-button *ngIf=\"numberOfWarning\" class=\"mr-5\" (action)=\"view('WARNING')\" icon=\"warning\"\r\n        [title]=\"numberOfWarning\" [tooltip]=\"'Number of warning rows' | sdTranslate\" size=\"sm\"></sd-button>\r\n      <sd-button *ngIf=\"numberOfError\" class=\"mr-5\" (action)=\"view('ERROR')\" icon=\"error\" [title]=\"numberOfError\"\r\n        color=\"danger\" [tooltip]=\"'Number of error rows' | sdTranslate\" size=\"sm\"></sd-button>\r\n    </div>\r\n    <div class=\"sd-box\">\r\n      <div class=\"sd-box-body p-0\">\r\n        <div class=\"table-responsive\" style=\"position: relative; height:50vh\">\r\n          <table class=\"table table-striped table-sm table-hover table-bordered\">\r\n            <thead class=\"thead-light\">\r\n              <tr>\r\n                <th class=\"text-center position-sticky c-sticky-left\" style=\"width: 50px;vertical-align: middle;\">#</th>\r\n                <th *ngIf=\"filteredItems?.length\" class=\"text-center\"\r\n                  style=\"min-width: 250px; width: 250px;vertical-align: middle;\">\r\n                  {{'Upload message' | sdTranslate}}</th>\r\n                <ng-container *ngFor=\"let column of option.columns\">\r\n                  <th *ngIf=\"column | columnHidden\" [ngStyle]=\"{'min-width':column.width ? column.width : '300px'}\"\r\n                    [matTooltip]=\"column.title\">\r\n                    <span class=\"c-ellipsis\"\r\n                      [ngStyle]=\"{'min-width':column.width ? column.width : '300px', 'max-width':column.width ? column.width : '300px'}\">{{column.title}}</span>\r\n                  </th>\r\n                </ng-container>\r\n              </tr>\r\n            </thead>\r\n            <tbody *ngIf=\"viewItems.length\">\r\n              <tr *ngFor=\"let item of viewItems\">\r\n                <td class=\"text-center position-sticky c-sticky-left\" style=\"width: 50px\">\r\n                  <span class=\"badge\"\r\n                    [ngClass]=\"{'badge-success':!item.sd.validation?.warning && !item.sd.validation?.error, 'badge-warning':item.sd.validation?.warning && !item.sd.validation?.error, 'badge-danger':item.sd.validation?.error}\"\r\n                    style=\"width: 100%\">{{item.sd.excelIndex}}</span>\r\n                </td>\r\n                <td style=\"min-width: 250px; width: 250px\">\r\n                  <div\r\n                    [innerHtml]=\"item.sd.validation?.error || item.sd.validation?.warning || item.sd.validation?.success || ('Success' | sdTranslate)\">\r\n                  </div>\r\n                </td>\r\n                <ng-container *ngFor=\"let column of option.columns\">\r\n                  <td *ngIf=\"column | columnHidden\" class=\"align-middle\" [ngClass]=\"{'table-warning':item.sd.validation?.data[column.field]?.warning && !item.sd.validation?.data[column.field]?.error, \r\n                    'table-danger':item.sd.validation?.data[column.field]?.error}\"\r\n                    [matTooltip]=\"item.sd.validation?.data[column.field]?.error || item.sd.validation?.data[column.field]?.warning\"\r\n                    [ngStyle]=\"{'min-width':column.width ? column.width : '300px'}\" matTooltipPosition=\"above\">\r\n                    <span class=\"c-ellipsis\">\r\n                      <div *ngIf=\"column.type !== 'array'\"\r\n                        [innerHtml]=\"item | columnTransform:column | async | safeHtml\"></div>\r\n                      <ng-container *ngIf=\"column.type === 'array'\">\r\n                        {{item.data[column.field]?.split(column.divideString)?.length}} {{column.unitString}}\r\n                        <button mat-button [matMenuTriggerFor]=\"menu\" class=\"c-mat-menu\">\r\n                          <mat-icon>open_in_new</mat-icon>\r\n                        </button>\r\n                        <mat-menu #menu=\"matMenu\">\r\n                          <div class=\"row mx-0\">\r\n                            <div class=\"col-6\" *ngFor=\"let itemArray of item.data[column.field]?.split(column.divideString)\"\r\n                              [innerHtml]=\"itemArray\">\r\n                            </div>\r\n                          </div>\r\n                        </mat-menu>\r\n                      </ng-container>\r\n                    </span>\r\n                  </td>\r\n                </ng-container>\r\n              </tr>\r\n            </tbody>\r\n          </table>\r\n        </div>\r\n      </div>\r\n      <div class=\"sd-box-footer clearfix\">\r\n        <div style=\"display: flex; align-items: center; align-content: space-between;\">\r\n          <div style=\"flex: 1;\" [innerHTML]=\"option?.note\">\r\n          </div>\r\n          <div style=\"flex: 1;\">\r\n            <mat-paginator [length]=\"filteredItems?.length || 0\" hidePageSize>\r\n            </mat-paginator>\r\n          </div>\r\n        </div>\r\n      </div>\r\n    </div>\r\n  </sd-modal-body>\r\n  <sd-modal-footer *sdDesktop>\r\n    <div class=\"mr-auto\">\r\n      <sd-button class=\"mr-5\" (action)=\"upload()\" icon=\"file_upload\" [title]=\"'Upload' | sdTranslate\" size=\"sm\"\r\n        color=\"info\" [loading]=\"uploading\"></sd-button>\r\n      <sd-button class=\"mr-5\" (action)=\"downloadTemplate()\" icon=\"file_download\" [loading]=\"isDownloadTemplate\"\r\n        [title]=\"'Download template' | sdTranslate\" color=\"info\" type=\"outline\" size=\"sm\">\r\n      </sd-button>\r\n    </div>\r\n    <sd-button *ngIf=\"filteredItems?.length\" class=\"mr-5\" (action)=\"export()\" icon=\"get_app\"\r\n      [title]=\"'Download result' | sdTranslate\" size=\"sm\" color=\"info\" type=\"outline\">\r\n    </sd-button>\r\n    <sd-button (action)=\"accept()\" [title]=\"'Accept' | sdTranslate\"\r\n      [disabled]=\"(numberOfSuccess === 0 && numberOfWarning === 0) || numberOfError > 0 || isUploaded\" color=\"primary\" type=\"fill\" size=\"sm\">\r\n    </sd-button>\r\n  </sd-modal-footer>\r\n  <sd-modal-footer *sdMobileTablet>\r\n    <sd-button style=\"flex: 1; padding-right: 5px;\" (action)=\"upload()\" icon=\"file_upload\"\r\n      [title]=\"'Upload' | sdTranslate\" width=\"100%\" size=\"sm\" color=\"info\" [loading]=\"uploading\"></sd-button>\r\n    <sd-button style=\"flex: 1; padding-left: 5px;\" (action)=\"accept()\" icon=\"check\" [title]=\"'Accept' | sdTranslate\"\r\n      [disabled]=\"(numberOfSuccess === 0 && numberOfWarning === 0) || numberOfError > 0\" color=\"success\" width=\"100%\" size=\"sm\"></sd-button>\r\n  </sd-modal-footer>\r\n</sd-modal>",
                styles: [".table thead td,.table thead th{padding-bottom:5px;padding-top:5px}.table-striped tbody tr:nth-of-type(2n) .c-sticky-left{background-color:#fff}.table-striped tbody tr:nth-of-type(odd) .c-sticky-left{background-color:#f2f2f2}.c-sticky-left{border-left:none!important;border-right:none!important;left:0!important;z-index:20}.c-ellipsis{display:block;overflow:hidden!important;padding:.1rem;text-overflow:ellipsis;white-space:nowrap}.c-mat-menu{border:none}.c-mat-menu mat-icon{font-size:20px;vertical-align:middle}:host ::ng-deep .mat-paginator-container{height:32px;min-height:32px}:host ::ng-deep .mat-paginator-container .mat-icon-button{height:28px;line-height:28px;width:28px}"]
            },] }
];
SdUploadExcel.ctorParameters = () => [
    { type: ChangeDetectorRef },
    { type: SdExportService },
    { type: SdTranslateService },
    { type: SdNotifyService },
    { type: SdColumnHiddenPipe },
    { type: SdLoadingService }
];
SdUploadExcel.propDecorators = {
    option: [{ type: Input }],
    modal: [{ type: ViewChild, args: ['modal',] }],
    paginator: [{ type: ViewChild, args: [MatPaginator,] }],
    sdClosed: [{ type: Output }]
};

class SdColumnTransformPipe {
    constructor(decimalPipe) {
        this.decimalPipe = decimalPipe;
        this.transform = (rowData, column) => __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c, _d, _e, _f;
            const { type, transform } = column;
            const value = rowData.data[column.field];
            if ((_a = rowData.sd.validation.data[column.field]) === null || _a === void 0 ? void 0 : _a.error) {
                return (_c = (_b = rowData.sd.origin[column.field]) !== null && _b !== void 0 ? _b : value) !== null && _c !== void 0 ? _c : '';
            }
            if (transform) {
                return transform(rowData.data, value);
            }
            if (column.type === 'number') {
                return (_d = Number.toVNCurrency(value)) !== null && _d !== void 0 ? _d : '';
            }
            if (column.type === 'bool') {
                if (value === '1' || value === true) {
                    return `<div class="text-center"><input type="checkbox" checked disabled></div>`;
                }
                else if (value === '0' || value === false) {
                    return `<div class="text-center"><input type="checkbox" disabled></div>`;
                }
            }
            if (column.type === 'date') {
                return (_e = Date.toFormat(value, column.format || 'dd/MM/yyyy')) !== null && _e !== void 0 ? _e : '';
            }
            if (column.type === 'datetime') {
                return (_f = Date.toFormat(value, column.format || 'dd/MM/yyyy HH:mm')) !== null && _f !== void 0 ? _f : '';
            }
            return value !== null && value !== void 0 ? value : '';
        });
    }
}
SdColumnTransformPipe.decorators = [
    { type: Pipe, args: [{
                name: 'columnTransform'
            },] }
];
SdColumnTransformPipe.ctorParameters = () => [
    { type: DecimalPipe }
];

class SdUploadExcelModule {
}
SdUploadExcelModule.decorators = [
    { type: NgModule, args: [{
                imports: [
                    CommonModule,
                    FormsModule,
                    DeviceDetectorModule.forRoot(),
                    MatSlideToggleModule,
                    MatTooltipModule,
                    MatPaginatorModule,
                    MatSlideToggleModule,
                    SdNotifyModule,
                    SdTranslateModule,
                    SdUtilityModule,
                    SdButtonModule,
                    SdModalModule,
                    SdInputModule,
                    MatIconModule,
                    MatMenuModule
                ],
                declarations: [
                    SdUploadExcel,
                    // pipe
                    SdColumnHiddenPipe,
                    SdColumnTransformPipe
                ],
                exports: [
                    SdUploadExcel
                ],
                providers: [
                    DecimalPipe,
                    SdColumnHiddenPipe
                ]
            },] }
];

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

export { SdUploadExcel, SdUploadExcelModule, SdColumnHiddenPipe as ɵa, SdColumnTransformPipe as ɵb };
//# sourceMappingURL=sd-angular-core-upload-excel.js.map
