import * as i0 from '@angular/core';
import { Injectable, EventEmitter, Component, Input, Output, ViewChild, NgModule } from '@angular/core';
import * as i1 from '@angular/common/http';
import { HttpParams, HttpClientModule } from '@angular/common/http';
import * as XLSX from 'xlsx';
import * as i2 from '@angular/material/tabs';
import { MatTabsModule } from '@angular/material/tabs';
import * as i3 from '@angular/material/grid-list';
import { MatGridListModule } from '@angular/material/grid-list';
import * as i4 from '@angular/material/card';
import { MatCardModule } from '@angular/material/card';
import * as i5 from '@angular/material/button';
import { MatButtonModule } from '@angular/material/button';
import * as i2$1 from '@angular/common';
import { CommonModule, DatePipe } from '@angular/common';
import * as i12 from '@angular/material/input';
import { MatInputModule } from '@angular/material/input';
import * as i6 from '@angular/material/form-field';
import { MatFormFieldModule } from '@angular/material/form-field';
import * as i1$1 from '@angular/router';
import { RouterModule } from '@angular/router';
import * as i4$1 from '@angular/material/icon';
import { MatIconModule } from '@angular/material/icon';
import * as i7 from '@angular/material/datepicker';
import { MatDatepickerModule } from '@angular/material/datepicker';
import * as i8 from '@angular/material/select';
import { MatSelectModule } from '@angular/material/select';
import * as i9 from '@angular/material/core';
import { MatOptionModule } from '@angular/material/core';
import * as i11 from '@angular/forms';
import { FormsModule } from '@angular/forms';
import * as i6$1 from '@angular/material/table';
import { MatTableDataSource, MatTableModule } from '@angular/material/table';
import { jsPDF } from 'jspdf';
import 'jspdf-autotable';
import * as i7$1 from '@angular/material/paginator';
import { MatPaginatorModule } from '@angular/material/paginator';

class ReportsService {
    constructor(httpClient) {
        this.httpClient = httpClient;
    }
    loadGroups(url) {
        return this.httpClient.get(url);
    }
    listReportsByGroupId(url, groupId) {
        return this.httpClient.get(`${url}/${groupId}`);
    }
    getReportWithFilters(url, reportId) {
        return this.httpClient.get(`${url}/${reportId}`);
    }
    executeReport(url, query) {
        // console.log('query', query);
        const params = new HttpParams()
            .set('pageNum', `${query.pageNum}`)
            .set('pageSize', `${query.pageSize}`);
        return this.httpClient.post(`${url}/${query.reportId}`, query.data, { params });
    }
    exportAsExcelFile(json, excelFileName) {
        const header = json; // columns name
        const wscols = [];
        for (let i = 0; i < header.length; i++) { // columns length added
            wscols.push({ wch: header[i].length + 5 });
        }
        // const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
        const table_elt = document.getElementById("excelDataTable");
        const workbook = XLSX.utils.table_to_book(table_elt);
        const ws = workbook.Sheets["Sheet1"];
        XLSX.utils.sheet_add_aoa(ws, [["Created " + new Date().toISOString()]], { origin: -1 });
        ws["!cols"] = wscols;
        XLSX.writeFile(workbook, excelFileName + ".xlsx");
    }
}
ReportsService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ReportsService, deps: [{ token: i1.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
ReportsService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ReportsService, providedIn: 'root' });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ReportsService, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: function () { return [{ type: i1.HttpClient }]; } });

let breakpoint;
function sharedGridLayout(resize, event) {
    let size;
    if (resize) {
        size = event.target.innerWidth;
        //console.log('event',size)
    }
    else {
        size = window.innerWidth;
    }
    switchMethod(size);
    return breakpoint;
}
function switchMethod(size) {
    switch (true) {
        case (size <= 768):
            breakpoint = 1;
            break;
        case (size >= 768 && size <= 992):
            breakpoint = 2;
            break;
        case (size >= 992):
            breakpoint = 3;
            break;
    }
}

class ReportsComponent {
    constructor(reportService) {
        this.reportService = reportService;
        this.reportsGroups = [];
        this.reportsByGroupId = [];
        this.$subs = [];
        this.onViewClicked = new EventEmitter();
        this.breakpoint = 3;
    }
    ngOnInit() {
        this.loadGroups();
    }
    loadGroups() {
        const sub1 = this.reportService
            .loadGroups(this.urlReportGroups)
            .subscribe((res) => {
            this.reportsGroups = res;
            this.$subs.push(sub1);
        });
    }
    listReportsByGroupId(groupId) {
        const sub2 = this.reportService
            .listReportsByGroupId(this.reportGroupByIdUrl, groupId)
            .subscribe((res2) => {
            this.reportsByGroupId = res2;
        });
        this.$subs.push(sub2);
    }
    onTabChanged(event) {
        this.listReportsByGroupId(this.reportsGroups[event].id);
    }
    viewReportFilterDetails(report) {
        this.onViewClicked.emit(report);
    }
    onResize(event) {
        this.breakpoint = sharedGridLayout(true, event);
        // console.log('breakPoint', this.breakpoint);
    }
    ngOnDestroy() {
        this.$subs.forEach((item) => item.unsubscribe());
    }
}
ReportsComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ReportsComponent, deps: [{ token: ReportsService }], target: i0.ɵɵFactoryTarget.Component });
ReportsComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "12.2.16", type: ReportsComponent, selector: "lib-reports-groups", inputs: { urlReportGroups: "urlReportGroups", reportGroupByIdUrl: "reportGroupByIdUrl" }, outputs: { onViewClicked: "onViewClicked" }, ngImport: i0, template: `
    <div class="reportsContainer">
      <div class="title">
        Marketing Reports
      </div>
        <mat-tab-group *ngIf="reportsGroups" (selectedIndexChange)="onTabChanged($event)">
          <mat-tab  [id]="group.id" *ngFor="let group of reportsGroups;let i=index"
                    label="{{group.name}}" >
          <mat-grid-list  class="space" [cols]="breakpoint" (window:resize)="onResize($event)" rowHeight="200px">
            <mat-grid-tile *ngFor="let report of reportsByGroupId">
              <mat-card class="example-card">
                <mat-card-title class="title">{{ report.name }}</mat-card-title>
                <mat-card-content>
                  <p>{{ report.descreption }}</p>
                </mat-card-content>
                <mat-card-actions>
                  <button
                    mat-button
                    class="viewButton"
                    (click)="viewReportFilterDetails(report)"
                  >
                    View
                  </button>
                </mat-card-actions>
              </mat-card>
            </mat-grid-tile>
          </mat-grid-list>
          </mat-tab>
        </mat-tab-group>
    </div>
  `, isInline: true, styles: ["\n      .example-card {\n        max-width: 350px;\n        border-radius: 8px;\n        height: 160px;\n        overflow: auto;\n        width: 93%\n      }\n\n      .viewButton {\n        background: #FF6600;\n        color: #ffffff;\n        float: right;\n      }\n      .title{\n        font-size: 18px;\n        font-weight: 600;\n        letter-spacing: 0.34px;\n        color: #1B1B1B;\n        opacity: 1;\n        margin-bottom: 15px;\n      }\n      .reportsContainer{\n        margin: 30px;\n      }\n      .tabs{\n        margin: 45px;\n      }\n      .space{\n        margin-top: 20px;\n      }\n    "], components: [{ type: i2.MatTabGroup, selector: "mat-tab-group", inputs: ["color", "disableRipple"], exportAs: ["matTabGroup"] }, { type: i2.MatTab, selector: "mat-tab", inputs: ["disabled", "label", "aria-label", "aria-labelledby"], exportAs: ["matTab"] }, { type: i3.MatGridList, selector: "mat-grid-list", inputs: ["cols", "gutterSize", "rowHeight"], exportAs: ["matGridList"] }, { type: i3.MatGridTile, selector: "mat-grid-tile", inputs: ["rowspan", "colspan"], exportAs: ["matGridTile"] }, { type: i4.MatCard, selector: "mat-card", exportAs: ["matCard"] }, { type: i5.MatButton, selector: "button[mat-button], button[mat-raised-button], button[mat-icon-button],             button[mat-fab], button[mat-mini-fab], button[mat-stroked-button],             button[mat-flat-button]", inputs: ["disabled", "disableRipple", "color"], exportAs: ["matButton"] }], directives: [{ type: i2$1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i2$1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { type: i4.MatCardTitle, selector: "mat-card-title, [mat-card-title], [matCardTitle]" }, { type: i4.MatCardContent, selector: "mat-card-content, [mat-card-content], [matCardContent]" }, { type: i4.MatCardActions, selector: "mat-card-actions", inputs: ["align"], exportAs: ["matCardActions"] }] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ReportsComponent, decorators: [{
            type: Component,
            args: [{
                    selector: 'lib-reports-groups',
                    template: `
    <div class="reportsContainer">
      <div class="title">
        Marketing Reports
      </div>
        <mat-tab-group *ngIf="reportsGroups" (selectedIndexChange)="onTabChanged($event)">
          <mat-tab  [id]="group.id" *ngFor="let group of reportsGroups;let i=index"
                    label="{{group.name}}" >
          <mat-grid-list  class="space" [cols]="breakpoint" (window:resize)="onResize($event)" rowHeight="200px">
            <mat-grid-tile *ngFor="let report of reportsByGroupId">
              <mat-card class="example-card">
                <mat-card-title class="title">{{ report.name }}</mat-card-title>
                <mat-card-content>
                  <p>{{ report.descreption }}</p>
                </mat-card-content>
                <mat-card-actions>
                  <button
                    mat-button
                    class="viewButton"
                    (click)="viewReportFilterDetails(report)"
                  >
                    View
                  </button>
                </mat-card-actions>
              </mat-card>
            </mat-grid-tile>
          </mat-grid-list>
          </mat-tab>
        </mat-tab-group>
    </div>
  `,
                    styles: [
                        `
      .example-card {
        max-width: 350px;
        border-radius: 8px;
        height: 160px;
        overflow: auto;
        width: 93%
      }

      .viewButton {
        background: #FF6600;
        color: #ffffff;
        float: right;
      }
      .title{
        font-size: 18px;
        font-weight: 600;
        letter-spacing: 0.34px;
        color: #1B1B1B;
        opacity: 1;
        margin-bottom: 15px;
      }
      .reportsContainer{
        margin: 30px;
      }
      .tabs{
        margin: 45px;
      }
      .space{
        margin-top: 20px;
      }
    `,
                    ],
                }]
        }], ctorParameters: function () { return [{ type: ReportsService }]; }, propDecorators: { urlReportGroups: [{
                type: Input
            }], reportGroupByIdUrl: [{
                type: Input
            }], onViewClicked: [{
                type: Output
            }] } });

class ReportDetailsComponent {
    constructor(reportService, datepipe) {
        this.reportService = reportService;
        this.datepipe = datepipe;
        this.$subs = [];
        this.breakpoint = 3;
        this.onExecuteFired = new EventEmitter();
        this.backClicked = new EventEmitter();
    }
    ngOnInit() {
        this.breakpoint = sharedGridLayout();
        this.loadReportFilters();
    }
    onResize(event) {
        this.breakpoint = sharedGridLayout(true, event);
    }
    loadReportFilters() {
        const sub1 = this.reportService
            .getReportWithFilters(this.loadReportDetailFilters, this.reportId)
            .subscribe((res) => {
            this.reportDetails = res;
        });
        this.$subs.push(sub1);
    }
    ngOnDestroy() {
        this.$subs.forEach((item) => item.unsubscribe());
    }
    validateAndConvertData() {
        var _a, _b;
        if (this.reportDetails && this.reportDetails.reportFilters) {
            for (let i = 0; i < ((_b = (_a = this.reportDetails) === null || _a === void 0 ? void 0 : _a.reportFilters) === null || _b === void 0 ? void 0 : _b.length); i++) {
                this.reportDetails.reportFilters[i].value =
                    this.reportDetails.reportFilters[i].dataType.toLocaleLowerCase() ===
                        'date'
                        ? this.datepipe.transform(this.reportDetails.reportFilters[i].value, 'yyyy-MM-dd')
                        : this.reportDetails.reportFilters[i].value;
            }
        }
        return true;
    }
    execute() {
        var _a;
        if ((_a = this.executeForm) === null || _a === void 0 ? void 0 : _a.invalid) {
            this.executeForm.form.markAllAsTouched();
            return;
        }
        this.validateAndConvertData();
        sessionStorage.setItem('executeForm', JSON.stringify(this.reportDetails.reportFilters));
        sessionStorage.setItem('reportName', this.reportDetails.name);
        this.onExecuteFired.emit({ fired: true });
    }
    onBackClicked() {
        this.backClicked.emit({ back: true });
    }
}
ReportDetailsComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ReportDetailsComponent, deps: [{ token: ReportsService }, { token: i2$1.DatePipe }], target: i0.ɵɵFactoryTarget.Component });
ReportDetailsComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "12.2.16", type: ReportDetailsComponent, selector: "lib-report-details", inputs: { reportId: "reportId", loadReportDetailFilters: "loadReportDetailFilters" }, outputs: { onExecuteFired: "onExecuteFired", backClicked: "backClicked" }, viewQueries: [{ propertyName: "executeForm", first: true, predicate: ["f"], descendants: true }], ngImport: i0, template: "<mat-card class=\"example-card\">\n  <mat-card-title><mat-icon (click)=\"onBackClicked()\" class=\"back-btn\">arrow_back</mat-icon> {{reportDetails?.name}}</mat-card-title>\n  <mat-card-subtitle>{{reportDetails?.descreption}}</mat-card-subtitle>\n  <mat-card-content *ngIf=\"reportDetails\">\n    <form name=\"form\"  #f=\"ngForm\" novalidate >\n      <mat-grid-list class=\"mt-2\" [cols]=\"breakpoint\" (window:resize)=\"onResize($event)\" rowHeight=\"100px\">\n        <mat-grid-tile *ngFor=\"let filter of reportDetails.reportFilters\">\n          <mat-form-field class=\"form-field\" appearance=\"outline\" *ngIf=\"filter.dataType.toLowerCase() == 'date' \">\n            <mat-label class=\"form-label\">{{filter.name}} </mat-label>\n            <input matInput [matDatepicker]=\"picker\" #date=\"ngModel\"\n                   [name]=\"filter.name\" [(ngModel)]=\"filter.value\" [required]=\"filter.required\">\n            <mat-datepicker-toggle matSuffix [for]=\"picker\"></mat-datepicker-toggle>\n            <mat-datepicker #picker></mat-datepicker>\n\n          </mat-form-field>\n\n          <mat-form-field class=\"form-field\" appearance=\"outline\" *ngIf=\"filter.dataType.toLowerCase() == 'text' \">\n            <mat-label class=\"form-label\">{{filter.name}} </mat-label>\n            <input matInput *ngIf=\"filter.dataType.toLowerCase() == 'text' \" [name]=\"filter.name\"\n                   [(ngModel)]=\"filter.value\" [required]=\"filter.required\">\n          </mat-form-field>\n          <mat-form-field class=\"form-field\" appearance=\"outline\" *ngIf=\"filter.dataType.toLowerCase() == 'number' \">\n            <mat-label class=\"form-label\">{{filter.name}} </mat-label>\n            <input matInput type=\"number\" [name]=\"filter.name\"\n                   [(ngModel)]=\"filter.value\" [required]=\"filter.required\" >\n          </mat-form-field>\n\n          <mat-form-field class=\"form-field\" appearance=\"outline\"\n                          *ngIf=\"filter.dataType.toLowerCase() == 'query' || filter.dataType.toLowerCase() ==='lookup'\">\n            <mat-label class=\"form-label\">{{filter.name}} </mat-label>\n            <mat-select *ngIf=\"filter.dataType.toLowerCase() == 'query' || filter.dataType.toLowerCase() ==='lookup'\"\n                        [name]=\"filter.name\" [(ngModel)]=\"filter.value\" [required]=\"filter.required\">\n              <mat-option *ngFor=\"let option of filter.lookUps\" [value]=\"option.id\">{{option.name}}</mat-option>\n            </mat-select>\n          </mat-form-field>\n        </mat-grid-tile>\n      </mat-grid-list>\n    </form>\n    <button  type=\"submit\" mat-button class=\"viewButton\" (click)=\"execute()\">Execute</button>\n\n  </mat-card-content>\n</mat-card>\n", styles: [".example-card{height:100%;width:100%;border-radius:8px}.back-btn{vertical-align:sub;color:#f60;cursor:pointer}.mat-form-field{width:93%}.viewButton{background:#FF6600;color:#fff}\n"], components: [{ type: i4.MatCard, selector: "mat-card", exportAs: ["matCard"] }, { type: i4$1.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { type: i3.MatGridList, selector: "mat-grid-list", inputs: ["cols", "gutterSize", "rowHeight"], exportAs: ["matGridList"] }, { type: i3.MatGridTile, selector: "mat-grid-tile", inputs: ["rowspan", "colspan"], exportAs: ["matGridTile"] }, { type: i6.MatFormField, selector: "mat-form-field", inputs: ["color", "floatLabel", "appearance", "hideRequiredMarker", "hintLabel"], exportAs: ["matFormField"] }, { type: i7.MatDatepickerToggle, selector: "mat-datepicker-toggle", inputs: ["tabIndex", "disabled", "for", "aria-label", "disableRipple"], exportAs: ["matDatepickerToggle"] }, { type: i7.MatDatepicker, selector: "mat-datepicker", exportAs: ["matDatepicker"] }, { type: i8.MatSelect, selector: "mat-select", inputs: ["disabled", "disableRipple", "tabIndex"], exportAs: ["matSelect"] }, { type: i9.MatOption, selector: "mat-option", exportAs: ["matOption"] }, { type: i5.MatButton, selector: "button[mat-button], button[mat-raised-button], button[mat-icon-button],             button[mat-fab], button[mat-mini-fab], button[mat-stroked-button],             button[mat-flat-button]", inputs: ["disabled", "disableRipple", "color"], exportAs: ["matButton"] }], directives: [{ type: i4.MatCardTitle, selector: "mat-card-title, [mat-card-title], [matCardTitle]" }, { type: i4.MatCardSubtitle, selector: "mat-card-subtitle, [mat-card-subtitle], [matCardSubtitle]" }, { type: i2$1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i4.MatCardContent, selector: "mat-card-content, [mat-card-content], [matCardContent]" }, { type: i11.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { type: i11.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { type: i11.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { type: i2$1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { type: i6.MatLabel, selector: "mat-label" }, { type: i12.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl],      input[matNativeControl], textarea[matNativeControl]", inputs: ["id", "disabled", "required", "type", "value", "readonly", "placeholder", "errorStateMatcher", "aria-describedby"], exportAs: ["matInput"] }, { type: i7.MatDatepickerInput, selector: "input[matDatepicker]", inputs: ["matDatepicker", "min", "max", "matDatepickerFilter"], exportAs: ["matDatepickerInput"] }, { type: i11.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { type: i11.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { type: i11.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { type: i11.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { type: i6.MatSuffix, selector: "[matSuffix]" }, { type: i11.NumberValueAccessor, selector: "input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]" }] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ReportDetailsComponent, decorators: [{
            type: Component,
            args: [{
                    selector: 'lib-report-details',
                    templateUrl: './report-details.component.html',
                    styleUrls: ['./report-details.component.css'],
                    // encapsulation: ViewEncapsulation.None,
                }]
        }], ctorParameters: function () { return [{ type: ReportsService }, { type: i2$1.DatePipe }]; }, propDecorators: { reportId: [{
                type: Input
            }], executeForm: [{
                type: ViewChild,
                args: ['f']
            }], loadReportDetailFilters: [{
                type: Input
            }], onExecuteFired: [{
                type: Output
            }], backClicked: [{
                type: Output
            }] } });

class NoDataComponent {
    constructor() { }
    ngOnInit() {
    }
}
NoDataComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: NoDataComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
NoDataComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "12.2.16", type: NoDataComponent, selector: "lib-no-data", ngImport: i0, template: "<div class=\"empty-state\">\n  <div class=\"empty-state__content\">\n    <div class=\"empty-state__icon\">\n      <img\n        src=\"data:image/png;base64, \"\n        alt=\"\">\n    </div>\n    <div class=\"empty-state__message\">No Data has been added yet.</div>\n  </div>\n</div>\n", styles: ["body{background:#ebedf2;font-family:\"Poppins\",sans-serif}.empty-state__message{color:#38a169;font-size:1.5rem;font-weight:500;margin-top:.85rem;text-align:center!important;align-items:center!important}.credit{color:#a2a5b9;font-size:.75rem;text-align:center}a{color:#444}.empty-state__icon{text-align:center}\n"] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: NoDataComponent, decorators: [{
            type: Component,
            args: [{
                    selector: 'lib-no-data',
                    templateUrl: './no-data.component.html',
                    styleUrls: ['./no-data.component.css']
                }]
        }], ctorParameters: function () { return []; } });

class ExecuteReportComponent {
    constructor(route, cd, reportService, datePipe) {
        this.route = route;
        this.cd = cd;
        this.reportService = reportService;
        this.datePipe = datePipe;
        this.backClicked = new EventEmitter();
        this.$subs = [];
        this.query = { total: 0, pageNum: 0, pageSize: 10, data: null, reportId: null };
        this.excel = [];
        this.reportId = +this.route.snapshot.params['id'];
        this.query.reportId = this.reportId;
        const formExecuted = sessionStorage.getItem('executeForm');
        this.executeForm = JSON.parse(formExecuted);
        this.reportName = sessionStorage.getItem('reportName');
        this.query.data = this.executeForm;
    }
    ngOnInit() {
        this.query.pageNum = 1;
        this.loadDataExecuted();
    }
    loadDataExecuted(fileType) {
        const sub1 = this.reportService
            .executeReport(this.urlRpt, this.query)
            .subscribe((res) => {
            switch (fileType) {
                case 'excel':
                    // console.log('res.detailsExcel', res.details);
                    this.hiddenListData = new MatTableDataSource(res.details);
                    this.hiddenData = res;
                    this.hiddenDisplayedColumns = res.headers.map((el) => el.property);
                    this.cd.detectChanges();
                    this.reportService.exportAsExcelFile(this.excel, this.reportName);
                    break;
                case 'pdf':
                    this.hiddenListData = new MatTableDataSource(res.details);
                    this.hiddenData = res;
                    this.hiddenDisplayedColumns = res.headers.map((el) => el.property);
                    this.cd.detectChanges();
                    this.pdfPreparing();
                    break;
                default:
                    this.data = res;
                    this.list = new MatTableDataSource(res.details);
                    this.query.total = res.totalCount;
                    this.displayedColumns = res.headers.map((el) => el.property);
                    break;
            }
        });
        this.$subs.push(sub1);
    }
    ngOnDestroy() {
        this.query = {
            total: 0,
            pageNum: 0,
            pageSize: 10,
            data: null,
            reportId: null,
        };
        // console.log('query', this.query);
        this.$subs.forEach((item) => item.unsubscribe());
    }
    getNextPage(e) {
        this.query.pageNum = e.pageIndex + 1;
        this.query.pageSize = e.pageSize;
        this.loadDataExecuted();
    }
    SavePDF() {
        this.query.pageSize = -1;
        this.query.pageNum = -1;
        this.loadDataExecuted('pdf');
    }
    SaveEXCEL() {
        this.query.pageSize = -1;
        this.query.pageNum = -1;
        this.loadDataExecuted('excel');
    }
    pdfPreparing() {
        const pdfsize = 'a0';
        const doc = new jsPDF('l', 'pt', pdfsize);
        // @ts-ignore
        doc.autoTable({
            html: '#excelDataTable',
            startY: 60,
            margin: { horizontal: 7 },
            styles: {
                fontSize: 50,
                cellWidth: 'wrap'
            },
            columnStyles: {
                1: { cellWidth: 'auto' }
            }
        });
        doc.save(this.reportName + '.pdf');
    }
    onBackClicked() {
        this.backClicked.emit({ back: true });
    }
    check(el, type) {
        if (type === 'Timestamp') {
            el = this.datePipe.transform(el, 'yyyy-MM-dd h:mm a');
        }
        return el;
    }
}
ExecuteReportComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ExecuteReportComponent, deps: [{ token: i1$1.ActivatedRoute }, { token: i0.ChangeDetectorRef }, { token: ReportsService }, { token: i2$1.DatePipe }], target: i0.ɵɵFactoryTarget.Component });
ExecuteReportComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "12.2.16", type: ExecuteReportComponent, selector: "lib-execute-report", inputs: { urlRpt: "urlRpt" }, outputs: { backClicked: "backClicked" }, ngImport: i0, template: "<div class=\"mat-elevation-z8\">\n  <div class=\"backBtn\">\n    <h3><mat-icon (click)=\"onBackClicked()\" class=\"back-btn\">arrow_back</mat-icon> Report Results</h3>\n  </div>\n  <div class=\"btns\">\n    <button *ngIf=\"data?.details.length>0\" type=\"button\" mat-button value=\"PDF\" class=\"btn savePdf\" (click)=\"SavePDF()\">PDF</button>\n    &nbsp;\n    <button *ngIf=\"data?.details.length>0\" type=\"button\" mat-button value=\"XLS\" class=\"btn savePdf\" (click)=\"SaveEXCEL()\">Excel</button>\n  </div>\n\n  <table *ngIf=\"data?.details.length>0\" mat-table [dataSource]=\"list\">\n    <ng-container *ngFor=\"let el of data.headers\" matColumnDef=\"{{el.property}}\">\n      <th mat-header-cell *matHeaderCellDef> {{el.property}} </th>\n      <td mat-cell *matCellDef=\"let row\">\n        <span>{{row[el.property] ? check(row[el.property],el.type) : \"N/A\"}}</span>\n      </td>\n    </ng-container>\n\n    <tr mat-header-row *matHeaderRowDef=\"displayedColumns\"></tr>\n    <tr mat-row *matRowDef=\"let row; columns: displayedColumns;\"></tr>\n    <tr class=\"mat-row\" *matNoDataRow>\n      <td class=\"mat-cell\" colspan=\"4\">No data matching</td>\n    </tr>\n  </table>\n  <mat-paginator  *ngIf=\"data?.totalCount>0\" [length]=\"query.total\"\n                 (page)=\"getNextPage($event)\"\n                 [pageSizeOptions]=\"[10, 25, 100]\">\n  </mat-paginator>\n\n\n  <table style=\"display: none;width: 100%\" mat-table [dataSource]=\"hiddenListData\" id=\"excelDataTable\">\n    <ng-container *ngFor=\"let el of hiddenData?.headers\" matColumnDef=\"{{el.property}}\">\n      <th mat-header-cell *matHeaderCellDef> {{el.property}} </th>\n      <td  mat-cell *matCellDef=\"let row\">\n        <span>{{row[el.property] !== undefined ? check(row[el.property],el.type) : \"N/A\"}}</span>\n<!--        <span *ngIf=\"row[el.type]==='Timestamp'\">{{row[el.property] ? (row[el.property]|date:'short') : 'N/A'}}</span>;-->\n      </td>\n    </ng-container>\n\n    <tr mat-header-row *matHeaderRowDef=\"hiddenDisplayedColumns\"></tr>\n    <tr mat-row *matRowDef=\"let row; columns: hiddenDisplayedColumns;\"></tr>\n    <tr class=\"mat-row\" *matNoDataRow>\n      <td class=\"mat-cell\" colspan=\"4\">No data matching</td>\n    </tr>\n  </table>\n</div>\n\n\n<lib-no-data *ngIf=\"data?.details?.length===0\"></lib-no-data>\n", styles: ["table{width:100%}.savePdf{color:#fff;background-color:#f60;border-color:#f60}.mat-elevation-z8{box-shadow:none;background:#ffffff}.btns{text-align:right;margin-bottom:25px;margin-right:5px}.back-btn{vertical-align:sub;color:#f60;cursor:pointer}h3{font-size:18px;font-weight:600;color:#000}\n"], components: [{ type: i4$1.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { type: i5.MatButton, selector: "button[mat-button], button[mat-raised-button], button[mat-icon-button],             button[mat-fab], button[mat-mini-fab], button[mat-stroked-button],             button[mat-flat-button]", inputs: ["disabled", "disableRipple", "color"], exportAs: ["matButton"] }, { type: i6$1.MatTable, selector: "mat-table, table[mat-table]", exportAs: ["matTable"] }, { type: i6$1.MatHeaderRow, selector: "mat-header-row, tr[mat-header-row]", exportAs: ["matHeaderRow"] }, { type: i6$1.MatRow, selector: "mat-row, tr[mat-row]", exportAs: ["matRow"] }, { type: i7$1.MatPaginator, selector: "mat-paginator", inputs: ["disabled"], exportAs: ["matPaginator"] }, { type: NoDataComponent, selector: "lib-no-data" }], directives: [{ type: i2$1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i2$1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { type: i6$1.MatColumnDef, selector: "[matColumnDef]", inputs: ["sticky", "matColumnDef"] }, { type: i6$1.MatHeaderCellDef, selector: "[matHeaderCellDef]" }, { type: i6$1.MatHeaderCell, selector: "mat-header-cell, th[mat-header-cell]" }, { type: i6$1.MatCellDef, selector: "[matCellDef]" }, { type: i6$1.MatCell, selector: "mat-cell, td[mat-cell]" }, { type: i6$1.MatHeaderRowDef, selector: "[matHeaderRowDef]", inputs: ["matHeaderRowDef", "matHeaderRowDefSticky"] }, { type: i6$1.MatRowDef, selector: "[matRowDef]", inputs: ["matRowDefColumns", "matRowDefWhen"] }, { type: i6$1.MatNoDataRow, selector: "ng-template[matNoDataRow]" }] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ExecuteReportComponent, decorators: [{
            type: Component,
            args: [{
                    selector: 'lib-execute-report',
                    templateUrl: './execute-report.component.html',
                    styleUrls: ['./execute-report.component.css']
                }]
        }], ctorParameters: function () { return [{ type: i1$1.ActivatedRoute }, { type: i0.ChangeDetectorRef }, { type: ReportsService }, { type: i2$1.DatePipe }]; }, propDecorators: { urlRpt: [{
                type: Input
            }], backClicked: [{
                type: Output
            }] } });

class ReportsModule {
}
ReportsModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ReportsModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
ReportsModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ReportsModule, declarations: [ReportsComponent,
        ReportDetailsComponent,
        ExecuteReportComponent,
        NoDataComponent], imports: [CommonModule,
        MatInputModule,
        MatFormFieldModule,
        MatTabsModule,
        MatGridListModule,
        MatCardModule,
        MatButtonModule,
        HttpClientModule,
        RouterModule,
        MatDatepickerModule,
        FormsModule,
        MatSelectModule,
        MatOptionModule,
        MatTableModule,
        MatPaginatorModule,
        MatIconModule], exports: [ReportsComponent,
        ReportDetailsComponent,
        ExecuteReportComponent,
        NoDataComponent] });
ReportsModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ReportsModule, providers: [DatePipe], imports: [[
            CommonModule,
            MatInputModule,
            MatFormFieldModule,
            MatTabsModule,
            MatGridListModule,
            MatCardModule,
            MatButtonModule,
            HttpClientModule,
            RouterModule,
            MatDatepickerModule,
            FormsModule,
            MatSelectModule,
            MatOptionModule,
            MatTableModule,
            MatPaginatorModule,
            MatIconModule
        ]] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.16", ngImport: i0, type: ReportsModule, decorators: [{
            type: NgModule,
            args: [{
                    declarations: [
                        ReportsComponent,
                        ReportDetailsComponent,
                        ExecuteReportComponent,
                        NoDataComponent
                    ],
                    imports: [
                        CommonModule,
                        MatInputModule,
                        MatFormFieldModule,
                        MatTabsModule,
                        MatGridListModule,
                        MatCardModule,
                        MatButtonModule,
                        HttpClientModule,
                        RouterModule,
                        MatDatepickerModule,
                        FormsModule,
                        MatSelectModule,
                        MatOptionModule,
                        MatTableModule,
                        MatPaginatorModule,
                        MatIconModule
                    ],
                    exports: [
                        ReportsComponent,
                        ReportDetailsComponent,
                        ExecuteReportComponent,
                        NoDataComponent
                    ],
                    providers: [DatePipe]
                }]
        }] });

/*
 * Public API Surface of reports
 */

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

export { ExecuteReportComponent, NoDataComponent, ReportDetailsComponent, ReportsComponent, ReportsModule, ReportsService, sharedGridLayout };
//# sourceMappingURL=reports-hyper74.js.map
