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';
import { moveItemInArray } from '@angular/cdk/drag-drop';
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 () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        columns = columns || [];
                        return [4 /*yield*/, this.excelService.generateExcelTemplate({
                                fileName: fileName || this.fileName,
                                columns: this.generateExcelColumns(columns)
                            })];
                    case 1: return [2 /*return*/, _a.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.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_3, _c, e_4, _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_4 = 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_4_1) { e_4 = { error: e_4_1 }; }
                                    finally {
                                        try {
                                            if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
                                        }
                                        finally { if (e_4) throw e_4.error; }
                                    }
                                }
                                else if (column.type !== 'image') {
                                    excelColumns.push({
                                        field: column.field,
                                        title: column.title,
                                        width: column.width
                                    });
                                }
                            }
                        }
                        catch (e_3_1) { e_3 = { error: e_3_1 }; }
                        finally {
                            try {
                                if (columns_2_1 && !columns_2_1.done && (_c = columns_2.return)) _c.call(columns_2);
                            }
                            finally { if (e_3) throw e_3.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 file name')).then(function (fileName) { return __awaiter(_this, void 0, void 0, function () {
                var result, excelConfig;
                var _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            this.loadingService.start();
                            _b.label = 1;
                        case 1:
                            _b.trys.push([1, , 5, 6]);
                            return [4 /*yield*/, this.initTemplate(this.exportableColumns, fileName)];
                        case 2:
                            result = _b.sent();
                            if (!((_a = result) === null || _a === void 0 ? void 0 : _a.filePath)) return [3 /*break*/, 4];
                            return [4 /*yield*/, this.excelService.uploadTemplate(this.fullKey, this.validator)];
                        case 3:
                            excelConfig = _b.sent();
                            this.excelConfigs.push({
                                name: excelConfig.name,
                                fullPath: excelConfig.fullPath,
                                removable: true
                            });
                            this.exportByTemplate.emit({
                                excelConfig: excelConfig,
                                excelColumns: this.exportableColumns
                            });
                            _b.label = 4;
                        case 4: return [3 /*break*/, 6];
                        case 5:
                            this.loadingService.stop();
                            return [7 /*endfinally*/];
                        case 6: 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 || []));
            _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 || []));
                        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.prototype.drop = function (event) {
        moveItemInArray(this.exportableColumns, event.previousIndex, event.currentIndex);
    };
    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([
        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        {{'Create new' | 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\">\r\n        <mat-chip *ngFor=\"let column of exportableColumns\" (click)=\"selected[column.field] = !selected[column.field]\"\r\n          [color]=\"selected[column.field] ? 'primary':''\">\r\n          {{column.title}}\r\n        </mat-chip>\r\n      </mat-chip-list>\r\n    </div>\r\n  </sd-modal-body>\r\n  <sd-modal-footer>\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]=\"'Generate template' | sdTranslate\" icon=\"get_app\" (action)=\"generateTemplate()\" size=\"sm\"\r\n        color=\"primary\">\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  </sd-modal-footer>\r\n</sd-modal-control>",
            styles: [".btn{color:#fff;background-color:#919191;border-color:#919191;box-shadow:0 2px 2px 0 rgba(153,153,153,.14),0 3px 1px -2px rgba(153,153,153,.2),0 1px 5px 0 rgba(153,153,153,.12)}.btn:active,.btn:hover{box-shadow:0 14px 26px -12px rgba(153,153,153,.14),0 3px 1px -2px rgba(153,153,153,.2),0 1px 5px 0 rgba(153,153,153,.12)}.btn.btn-sm{padding:.2rem .5rem;font-size:11px}.btn.btn-xs{padding:.1rem .3rem;font-size:9px}.btn.btn-round{border-radius:30px}.btn.btn-primary{color:#fff;background-color:#c82c37;border-color:#c82c37;box-shadow:0 2px 2px 0 rgba(156,39,176,.14),0 3px 1px -2px rgba(156,39,176,.2),0 1px 5px 0 rgba(156,39,176,.12)}.btn.btn-primary:active,.btn.btn-primary:hover{box-shadow:0 14px 26px -12px rgba(156,39,176,.42),0 4px 23px 0 rgba(0,0,0,.12),0 8px 10px -5px rgba(156,39,176,.2)}.btn.btn-info{color:#fff;background-color:#00bcd4;border-color:#00bcd4;box-shadow:0 2px 2px 0 rgba(0,188,212,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,188,212,.12)}.btn.btn-info:active,.btn.btn-info:hover{box-shadow:0 14px 26px -12px rgba(0,188,212,.42),0 4px 23px 0 rgba(0,0,0,.12),0 8px 10px -5px rgba(0,188,212,.2)}.btn.btn-success{color:#fff;background-color:#4caf50;border-color:#4caf50;box-shadow:0 2px 2px 0 rgba(76,175,80,.14),0 3px 1px -2px rgba(76,175,80,.2),0 1px 5px 0 rgba(76,175,80,.12)}.btn.btn-success:active,.btn.btn-success:hover{box-shadow:0 14px 26px -12px rgba(76,175,80,.42),0 4px 23px 0 rgba(0,0,0,.12),0 8px 10px -5px rgba(76,175,80,.2)}.btn.btn-warning{color:#fff;background-color:#ff9800;border-color:#ff9800;box-shadow:0 2px 2px 0 rgba(255,152,0,.14),0 3px 1px -2px rgba(255,152,0,.2),0 1px 5px 0 rgba(255,152,0,.12)}.btn.btn-warning:active,.btn.btn-warning:hover{box-shadow:0 14px 26px -12px rgba(255,152,0,.42),0 4px 23px 0 rgba(0,0,0,.12),0 8px 10px -5px rgba(255,152,0,.2)}.btn.btn-danger{color:#fff;background-color:#f44336;border-color:#f44336;box-shadow:0 2px 2px 0 rgba(244,67,54,.14),0 3px 1px -2px rgba(244,67,54,.2),0 1px 5px 0 rgba(244,67,54,.12)}.btn.btn-danger:active,.btn.btn-danger:hover{box-shadow:0 14px 26px -12px rgba(244,67,54,.42),0 4px 23px 0 rgba(0,0,0,.12),0 8px 10px -5px rgba(244,67,54,.2)}", ".sd-label{font-weight:500;color:#919191!important}.sd-label.sd-label-primary{color:#c82c37!important}.sd-label.sd-label-success{color:#4caf50!important}.sd-label.sd-label-info{color:#00bcd4!important}.sd-label.sd-label-warning{color:#ff9800!important}.sd-label.sd-label-danger{color:#f44336!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, 