import { Component, OnInit, Input, Inject, TemplateRef, ViewChild, NgZone, ViewEncapsulation, HostListener, OnDestroy, SimpleChanges, EventEmitter, Output } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { RESIZE_EVENT } from '../datagrid/window-resize';

import { FlexmonsterPivot } from "../datagrid/flexmonster/flexmonster.angular4";
import { DashboardService } from '../dashboard/dashboard.service';

// import { Subscription } from 'rxjs/Subscription';
import { Subscription } from 'rxjs';
import {MatDialog,MAT_DIALOG_DATA,MatDialogRef} from '@angular/material/dialog';
import { OpenDialogComponent } from './open-dialog-box/open-dialog.component';

@Component({
    selector: 'fm-component',
    templateUrl: './fm-component.component.html',
    styleUrls: ['./fm-component.component.css'],
    // encapsulation: ViewEncapsulation.Native
    encapsulation: ViewEncapsulation.None
})
export class FmComponentComponent implements OnInit, OnDestroy {

    @Input('data') reportData: any;
    @Input('elWidth') elWidth:any;
    //Added by Mayur Pawar on 05/04/21 to remove options toolbar in FM
    @Input('hideOptions') hideOptions:any;
    @ViewChild('fmComponent') fmComponent!: FlexmonsterPivot;
	// Added by Mahesh Saggam on 28-JULY-21 [to hide or show the toolbar based on flag]
    toolbar = true;
    height = '500';

    // @ViewChild('pivotGrid') pivotGrid: FlexmonsterPivot;

    licenseKey:any;
    compFolder:any;
    hostUrl:any;
    contWidth:any;
    pluginMetadata:any;
    viewType:any;
    chartType:any;
    type:any;
    reportConfig:any;
    reportName:any;
    reportLoaded = false;
    myLayoutSubcription: Subscription | any;
    otherLayoutSubcription: Subscription | any;
    reportSubcription: Subscription | any;
    isExpanded: boolean = false;
    layoutReportData:any;
    prefName:any;
    selectedLayout:any;
    //gridType;
    expandedAll: boolean =false;
    expanded: boolean =false;
    getReportData:any;
    reportDataFileName:any;//Added by shrutika on 16-09-19 for issue in report, updated data not display.
    elemId = "fm-comp-view";
    @Output() onDrillDown: EventEmitter<any> = new EventEmitter<any>();

    constructor(private http: HttpClient, public zone: NgZone, private dashboardService: DashboardService, public dialog: MatDialog) { }

    ngOnInit() {

        // this.compFolder = this.licenseKey ? "dashboard/assets/flexmonster/" : "https://cdn.flexmonster.com/";
        console.log("PivotGridComponent [ngOnInit]", this.pluginMetadata, this.licenseKey, this.reportData, "compFolder==>", this.compFolder, "elWidth==>", this.elWidth);
        if(this.reportData)
        {
            this.toolbar = this.reportData.toolbar == undefined ? (true) : (this.reportData.toolbar);
            this.height = this.reportData.height == undefined ? '500' : this.reportData.height;
            if(this.reportData['elemId'] != undefined)
            {
                this.elemId = this.reportData['elemId'];
            }
        }
        console.log('Print toolbar line 64::: ', this.toolbar);
        if (this.pluginMetadata) {
            this.reportData = this.pluginMetadata.compData.data;
        //Added by shrutika on 16-09-19 [Start] for issue in report, updated data not display.
         this.reportDataFileName = this.reportData.filename ;
         console.log('Inside oninit.......376[',this.reportDataFileName);
        }

        if (this.reportData.explore_details) {
            this.viewType = this.reportData.explore_details.viewType;
            console.log('viewType in explore report==>',this.viewType);
            this.type = this.reportData.explore_details.type;
            console.log('type insode expolore details',this.type)
            this.reportName = this.reportData.explore_details.reportFile || this.reportData.metadataname + this.reportData.compId + "_report";
            console.log('Report name if exploreDetails=>', this.reportName);
        } else {
            //Change by pratheek on 13-08-19 for Explore option to be added in home screen and report. 
           // this.reportName = this.reportData.metadataname + this.reportData.compId + "_report";
           this.reportName = this.reportData.reportName || ( this.reportData.metadataname + this.reportData.compId + "_report" );
            console.log('Report name in else=>', this.reportName);
        }
        this.prefName = this.reportName;
        
        // this.dashboardService.setReportName(this.reportName);

        this.licenseKey = this.reportData.licenseKey;
        //this.compFolder =  "https://cdn.flexmonster.com/";

        if (this.hostUrl) {
            RESIZE_EVENT.subscribe(
                (clientWidth:any) => {
                    console.log('on device width resize', clientWidth);
                    this.elWidth = clientWidth;
                    if (this.fmComponent) {
                        this.fmComponent.flexmonster.refresh();
                        this.zone.run(() => {
                            console.log('view refreshed');
                        });
                    }
                }
            );
        }

        if (this.reportData.explore_details && this.reportData.explore_details.reportConfig) {
            this.reportConfig = this.reportData.explore_details.reportConfig;
            //Change by shrutika on 16-09-19 [Start] for issue in report, updated data not display.
            //this.reportConfig.dataSource['data'] = this.reportData.data.data || this.reportData.data;
            this.reportConfig.dataSource = this.getCurrentDataSource();
            this.reportLoaded = true;
        }
        else {
            //  var repoName = this.dashboardService.getCurrReportName();
            //console.log('repoName===>',repoName);

            /*
            this.reportSubcription = this.fetchReport(this.reportName).subscribe(
                response => {
                    console.log('Response of getExploreReport', this.reportName, response);
                    this.reportLoaded = true;
                    if (response && response != null && Object.keys(response).length) {
                        this.reportConfig = response;
                        this.reportConfig.dataSource['data'] = this.reportData.data.data || this.reportData.data;
                    }
                    this.onReportComplete();
                }
            );
            */
            //this.onReportComplete();
            //this.applyReport(this.reportName,'','');
        }
        this.myLayouts(this.reportName); //TO show Layout Data on Load
        
    }
   
    ngOnChanges(changes: SimpleChanges) 
    {
        console.log('Print inside onChanges of fm-component::::: ', changes);
        console.log('ngOnChanges in fm component', this.contWidth, this.elWidth);
        
        if (!this.hostUrl && this.elWidth != 0 && this.contWidth != this.elWidth && this.fmComponent && this.fmComponent.flexmonster) 
        {
            console.log('on element width resize');
            this.contWidth = this.elWidth;
            console.log('on contWidth resize', this.contWidth);
            this.fmComponent.flexmonster.refresh();
        }
         //Added by Samruddhi Pawar for Dashboard Definition on 15/03/21 [Start]
        if(this.reportData.chartDetails == "true")
        {
                    this.viewType = this.reportData.explore_details.viewType;
                    console.log('viewType in explore report==>2',this.viewType);
                    this.type = this.reportData.explore_details.type;
                    console.log('type inside explore details',this.type)
                    this.reportName = this.reportData.explore_details.reportFile || this.reportData.metadataname + this.reportData.compId + "_report";
                    console.log('Report name if exploreDetails=>', this.reportName);
            
                    console.log('Report data......', this.reportData);
                    this.onReportComplete();
        }
        //Added by Samruddhi Pawar for Dashboard Definition on 15/03/21 [End]
       // Added by Mahesh Saggam [16-DEC-2020] [for incentive process] Start
        if(this.fmComponent != undefined && this.fmComponent.flexmonster != undefined){
            console.log('Print line no 140:::::: ', this.reportData);
            this.fmComponent.flexmonster.updateData({
                data: this.reportData.data.data
            });
        }
        // Added by Mahesh Saggam [16-DEC-2020] [for incentive process] End
    }

    onReportComplete(): void {
		// Added by Mahesh Saggam on 28-JULY-21 [to hide or show the toolbar based on flag]
        console.log('On Report Complete', this.toolbar, this.hideOptions);
        if(this.reportData && this.reportData['callFromVisual'] != undefined && this.reportData['callFromVisual'])
        {
            console.log('Print inside onreport complete callFromVisual ', this.reportData['callFromVisual'])
            this.fmComponent.flexmonster.off("reportcomplete");
            this.fmComponent.flexmonster.setReport(this.reportData);
            this.onReportChange();
            document.getElementById(this.elemId)?.addEventListener('click', this.onBarClick.bind(this));
            return;
        }
        //Added by Samruddhi to hide toolbar in fm-data for visual_definition and visual_process on 16-04-21 [Start]
        if(this.hideOptions != undefined)
        {
            console.log('Hide options toolbar 249'); //Added on 15-04-21
            let elem = document.getElementById("fm-toolbar-wrapper");
            if(elem != null)
            {
                //elem.setAttribute('style', 'display: none;');
                if(elem.nextElementSibling != null)
                {
                    elem.nextElementSibling.setAttribute("style", "height: 100%;");
                }
            }
        }
        //Added by Samruddhi to hide toolbar in fm-data for visual_definition and visual_process on 16-04-21 [End]
         var reportConfig = {};
        //Added by Samruddhi Pawar for Dashboard Definition on 15/03/21 [Start]
        if(this.reportData.chartDetails == "true")
        {
            console.log('if reportConfig.........1701', this.viewType);
            //Added by Nikhil Mhetre for visual definition on 07-04-2021
            if (this.viewType === "charts" || this.viewType === "compact") {
                reportConfig = this.initChartReport();
            }
            else {
                reportConfig = this.initGridReport();
            }
        }
        //Added by Samruddhi Pawar for Dashboard Definition on 15/03/21 [End]
        else if(this.reportConfig) {
            //Change by shrutika on 16-09-19 [Start] for issue in report, updated data not display.
            //this.reportConfig.dataSource['data'] = this.reportData.data.data || this.reportData.data;
            this.reportConfig.dataSource = this.getCurrentDataSource();
            reportConfig = this.reportConfig;
        }
        else {
            if (this.viewType === "charts") {
                reportConfig = this.initChartReport();
            }
            else {
                reportConfig = this.initGridReport();
            }
        }

        /*
        var reportConfig = {
           dataSource: {
                dataSourceType: "json",
                data: this.reportData.data.data || this.reportData.data
           },
            options : {
               viewType: this.viewType || "grid",
               grid: {
                   type: this.type || "flat"
               },
               chart: {
                type: this.type || "bar",
                autoRange: false,
                showFilter: false,
                showMeasures: false
               },
               configuratorButton : false,
               showGrandTotals : this.reportData.slice ? this.reportData.slice.showGrandTotals : 'of',
               showTotals : this.reportData.slice ? this.reportData.slice.showTotals : 'of',
               showCalculatedValuesButton: false,
               showDrillThroughConfigurator: false
          },
          rows: this.reportData.slice ? this.reportData.slice.rows : [],
          //columns: this.reportData.slice ? this.reportData.slice.columns : [],
          measures: this.reportData.slice ? this.reportData.slice.measures : [] 
        };
        */
        var currReport;
        if (this.fmComponent && this.fmComponent.flexmonster) {
            currReport = this.fmComponent.flexmonster.getReport();
        }
        console.log('--- currReport -- ', currReport, this.reportLoaded);
	// Changes made by Mahesh Saggam on 02-AUG-21 [Not able to set report when cuuReport is null]
        if (this.fmComponent && this.reportLoaded) {
            this.fmComponent.flexmonster.off("reportcomplete");
            this.fmComponent.flexmonster.setReport(reportConfig);
            console.log('reportConfig:::', reportConfig);
            console.log('Print reportConfig in string:::: ', JSON.stringify(reportConfig))
            console.log('fmComponent:::', this.fmComponent);

            if (this.reportData.filterInfo) {
                var column = this.reportData.filterInfo.column;
                var value = this.reportData.filterInfo.value;
                this.fmComponent.flexmonster.setFilter(
                    column, this.getColumnVals(column, value)
                );
            }
        }
        console.log('End of if block 245', this.hideOptions); //Added on 15-04-21

        //Added by Mayur Pawar on 05/04/21 to remove options toolbar in FM [Start]
        // if(this.hideOptions != undefined)
        // {
        //     console.log('Hide options toolbar 249'); //Added on 15-04-21
        //     let elem = document.getElementById("fm-toolbar-wrapper");
        //     if(elem != null)
        //     {
        //         elem.setAttribute('style', 'display: none;');
        //         if(elem.nextElementSibling != null)
        //         {
        //             elem.nextElementSibling.setAttribute("style", "height: 100%;");
        //         }
        //     }
        // }
        //Added by Mayur Pawar on 05/04/21 to remove options toolbar in FM [End]

        this.onReportChange();
    }

    //TO apply selected layout On click of Apply button 
    applyReport(objName:any, prefName:any, userId:any): void {
        console.log('reportConfig:::', this.reportConfig);
        console.log('fmComponent:::', this.fmComponent);
        if (!this.reportConfig || !this.fmComponent) return;
        console.log('inside applyReport fmComponent:::', this.reportDataFileName);
          //Change by shrutika on 16-09-19 [Start] for issue in report, updated data not display.
        //this.reportConfig.dataSource['data'] = this.reportData.data.data || this.reportData.data;
        this.reportConfig.dataSource = this.getCurrentDataSource();
        //Added by shrutika on 16-09-19 [End] for issue in report, updated data not display.

        setTimeout(() => {
            /*var viewType = this.reportConfig['options'].grid.type;
            if(viewType === 'flat'){
                console.log('inside if viewType at customize Toolbar====>',viewType)
                this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-expand-all").style.display = 'none';
            }*/
            this.onReportChange();
        }, 200);
        var reportConfig = this.reportConfig;
		//Change made by Pratheek on 13-08-19[ to open report data and homepage data in flexmonster]-Start	
        if (this.fmComponent && this.reportData.filterInfo) {
            console.log('when report is applied inside fm-component');
            var viewType = this.reportConfig['options'].grid.type;
            console.log('viewType ==>',viewType)
            this.fmComponent.flexmonster.off("reportcomplete");
            this.fmComponent.flexmonster.setReport(reportConfig);
            if (this.reportData.filterInfo) {
                var column = this.reportData.filterInfo.column;
                var value = this.reportData.filterInfo.value;
                this.fmComponent.flexmonster.setFilter(
                    column, this.getColumnVals(column, value)
                );
            }

            this.fmComponent.flexmonster.refresh();
        }
    }

    myLayouts(reportName:any) {
        this.myLayoutSubcription = this.getAllReportLayout(reportName).subscribe((response:any) => {
            console.log('Response of getAllLayoutReport', reportName, response);
            this.reportLoaded = true;
            if (response && response != null && Object.keys(response).length) {
                this.layoutReportData = response;
                
                var selectedLayout:any = localStorage.getItem(this.reportName+"_selected_layout");
                
                if (selectedLayout && selectedLayout != null && selectedLayout.trim())
                {
                    selectedLayout = JSON.parse(selectedLayout);
                    this.reportConfig = selectedLayout['layoutConfig'];
                    this.selectedLayout = selectedLayout['layoutID'];
                    this.prefName = selectedLayout['layoutName'];
                    
                    console.log('my layout report config==>', this.reportConfig);
                    this.applyReport(reportName, prefName, userName);
                }
                else if (response.allLayoutPref && response.allLayoutPref.MY_LAYOUT[0]) {
                    var myLayout = response.allLayoutPref.MY_LAYOUT[0];
                    var userName = myLayout.userId;
                    var prefName = myLayout.prefName;
                    
                    var selReportConfig = localStorage.getItem(this.reportName+"_selected_layout");
                    
                    if (selReportConfig && selReportConfig != null && selReportConfig.trim())
                    {
                        selReportConfig = JSON.parse(selReportConfig);
                        this.reportConfig = selReportConfig;
                    }
                    else
                    {
                        this.reportConfig = myLayout.prefValue;
                    }
                    
                    this.prefName = prefName;
                    this.selectedLayout = myLayout.objName+myLayout.prefName+myLayout.userId;
                    console.log('my layout report config==>', this.reportConfig);
                    this.applyReport(reportName, prefName, userName);
                }
            }
        })
    }


    customizeToolbar(toolbar:any) {
        console.log('Print toolbar inside customizeToolbar::: ', toolbar);
	// Added by Mahesh Saggam on 28-JULY-21 [Error occurs when toolbar is undefined]
        if(toolbar)
        {       
            var tabs = toolbar.getTabs();
            var openHandleFunc = this.tabOpenHandler.bind(this)
            var handlerFunc = this.tabHandler.bind(this);
            var expandAllFunc = this.expandAll.bind(this);
            var expandFunc = this.expand.bind(this);
            var collaspseAllFunc = this.collapseAllData.bind(this);
            var collapseFunct = this.collapseData.bind(this);

            toolbar.getTabs = function () {
                console.log('tabs', tabs);
                delete tabs[0];
                // delete tabs[1];
                delete tabs[4];

                delete tabs[3].menu[0];
                delete tabs[3].menu[4];

                tabs[1] = {
                    icon: this.icons.open,
                    title: "Open",
                    handler: openHandleFunc
                };

                tabs[2] = {
                    icon: this.icons.save,
                    title: "Save",
                    handler: handlerFunc
                };

                //Added Expand And Expand All and Collapse and Collapse All tab Start  
                tabs[13] = {
                    id: "fm-tab-expand-all",
                    title: "Expand All",
                    handler: expandAllFunc
                };
                
                tabs[14] = {
                    id: "fm-tab-collapse-all",
                    title: "Collapse All",
                    handler: collaspseAllFunc
                };
                        
            tabs[15] = {
                    id: "fm-tab-expand",
                    title: "Expand",
                    handler: expandFunc
                };
                
                
            tabs[16] = {
                        id: "fm-tab-collapse",
                        title: "Collapse",
                        handler: collapseFunct
                };
                
                return tabs;
                //Added Expand And Expand All and Collapse and Collapse All tab End
            }
            setTimeout(() => {
                /*var viewType = this.reportConfig['options'].grid.type;
                if(viewType === 'flat'){
                    console.log('inside if viewType at customize Toolbar====>',viewType)
                    this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-expand-all").style.display = 'none';
                }*/
                this.onReportChange();
            }, 200);
        }
    }
    
    initGridReport() {
        console.log('Inside initGridReport::: 472 ', this.reportData);//Added on 16-04-21

        //Added by shrutika on 13-08-19 [Start] for Explore option to be added in home screen and report. 
        var localDataSource = {
            dataSourceType: "json",
            data: this.reportData.data.data || this.reportData.data,
            mapping: this.reportData.mapping ? this.reportData.mapping : {},
        }

        var serverDataSource = {
            filename : this.reportData.filename
        }
        var reportConfig = {
            /* dataSource: {
                dataSourceType: "json",
                data: this.reportData.data.data || this.reportData.data
            }, */

         dataSource : this.reportData.filename ? serverDataSource : localDataSource,
        //Added by shrutika on 13-08-19 [End] for Explore option to be added in home screen and report. 
            options: {
                viewType: "grid",
                grid: {
                    type: this.type || "flat"
                },
                configuratorButton: false,
                showGrandTotals: this.reportData.slice ? this.reportData.slice.showGrandTotals : 'of',
                showTotals: this.reportData.slice ? this.reportData.slice.showTotals : 'of',
                showCalculatedValuesButton: false,
                showDrillThroughConfigurator: false
            },
            rows: this.reportData.slice ? this.reportData.slice.rows : [],
            columns: this.reportData.columnsList ? this.reportData.columnsList : [],
            //columns: this.reportData.slice ? this.reportData.slice.columns : [],
            measures: this.reportData.slice ? this.reportData.slice.measures : [],
            width: "100%",
            height: "100%",
            //Added by shrutika on 06-12-19[Start] for display blank space instead of invalid date or blank text in Explore option.
            localization: {
                grid: {
                  blankMember: "",
                  dateInvalidCaption: ""
                }
              },
			formats: this.reportData.formats ? this.reportData.formats : []
              //Added by shrutika on 06-12-19[End] for display blank space instead of invalid date or blank text in Explore option.
        };
        return reportConfig;
    }

    initChartReport() {
        console.log('Inside initChartReport');
        //TODO 
        //if condition Added by Mayur Pawar for Dashboard Definition on 15/03/21 [Start]
        if(this.reportData.chartDetails != "true")
        {
            var xAxisCol = this.findInArray(this.reportData.column_group, 'id', 'x-axis');
            var yAxisCol = this.findInArray(this.reportData.column_group, 'id', 'y-axis');
            console.log('Inside X-AXis and Y-AXis ===> ', xAxisCol, yAxisCol);
        }
        //if condition Added by Mayur Pawar for Dashboard Definition on 15/03/21 [End]
        //Added by Nikhil Mhetre for Dashboard Definition on 15/03/21 [Start]
        if(this.reportData.chartDetails == "true")
        {
           console.log('line no 455');
            let reportConfig = {
            dataSource: {
                dataSourceType: "json",
                data: this.reportData.data.data || this.reportData.data,
                mapping: this.reportData.mapping ? this.reportData.mapping : {},
            },

            options:this.reportData.options,
            // columns: this.reportData.columnsList ? this.reportData.columnsList : [],
            slice:this.reportData.slice,
            width: "100%",
            height: "100%",
			formats: this.reportData.formats ? this.reportData.formats : [],
            };
            return reportConfig;
        }
        //Added by Nikhil Mhetre for Dashboard Definition on 15/03/21 [End]
        else
        {
        console.log('line no 474');
        let reportConfig = {
            dataSource: {
                dataSourceType: "json",
                data: this.reportData.data.data || this.reportData.data,
                mapping: this.reportData.mapping ? this.reportData.mapping : []
            },
            options: {
                viewType: "charts",
                chart: {
                    type: this.type || "bar",
                    autoRange: false,
                    showFilter: false,
                    showMeasures: false
                },
                configuratorActive: false,
                configuratorButton: false,
                drillThrough: false,
                showCalculatedValuesButton: false,
                showDrillThroughConfigurator: false
            },
            columns: this.reportData.columnsList ? this.reportData.columnsList : [],
            slice: {
                rows: [{
                    uniqueName: xAxisCol.id,
                    caption: xAxisCol.value,
                    sortOrder: xAxisCol.sortOrder ? xAxisCol.sortOrder.split(',') : ""
                }],
                columns: [{
                    uniqueName: "[Measures]"
                }
                ],
                measures: [{
                    uniqueName: yAxisCol.id,
                    caption: yAxisCol.value,
                    aggregation: yAxisCol.aggrFunction
                }
                ],
            },
            width: "100%",
            height: "100%"
        };
        return reportConfig;
        }
    }

    findInArray(array:any, key:any, value:any) {

        var foundObj = array.find((obj:any) => obj[key] === value);
        if (foundObj && foundObj.columns && foundObj.columns.length > 0) {
            return foundObj.columns[0];
        } else {
            return { "id": "COLNOTDEF", "value": "Column is not configured" };
        }
    }

    tabHandler() {
        /* var confirmSave = confirm("Confirm Save ?");
         if (confirmSave) {
             var report = this.fmComponent.flexmonster.getReport();
             console.log('On Save Click',report,this.reportName);
             this.saveReportInCache(this.reportName, report);
         } */
        console.log("on click of save tabHandler");
        const dialogRef = this.dialog.open(OpenDialogComponent, { disableClose: true, data: { 'template': 'SAVE_DIALOG', 'reportName': this.prefName } });

        dialogRef.afterClosed().subscribe(resp => {
            console.log('The dialog result after was closed==>', resp);
            if (resp) {
                console.log('called=>', resp);
                var layoutName = resp;
                 //Added by shrutika on 16-09-19 for issue in report, updated data not display.
                var report : any = this.fmComponent.flexmonster.getReport();
                console.log('On Save Click', report, this.reportName);
                console.log('datsource inside tabhandler', report.dataSource.dataSourceType);
                //Added by shrutika on 16-09-19 [End] for issue in report, updated data not display.
                if(report.dataSource.dataSourceType == "csv")
                {
                   report.dataSource.filename = "";
                }
                //Added by shrutika on 16-09-19 [End] for issue in report, updated data not display.
                localStorage.removeItem(this.reportName+"_selected_layout");
                this.saveReportInCache(this.reportName, layoutName, report);
                //this.dashboardService.setReportName(this.reportName);
            }
        });
    }

    //On click of Open button Start
    tabOpenHandler() {
        const openDialogRef = this.dialog.open(OpenDialogComponent, { disableClose: true, data: { 'template': 'OPEN_DIALOG', 'layoutReport': this.layoutReportData, 'selectedLayout': this.selectedLayout } });
        openDialogRef.afterClosed().subscribe(result => {
            console.log('The dialog result after was closed==>', result);
            if (result) {
                console.log('result on pen tab click==>', result);
                //this.reportConfig = result;
                //this.applyReport(this.reportName, result.pref_name, result.LAYOUT_OWNER);
               // this.fetchReport(this.reportName, result.prefName, result.LAYOUT_OWNER);
                this.prefName = result.prefName;
                this.selectedLayout = result.objName+result.prefName+result.userId;
                this.fetchReport( result.userId,result.prefName, this.reportName );
            }
        });
    }
    //On click of Open button End

    fetchReport(userId:any,prefName:any, objName:any) {
        //return this.dashboardService.getExploreReport(reportName);
        this.reportSubcription = this.dashboardService.getExploreReport(userId,objName, prefName).subscribe(
            (response:any) => {
                console.log('Response of getExploreReport', this.reportName, "resp==>",response,"userId==>",userId,"prefName==>",prefName);
                this.reportLoaded = true;
                if (response && response != null && Object.keys(response).length) {
                    this.reportConfig = response;
                    
                    var layoutDetails:any = {};
                    layoutDetails['layoutID'] = this.selectedLayout;
                    layoutDetails['layoutName'] = prefName;
                    layoutDetails['layoutConfig'] = this.reportConfig;
                    
                    localStorage.setItem(this.reportName+"_selected_layout",JSON.stringify(layoutDetails));
                    
                    //Change by shrutika on 16-09-19 [Start] for issue in report, updated data not display.
                   // this.reportConfig.dataSource['data'] = this.reportData.data.data || this.reportData.data;
                   this.reportConfig.dataSource = this.getCurrentDataSource();
                    this.applyReport(objName, prefName, userId);
                }
                this.onReportComplete();
            }
        );
    }

    //Get All Layout Report
    getAllReportLayout(reportName:any) {
        return this.dashboardService.getAllLayoutByObject(this.reportName, false);
    }

    saveReportInCache(objName:any, layoutName:any, reportConfig:any) {
        reportConfig.dataSource.data = "";
        //localStorage.setItem(key, JSON.stringify(reportConfig));
        this.dashboardService.saveExploreReport(objName, layoutName, reportConfig);
    }

    getColumnVals(column:any, value:any) {
        var filterValues:any = [];
        var formattedVal = column + '.[' + value + ']'
        filterValues.push(formattedVal);
        console.log('filterValues', filterValues);
        return filterValues;
    }

    ngOnDestroy() {
        this.myLayoutSubcription.unsubscribe();
    }

    //CHANGES DONE BY For Expand And Expand All and Collapse and CollapseAll KAMAL START
    expandAll()  //To Expand All Data at once
    {
        console.log("Expand All functionallity called here");
        this.fmComponent.flexmonster.expandAllData();
        console.log('if expanded result==>', this.fmComponent.flexmonster);
        this.expandedAll = true;
        console.log('expanded al result in expandAll function==>',this.expandedAll);
    }

       
    collapseAllData()
    {
        console.log("collapseAllData functionallity called here");
        this.fmComponent.flexmonster.collapseAllData();
        console.log('if collapse result==>', this.fmComponent.flexmonster);
        this.expandedAll = false;
        console.log('expanded al result in collapseAllData function==>',this.expandedAll);
    }

    expand() //To Expand Data of a selected cell 
    {
        console.log('Expand  functionallity called here');
        var value = this.fmComponent.flexmonster.getSelectedCell(); //To get selectedCell info
        console.log('value ==>', value);
        if (value) {
            console.log('value in expand Call==>', value);
            var selectedValue = value.hierarchy.uniqueName; //TO get selcedValue uniqueName
            console.log('selectedValue result==>', selectedValue);
            this.fmComponent.flexmonster.expandData(selectedValue);
            this.expanded = true;
        }
    }

    collapseData()
    {
        console.log('collapseData  functionallity called here');
        var value = this.fmComponent.flexmonster.getSelectedCell(); //To get selectedCell info
        console.log('value ==>', value);
        if (value) {
            console.log('value in collapseData Call==>', value);
            var selectedValue = value.hierarchy.uniqueName; //TO get selcedValue uniqueName
            console.log('selectedValue result==>', selectedValue);
            this.fmComponent.flexmonster.collapseData(selectedValue);
            this.expanded = false;
        }
    }
  //CHANGES DONE BY KAMAL For Expand And Expand All and Collapse and CollapseAll  END

    //Added by Kamal.P in order to show Expand Collapse Expand All Collapse All tab Conditionally Start
    onReportChange() {  
        //console.log('flexmonster==>',this.fmComponent.flexmonster,'getRport==>',this.fmComponent.flexmonster.getOptions(), 'toolbar==>',this.fmComponent.flexmonster,'toolbarelement==>',this.fmComponent.flexmonster['toolbar'],'elemnetID==>',this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-expand-all"));
        //fm-tab-collapse-all
        //var reportConfig = 
        setTimeout(() => {
	// Added by Mahesh Saggam on 28-JULY-21 [Error occurs when toolbar is undefined]
            if(this.fmComponent.flexmonster)
            {
                var getReport = this.fmComponent.flexmonster.getOptions();
                console.log('getReport==>',getReport);
                if(getReport && getReport!== null){
                    console.log('if get Report is not null',getReport);
                    var reportType = getReport.grid.type;
                    var viewType  = getReport.viewType;
                    console.log('reportType==>',reportType , 'viewType==>',viewType);
                    if(reportType === 'flat' || viewType === 'charts'){
                        console.log('viewTpe==>',viewType, 'reportType==>',reportType)
                        this.hideToolbar();
                        
                    }else{
                        this.showExapandCollapseAllToolbar();
                        this.showExpandCollapseToolBar();
                    }
                }else{
                    this.hideToolbar();
                }
            }
        }, 700);
    }
    
    showExapandCollapseAllToolbar(){
	// Added by Mahesh Saggam on 28-JULY-21 [Error occurs when toolbar is undefined]
        if(this.fmComponent.flexmonster['toolbar'])
        {
            if(this.expandedAll){
                console.log('inside false consition');
                this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-expand-all").style.display = 'none'; 
                this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-collapse-all").style.display = 'inline-block';
            }else{
                console.log('inside else consition');
                this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-expand-all").style.display = 'inline-block';
                this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-collapse-all").style.display = 'none';
            }
        }
    }
    
    showExpandCollapseToolBar(){
	// Added by Mahesh Saggam on 28-JULY-21 [Error occurs when toolbar is undefined]
        if(this.fmComponent.flexmonster['toolbar'])
        {
            if(this.expanded){
                console.log('inside false consition');
                this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-expand").style.display = 'none';
                this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-collapse").style.display = 'inline-block';
            }else{
                console.log('inside else consition');
                this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-expand").style.display = 'inline-block'; 
                this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-collapse").style.display = 'none';
            }
        }
    }
    
    hideToolbar(){
	// Added by Mahesh Saggam on 28-JULY-21 [Error occurs when toolbar is undefined]
        if(this.fmComponent.flexmonster['toolbar'])
        {
            this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-expand-all").style.display = 'none';
            this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-collapse-all").style.display = 'none'; 
            this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-expand").style.display = 'none'; 
            this.fmComponent.flexmonster['toolbar'].getElementById("fm-tab-collapse").style.display = 'none'; 
        }
    }
    
  //Added by Kamal.P in order to show Expand Collapse Expand All Collapse All tab Conditionally End
  //Added by shrutika on 16-09-19 [Start] for issue in report, updated data not display.
  getCurrentDataSource()
  {
    var localDataSource = {
        dataSourceType: "json",
        data: this.reportData.data.data || this.reportData.data
    }
    
    var serverDataSource = {
        filename : this.reportDataFileName
    }
    var dataSource = this.reportDataFileName ? serverDataSource : localDataSource;
    console.log("inside getCurrentData....693",this.reportDataFileName, dataSource);
    return dataSource;
  }
  //Added by shrutika on 16-09-19 [Start] for issue in report, updated data not display.

    onBarClick( event:any ) {
        console.log('Inside on bar click 846 ', event);
        this.onDrillDown.emit( event );
    }
}

/*
@Component({
    selector: 'dialog-overview-example-dialog',
    templateUrl: './dialogue.component.html',
    styleUrls: ['./fm-component.component.css'],
})
export class DialogOverviewExampleDialog implements OnInit {
    share: boolean = false;
    public editMode: boolean = false;
    currReportName;

    constructor(
        public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
        @Inject(MAT_DIALOG_DATA) public data: any) {
        dialogRef.disableClose = true;
    }

    ngOnInit() {
        this.currReportName = this.data.reportName;
        console.log('currReportName====>', this.currReportName);
    }

    onNoClick(): void {
        this.dialogRef.close();
    }

} */
