import { __awaiter, __decorate, __generator, __read, __spread, __values } from "tslib";
import { Component, OnInit, AfterViewInit, ViewChild, Output, EventEmitter, Input, ChangeDetectorRef } from '@angular/core';
import { TranslateService } from '../../../../services/translate/translate.service';
import { NotifyService } from '../../../../services/notify/notify.service';
import { ExcelService } from '../../../../services/excel/excel.service';
import { LoadingService } from '../../../../services/loading/loading.service';
import * as hash from 'object-hash';
var GridPopupExportExcelComponent = /** @class */ (function () {
    function GridPopupExportExcelComponent(ref, loadingService, excelService, notifyService, translateService) {
        var _this = this;
        this.ref = ref;
        this.loadingService = loadingService;
        this.excelService = excelService;
        this.notifyService = notifyService;
        this.translateService = translateService;
        this.prefix = 'Popup Export Excel';
        this.newExcelConfig = 'fd8fb5db-a7ad-4398-93ac-cb3350261180';
        this.key = '';
        this.columns = [];
        this.extendColumns = [];
        this.excelConfigs = [];
        this.exportByTemplate = new EventEmitter();
        this.tabIndex = 0;
        this.selectedExcelConfig = {};
        this.exportableColumns = [];
        this.selected = {};
        this.generateExcelColumns = function (columns) {
            var e_1, _a, e_2, _b;
            var excelColumns = [];
            try {
                for (var columns_1 = __values(columns), columns_1_1 = columns_1.next(); !columns_1_1.done; columns_1_1 = columns_1.next()) {
                    var column = columns_1_1.value;
                    if (column.type === 'children') {
                        try {
                            for (var _c = (e_2 = void 0, __values(column.children)), _d = _c.next(); !_d.done; _d = _c.next()) {
                                var childColumn = _d.value;
                                if (childColumn.type !== 'image') {
                                    excelColumns.push({
                                        field: childColumn.field,
                                        title: childColumn.title,
                                        description: childColumn.description,
                                        width: childColumn.width
                                    });
                                }
                            }
                        }
                        catch (e_2_1) { e_2 = { error: e_2_1 }; }
                        finally {
                            try {
                                if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
                            }
                            finally { if (e_2) throw e_2.error; }
                        }
                    }
                    else if (column.type !== 'image') {
                        excelColumns.push({
                            field: column.field,
                            title: column.title,
                            description: column.description,
                            width: column.width
                        });
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (columns_1_1 && !columns_1_1.done && (_a = columns_1.return)) _a.call(columns_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return excelColumns;
        };
        this.initTemplate = function (columns, fileName) { return __awaiter(_this, void 0, void 0, function () {
            var sheets, _a, _b, sheet, _c, _d, _e, e_3_1;
            var e_3, _f;
            var _g;
            return __generator(this, function (_h) {
                switch (_h.label) {
                    case 0:
                        columns = columns || [];
                        sheets = [];
                        if (!Array.isArray((_g = this.exportOption) === null || _g === void 0 ? void 0 : _g.sheets)) return [3 /*break*/, 9];
                        _h.label = 1;
                    case 1:
                        _h.trys.push([1, 7, 8, 9]);
                        _a = __values(this.exportOption.sheets), _b = _a.next();
                        _h.label = 2;
                    case 2:
                        if (!!_b.done) return [3 /*break*/, 6];
                        sheet = _b.value;
                        if (!(sheet.name && sheet.items && sheet.fields)) return [3 /*break*/, 5];
                        if (!Array.isArray(sheet.items)) return [3 /*break*/, 3];
                        sheets.push({
                            name: sheet.name,
                            items: sheet.items,
                            fields: sheet.fields
                        });
                        return [3 /*break*/, 5];
                    case 3:
                        _d = (_c = sheets).push;
                        _e = {
                            name: sheet.name
                        };
                        return [4 /*yield*/, sheet.items()];
                    case 4:
                        _d.apply(_c, [(_e.items = _h.sent(),
                                _e.fields = sheet.fields,
                                _e)]);
                        _h.label = 5;
                    case 5:
                        _b = _a.next();
                        return [3 /*break*/, 2];
                    case 6: return [3 /*break*/, 9];
                    case 7:
                        e_3_1 = _h.sent();
                        e_3 = { error: e_3_1 };
                        return [3 /*break*/, 9];
                    case 8:
                        try {
                            if (_b && !_b.done && (_f = _a.return)) _f.call(_a);
                        }
                        finally { if (e_3) throw e_3.error; }
                        return [7 /*endfinally*/];
                    case 9: return [4 /*yield*/, this.excelService.generateExcelTemplate({
                            fileName: fileName || this.fileName,
                            columns: this.generateExcelColumns(columns),
                            sheets: sheets
                        })];
                    case 10: return [2 /*return*/, _h.sent()];
                }
            });
        }); };
        this.initDefaultTemplate = function () { return __awaiter(_this, void 0, void 0, function () {
            var extendColumns, columns;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        extendColumns = this.extendColumns || [];
                        columns = __spread(this.columns, extendColumns);
                        return [4 /*yield*/, this.initTemplate(columns)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        }); };
        this.generateTemplate = function () { return __awaiter(_this, void 0, void 0, function () {
            var result;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        this.loadingService.start();
                        return [4 /*yield*/, this.initDefaultTemplate().finally(this.loadingService.stop)];
                    case 1:
                        result = _b.sent();
                        if ((_a = result) === null || _a === void 0 ? void 0 : _a.filePath) {
                            this.excelService.downloadTemplate(result.filePath, this.fileName + ".xlsx");
                        }
                        return [2 /*return*/];
                }
            });
        }); };
        this.generateAndUploadTemplate = function (columns, fileName) { return __awaiter(_this, void 0, void 0, function () {
            var sheets, _a, _b, sheet, _c, _d, _e, e_4_1;
            var e_4, _f;
            var _g;
            return __generator(this, function (_h) {
                switch (_h.label) {
                    case 0:
                        sheets = [];
                        if (!Array.isArray((_g = this.exportOption) === null || _g === void 0 ? void 0 : _g.sheets)) return [3 /*break*/, 9];
                        _h.label = 1;
                    case 1:
                        _h.trys.push([1, 7, 8, 9]);
                        _a = __values(this.exportOption.sheets), _b = _a.next();
                        _h.label = 2;
                    case 2:
                        if (!!_b.done) return [3 /*break*/, 6];
                        sheet = _b.value;
                        if (!(sheet.name && sheet.items && sheet.fields)) return [3 /*break*/, 5];
                        if (!Array.isArray(sheet.items)) return [3 /*break*/, 3];
                        sheets.push({
                            name: sheet.name,
                            items: sheet.items,
                            fields: sheet.fields
                        });
                        return [3 /*break*/, 5];
                    case 3:
                        _d = (_c = sheets).push;
                        _e = {
                            name: sheet.name
                        };
                        return [4 /*yield*/, sheet.items()];
                    case 4:
                        _d.apply(_c, [(_e.items = _h.sent(),
                                _e.fields = sheet.fields,
                                _e)]);
                        _h.label = 5;
                    case 5:
                        _b = _a.next();
                        return [3 /*break*/, 2];
                    case 6: return [3 /*break*/, 9];
                    case 7:
                        e_4_1 = _h.sent();
                        e_4 = { error: e_4_1 };
                        return [3 /*break*/, 9];
                    case 8:
                        try {
                            if (_b && !_b.done && (_f = _a.return)) _f.call(_a);
                        }
                        finally { if (e_4) throw e_4.error; }
                        return [7 /*endfinally*/];
                    case 9: return [4 /*yield*/, this.excelService.generateAndUploadExcelTemplate(this.fullKey, {
                            fileName: fileName || this.fileName,
                            columns: this.generateExcelColumns(columns),
                            sheets: sheets
                        })];
                    case 10: return [2 /*return*/, _h.sent()];
                }
            });
        }); };
        this.onExportByTemplate = function (excelConfig) {
            var extendColumns = _this.extendColumns || [];
            var columns = __spread(_this.columns, extendColumns);
            _this.exportByTemplate.emit({
                excelConfig: excelConfig,
                excelColumns: _this.generateExcelColumns(columns)
            });
            _this.ref.detectChanges();
        };
        this.uploadTemplate = function () { return __awaiter(_this, void 0, void 0, function () {
            var excelConfig;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.excelService.uploadTemplate(this.fullKey, this.validator)];
                    case 1:
                        excelConfig = _a.sent();
                        this.excelConfigs.push({
                            name: excelConfig.name,
                            fullPath: excelConfig.fullPath,
                            removable: true
                        });
                        this.ref.detectChanges();
                        return [2 /*return*/];
                }
            });
        }); };
        this.downloadTemplate = function (excelConfig) {
            _this.excelService.downloadTemplate(excelConfig.fullPath, excelConfig.name);
        };
        this.removeTemplate = function (excelConfig) {
            _this.notifyService.confirm(_this.translateService.translate('Remove template')).then(function () { return __awaiter(_this, void 0, void 0, function () {
                var idx;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.loadingService.start();
                            return [4 /*yield*/, this.excelService.remove(this.fullKey, excelConfig.name).finally(this.loadingService.stop)];
                        case 1:
                            _a.sent();
                            idx = this.excelConfigs.indexOf(excelConfig);
                            this.excelConfigs.splice(idx, 1);
                            this.ref.detectChanges();
                            return [2 /*return*/];
                    }
                });
            }); });
        };
        this.exportDefault = function () { return __awaiter(_this, void 0, void 0, function () {
            var result, excelColumns, extendColumns, columns, columns_2, columns_2_1, column, _a, _b, childColumn;
            var e_5, _c, e_6, _d;
            return __generator(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        this.loadingService.start();
                        return [4 /*yield*/, this.initDefaultTemplate().finally(this.loadingService.stop)];
                    case 1:
                        result = _e.sent();
                        excelColumns = [];
                        extendColumns = this.extendColumns || [];
                        columns = __spread(this.columns, extendColumns);
                        try {
                            for (columns_2 = __values(columns), columns_2_1 = columns_2.next(); !columns_2_1.done; columns_2_1 = columns_2.next()) {
                                column = columns_2_1.value;
                                if (column.type === 'children') {
                                    try {
                                        for (_a = (e_6 = void 0, __values(column.children)), _b = _a.next(); !_b.done; _b = _a.next()) {
                                            childColumn = _b.value;
                                            if (childColumn.type !== 'image') {
                                                excelColumns.push({
                                                    field: childColumn.field,
                                                    title: childColumn.title,
                                                    width: childColumn.width
                                                });
                                            }
                                        }
                                    }
                                    catch (e_6_1) { e_6 = { error: e_6_1 }; }
                                    finally {
                                        try {
                                            if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
                                        }
                                        finally { if (e_6) throw e_6.error; }
                                    }
                                }
                                else if (column.type !== 'image') {
                                    excelColumns.push({
                                        field: column.field,
                                        title: column.title,
                                        width: column.width
                                    });
                                }
                            }
                        }
                        catch (e_5_1) { e_5 = { error: e_5_1 }; }
                        finally {
                            try {
                                if (columns_2_1 && !columns_2_1.done && (_c = columns_2.return)) _c.call(columns_2);
                            }
                            finally { if (e_5) throw e_5.error; }
                        }
                        this.exportByTemplate.emit({
                            excelConfig: {
                                fullPath: result.filePath,
                                name: "[" + this.fullKey + "] Default.xlsx"
                            },
                            excelColumns: excelColumns
                        });
                        this.ref.detectChanges();
                        return [2 /*return*/];
                }
            });
        }); };
        this.newTemplate = function () {
            _this.notifyService.confirmWithInput(_this.translateService.translate('Enter your template name')).then(function (fileName) { return __awaiter(_this, void 0, void 0, function () {
                var exportableColumns, result, excelConfig;
                var _this = this;
                var _a, _b, _c;
                return __generator(this, function (_d) {
                    switch (_d.label) {
                        case 0:
                            this.loadingService.start();
                            fileName = fileName + '.xlsx';
                            _d.label = 1;
                        case 1:
                            _d.trys.push([1, , 3, 4]);
                            if ((_b = (_a = this).validator) === null || _b === void 0 ? void 0 : _b.call(_a, fileName)) {
                                this.notifyService.notify.warning(this.validator(fileName));
                                return [2 /*return*/];
                            }
                            exportableColumns = this.exportableColumns.filter(function (column) { return _this.selected[column.field]; });
                            if (!exportableColumns.length) {
                                exportableColumns = this.exportableColumns;
                            }
                            return [4 /*yield*/, this.generateAndUploadTemplate(exportableColumns, fileName)];
                        case 2:
                            result = _d.sent();
                            if ((_c = result) === null || _c === void 0 ? void 0 : _c.filePath) {
                                excelConfig = {
                                    fullPath: result.filePath,
                                    name: result.fileName,
                                    removable: true
                                };
                                this.excelConfigs.push(excelConfig);
                                this.onExportByTemplate(excelConfig);
                            }
                            return [3 /*break*/, 4];
                        case 3:
                            this.loadingService.stop();
                            return [7 /*endfinally*/];
                        case 4: return [2 /*return*/];
                    }
                });
            }); });
        };
        this.onChangeRadio = function (matRadioChange) {
            var selectedExcelConfig = _this.excelConfigs.find(function (e) { return e.name === matRadioChange.value; });
            if (!selectedExcelConfig) {
                _this.selectedExcelConfig = {
                    name: _this.newExcelConfig
                };
            }
            else {
                _this.selectedExcelConfig = selectedExcelConfig;
            }
            _this.exportableColumns = __spread(_this.columns, (_this.extendColumns || [])).filter(function (e) { return e.type !== 'image'; });
            _this.selected = {};
        };
    }
    Object.defineProperty(GridPopupExportExcelComponent.prototype, "fullKey", {
        get: function () {
            if (!this.key) {
                return '';
            }
            return hash({
                prefix: this.prefix,
                key: this.key
            });
        },
        enumerable: true,
        configurable: true
    });
    GridPopupExportExcelComponent.prototype.ngOnInit = function () {
    };
    GridPopupExportExcelComponent.prototype.ngAfterViewInit = function () {
    };
    GridPopupExportExcelComponent.prototype.open = function () {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (!!this.fullKey) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.exportDefault()];
                    case 1:
                        _c.sent();
                        return [2 /*return*/];
                    case 2: return [4 /*yield*/, this.loadConfiguration()];
                    case 3:
                        _c.sent();
                        this.exportableColumns = __spread(this.columns, (this.extendColumns || [])).filter(function (e) { return e.type !== 'image'; });
                        this.selected = {};
                        if (!((_a = this.selectedExcelConfig) === null || _a === void 0 ? void 0 : _a.name)) {
                            if (((_b = this.excelConfigs) === null || _b === void 0 ? void 0 : _b.length) > 0) {
                                this.selectedExcelConfig = this.excelConfigs[0];
                            }
                            else {
                                this.selectedExcelConfig = {
                                    name: this.newExcelConfig
                                };
                            }
                        }
                        this.modal.open();
                        this.ref.detectChanges();
                        return [2 /*return*/];
                }
            });
        });
    };
    GridPopupExportExcelComponent.prototype.loadConfiguration = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        this.excelConfigs = [];
                        _a = this;
                        return [4 /*yield*/, this.excelService.getFiles(this.fullKey)];
                    case 1:
                        _a.excelConfigs = _b.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    GridPopupExportExcelComponent.ctorParameters = function () { return [
        { type: ChangeDetectorRef },
        { type: LoadingService },
        { type: ExcelService },
        { type: NotifyService },
        { type: TranslateService }
    ]; };
    __decorate([
        ViewChild('modal')
    ], GridPopupExportExcelComponent.prototype, "modal", void 0);
    __decorate([
        Input()
    ], GridPopupExportExcelComponent.prototype, "key", void 0);
    __decorate([
        Input()
    ], GridPopupExportExcelComponent.prototype, "columns", void 0);
    __decorate([
        Input()
    ], GridPopupExportExcelComponent.prototype, "extendColumns", void 0);
    __decorate([
        Input()
    ], GridPopupExportExcelComponent.prototype, "fileName", void 0);
    __decorate([
        Input()
    ], GridPopupExportExcelComponent.prototype, "validator", void 0);
    __decorate([
        Input()
    ], GridPopupExportExcelComponent.prototype, "exportOption", void 0);
    __decorate([
        Output()
    ], GridPopupExportExcelComponent.prototype, "exportByTemplate", void 0);
    GridPopupExportExcelComponent = __decorate([
        Component({
            selector: 'sd-grid-popup-export-excel',
            template: "<sd-modal-control width=\"sm\" [title]=\"'Export excel' | sdTranslate\" #modal>\r\n  <sd-modal-body>\r\n    <mat-radio-group class=\"c-radio-group\" [ngModel]=\"selectedExcelConfig.name\" (change)=\"onChangeRadio($event)\">\r\n      <mat-radio-button class=\"c-radio-button\" *ngFor=\"let excelConfig of excelConfigs\" [value]=\"excelConfig.name\"\r\n        color=\"primary\">\r\n        {{excelConfig.name}}\r\n      </mat-radio-button>\r\n      <mat-radio-button class=\"c-radio-button\" [value]=\"newExcelConfig\" color=\"accent\">\r\n        {{'New template' | sdTranslate}}\r\n      </mat-radio-button>\r\n    </mat-radio-group>\r\n    <div *ngIf=\"selectedExcelConfig.name === newExcelConfig\">\r\n      <mat-chip-list selectable=\"true\" multiple=\"true\">\r\n        <ng-container *ngFor=\"let column of exportableColumns\">\r\n          <mat-chip [selected]=\"selected[column.field]\" (click)=\"selected[column.field] = !selected[column.field]\">\r\n            {{column.title}}\r\n          </mat-chip>\r\n        </ng-container>\r\n      </mat-chip-list>\r\n    </div>\r\n  </sd-modal-body>\r\n  <sd-modal-footer>\r\n    <ng-container *sdDesktop>\r\n      <div class=\"float-right\" *ngIf=\"selectedExcelConfig && selectedExcelConfig.name !== newExcelConfig\">\r\n        <sd-button *ngIf=\"selectedExcelConfig.removable\" class=\"mr-5\" [title]=\"'Delete' | sdTranslate\" icon=\"delete\"\r\n          (action)=\"removeTemplate(selectedExcelConfig)\" size=\"sm\">\r\n        </sd-button>\r\n        <sd-button [title]=\"'Export' | sdTranslate\" icon=\"get_app\" (action)=\"onExportByTemplate(selectedExcelConfig)\"\r\n          size=\"sm\" color=\"primary\">\r\n        </sd-button>\r\n      </div>\r\n      <div class=\"float-right\" *ngIf=\"selectedExcelConfig?.name === newExcelConfig\">\r\n        <sd-button [title]=\"'Add template' | sdTranslate\" icon=\"add\" (action)=\"uploadTemplate()\" size=\"sm\">\r\n        </sd-button>\r\n        <sd-button [title]=\"'Download' | sdTranslate\" icon=\"get_app\" (action)=\"newTemplate()\" size=\"sm\" color=\"primary\">\r\n        </sd-button>\r\n      </div>\r\n    </ng-container>\r\n    <ng-container *sdMobileTablet>\r\n      <ng-container *ngIf=\"selectedExcelConfig && selectedExcelConfig.name !== newExcelConfig\">\r\n        <sd-button *ngIf=\"selectedExcelConfig.removable\" style=\"flex: 1; padding-right: 5px;\"\r\n          [title]=\"'Delete' | sdTranslate\" icon=\"delete\" (action)=\"removeTemplate(selectedExcelConfig)\" size=\"sm\"\r\n          width=\"100%\">\r\n        </sd-button>\r\n        <sd-button style=\"flex: 1;\" [ngClass]=\"{'pl-5':selectedExcelConfig.removable}\" [title]=\"'Export' | sdTranslate\"\r\n          icon=\"get_app\" (action)=\"onExportByTemplate(selectedExcelConfig)\" size=\"sm\" color=\"primary\" width=\"100%\">\r\n        </sd-button>\r\n      </ng-container>\r\n      <ng-container *ngIf=\"selectedExcelConfig?.name === newExcelConfig\">\r\n        <sd-button style=\"flex: 1; padding-right: 5px;\" [title]=\"'Add template' | sdTranslate\" icon=\"add\"\r\n          (action)=\"uploadTemplate()\" size=\"sm\" width=\"100%\">\r\n        </sd-button>\r\n        <sd-button style=\"flex: 1; padding-left: 5px;\" [title]=\"'Download' | sdTranslate\" icon=\"get_app\"\r\n          (action)=\"newTemplate()\" size=\"sm\" color=\"primary\" width=\"100%\">\r\n        </sd-button>\r\n      </ng-container>\r\n    </ng-container>\r\n  </sd-modal-footer>\r\n</sd-modal-control>",
            styles: ["", ".sd-label.sd-label-primary{color:#2f6bff!important}.sd-label.sd-label-success{color:#00bc3c!important}.sd-label.sd-label-info{color:#13c2c2!important}.sd-label.sd-label-warning{color:#fa8c16!important}.sd-label.sd-label-danger{color:#f5222d!important}", "::-webkit-scrollbar{width:7px;height:7px}::-webkit-scrollbar-track{background:#f1f1f1}::-webkit-scrollbar-thumb{background:#888;border-radius:50px}::-webkit-scrollbar-thumb:hover{background:#555}", ".c-radio-group{display:flex;flex-direction:column;margin:15px 0}.c-radio-button{margin:5px}"]
        })
    ], GridPopupExportExcelComponent);
    return GridPopupExportExcelComponent;
}());
export { GridPopupExportExcelComponent };
//# sourceMappingURL=data:application/json;base64, 