import { Component, OnInit,OnDestroy, Input, NgZone, ElementRef,ViewChild, ViewContainerRef, ComponentFactoryResolver, EventEmitter, Output} from '@angular/core';
// import { Subscription } from 'rxjs/Subscription';

import { DashboardService } from '../dashboard.service';
import { FilterDataService } from '../dashboard-filter/filter-data.service';
import { DashboardViewComponent } from '../dashboard-view/dashboard-view.component';

import { Portal,  TemplatePortalDirective } from '@angular/cdk/portal';
// import { VisualConstructorOptions } from '../../visuals/VisualConstructorOptions';
//import { VisualUpdateOptions } from '../../visuals/VisualUpdateOptions';
import { VisualUpdateOptions } from 'visuals';
// import { Store } from '../../visuals/Store';
import { Subscription } from 'rxjs';

declare var checkNetwork: any;

@Component({
  selector: 'dashboard-component',
  templateUrl: './dashboard-component.component.html',
  styleUrls: ['./dashboard-component.component.css'],
  host: { '[class]': 'compCss', '[style.width]': 'compWidth', '[style.height]': 'compHeight' }
})
export class DashboardComponentComponent implements OnInit ,OnDestroy{

  @Input() compConfig: any;
  @Input() dashboardName: any;
  @Input() isLinkComponent: any;
  @Input() vieWtype: any;

  @Input() isSingleDashboard: any;
  @ViewChild('drillDownContainer', { static: true,read: ViewContainerRef }) drillDownContainer: any;
  @ViewChild('angDbContainer') angDbContainer : ElementRef | any;
  @ViewChild('draggable') draggableElement: ElementRef | any;

  @Output() onDrillDown: EventEmitter<any> = new EventEmitter();

  compTitle: any;
  compIcon: any;
  compType: any;
  compName: any;
  compHTML: any;
  compCss: any;
  compWidth: any;
  compHeight: any;
  datasourceId: any;
  obj_links: any;
  obj_actions: any;
  obj_name: any;
  compId: any;
  linkData: any;
  gridType: any;
  expIconPos : string ='';

  treeCompArray = "coaching-dashboard,assessment-details,tree-component".split(',');

  compData: any = {};
  refreshDate: any;
  loaded = false;
  loading = true;
  isNullData: any;
  showLinks: any;
  trigger: any;
  hostUrl: any;
  defaultLinks: Array<string> = ["1","2","3","4","6", "7"];
  feedData: any;
  pkFieldValue = "";
  ASSET_IMG_URL = "dashboard/assets/images";

  subscription: Subscription | any;
  subscriptionFV: Subscription | any;
  respSubcription: Subscription | any;
  tabChangeSubcription: Subscription | any;
  autoRefreshSubcription: Subscription | any;
  totalVal: any;
  titleLabel: any;
  isMobile: any;
  flatView: any;
  flatCompView: any;
  minHeight: any;
  //Added by Saiprasad G for floating button
  floatingButton = 'N';

  filterParameter: string = '';
  @Input() isDrillDown: boolean = false;
  compRef: any;
  @Input() filterInfo: any;
  @Output() onDrillDownClose: EventEmitter<any> = new EventEmitter();
  @Input() filters: any;
  @ViewChild(TemplatePortalDirective) templatePortal: Portal<any> | any;
  @Output() onRowSelect: EventEmitter<any> = new EventEmitter();
  appliedFilters: any;
// Added by Mahesh Saggam on 07-SEP-21 [To call visuals from dashboard] Start
  visualUpdOptions: any;
  isRefresh = false

  constructor( public dashboardService: DashboardService, public filterSvc: FilterDataService, public zone: NgZone, public elementRef: ElementRef, private _componentFactoryResolver: ComponentFactoryResolver) { }

  ngOnInit() {
      console.log('DashboardComponentComponent ngOnInit..',this.compConfig,this.filters,this.filterInfo);

      this.hostUrl = this.dashboardService.getHostURL();

      if(!this.hostUrl){
        this.ASSET_IMG_URL = "/ibase/E12BROWSER/"+this.ASSET_IMG_URL;
      }

	  // Added By Saitej D on 7Mar19
      if(this.compConfig && this.compConfig.isAutoRefresh == 'Y')
      {
          if(this.autoRefreshSubcription){
              this.autoRefreshSubcription.unsubscribe();
          }
          this.autoRefreshSubcription = this.dashboardService.autoRefresh.subscribe(
             (res: any) => {
                 console.log('Auto Refresh '+this.dashboardName+" dashboard");
                 this.getCompData(this.filterParameter, true, false);
             }
          );
      }
      // Added By Saitej D on 7Mar19

      if(!this.isDrillDown)
      {
          this.setCompInfo();
          let index = window.location.pathname.indexOf('E12BROWSER');
          var pageNo = this.dashboardService.dashboardPageNoList[this.dashboardName];
          console.log('DASHBOARD Page No:: isLinkComponent::',pageNo, this.isLinkComponent);
          if(index == -1){
              this.isMobile = true;
          }
          if(pageNo == 1 || index == -1 || this.isLinkComponent){
              this.filterParameter = this.dashboardService.getDefaultFilterParam(this.dashboardName, this.datasourceId);
              var loadedDashboardsList: any = this.dashboardService.loadedDashboardsList;
              console.log('loadedDashboardsList In DashboardComponent',this.dashboardName, loadedDashboardsList);
              if( loadedDashboardsList.indexOf(this.dashboardName) > -1 )
              {
                  this.getCompData(this.filterParameter, false, false);
              }
              else
              {
                  this.dashboardService.loadedDashboardsList.push(this.dashboardName);
                  this.getCompData(this.filterParameter, true, false);
              }

          } else {
              var tabChangeEmitter = (window as any)["AngDashboard"].onTabChange;
              this.tabChangeSubcription = tabChangeEmitter.subscribe(
                      (metadataname: any) => {
                          if(this.dashboardName == metadataname)
                          {
                              console.log('On Tab Change Event',metadataname);
                              this.filterParameter = this.dashboardService.getDefaultFilterParam(this.dashboardName, this.datasourceId);
                              //this.getCompData(this.filterParameter, false, false);
                              var loadedDashboardsList: any = this.dashboardService.loadedDashboardsList;
                              console.log('onTabChange loadedDashboardsList In DashboardComponent',this.dashboardName, loadedDashboardsList);
                              if( loadedDashboardsList.indexOf(this.dashboardName) > -1 )
                              {
                                  this.getCompData(this.filterParameter, false, false);
                              }
                              else
                              {
                                  this.dashboardService.loadedDashboardsList.push(this.dashboardName);
                                  this.getCompData(this.filterParameter, true, false);
                              }
                              this.tabChangeSubcription.unsubscribe();
                          }
                      }
              );
          }

          this.subscription = this.filterSvc.getFilterParameters(this.compTitle).subscribe((filterParameter: any) => {
              if(filterParameter && filterParameter.metadataName == this.dashboardName)
              {
                  if(this.compRef){
                      this.compRef.destroy();
                  }
                  this.filterParameter= filterParameter.value;
                  this.getCompData(this.filterParameter, false, true);
              }
          });

	// Added by Pankaj R on 16-SEP-21 To pass the filter parameter to drill down for default parameter [START]
	this.filterSvc.setFilters(this.dashboardName);
	var filterDef = this.filterSvc.getFilters();
	console.log('New filterDef :: ',filterDef);
	this.getAppliedFilters(filterDef);
	console.log('233 this.appliedFilters', this.appliedFilters);
	// Added by Pankaj R on 16-SEP-21 To pass the filter parameter to drill down for default parameter [END]

        //Added by Prajyot
        this.subscriptionFV = this.filterSvc.getFilterValues(this.dashboardName).subscribe((filterValues: any) => {
	  if(filterValues && filterValues.metadataName == this.dashboardName)
            {
                console.log('::setting appliedFilters as filter values in dashboard-component.component',filterValues);
                this.appliedFilters = filterValues.values;
            }
          });
      }
      else
      {
        this.setCompInfo();
        console.log("compConfig for Drill Down filterInfo",this.filterInfo);
        if(this.filterInfo)
        {
            //var filterParameter = this.applyFilters(this.filters,this.filterInfo.rowData);
            //this.getCompData(filterParameter, false, false);
            this.applyFilters(this.filters,this.filterInfo);
        }
        else
        {
            this.getCompData('', false, false);
        }
        this.subscription = this.filterSvc.getFilterParameters(this.compTitle).subscribe((filterParameter: any) => {
            /*if(filterParameter && filterParameter.metadataName == this.filterInfo.linkMetadata)
            {
                this.filterParameter= filterParameter.value;
                this.getCompData(this.filterParameter, false, false);
            }*/
            if(this.isDrillDown){
                this.closeDrillDown();
            }
        });

      }
  }

  ngAfterViewInit(){
       console.log(' this.draggableElement ngAfterViewInit...',this.draggableElement);

   if (this.draggableElement!==undefined && this.draggableElement!==null )
    {
         var localdrillDown = localStorage.getItem('DrildropdownClick');

          console.log(' localdrillDown ngAfterViewInit: ', localdrillDown );
          console.log(' this.draggableElement.nativeElement.. NIlesh  Neqw',this.draggableElement.nativeElement);
           if ( localdrillDown == "ranking" )
            {
                    console.log(' localdrillDown Remove: ', localdrillDown );
                    this.draggableElement.nativeElement.remove();
            }

          console.log(' this.draggableElement.nativeElement.. After NIlesh New ',this.draggableElement.nativeElement);

  }
  }

  getCompData(filterParameter: any, isRefresh: any, isFilterApplied?: any)
  {
      this.visualUpdOptions = undefined
    //Changes By Prajyot 09FEB19 - For checking network availability and makes server call - Starts
    checkNetwork((isNetwork: any)=>{
        console.log('isNetwork', isNetwork);
        this.dashboardService.setNetwork(isNetwork);
        if( !isNetwork && isRefresh )
        {
            alert('It seems there is no network. Unable to refresh dashboard.');
        }
    });

      this.compData["data"] = [];
      if(this.respSubcription){
          this.respSubcription.unsubscribe();
      }
      this.loaded = false;
      this.loading = true;
      console.log('START TIME',new Date());
      console.log('getCompData filterParameter::',filterParameter);
      console.log('getCompData filterInfo::',this.filterInfo);
      var _appliedFilters;
      if(this.filterInfo)
      {
          _appliedFilters = this.filterInfo._appliedFilters || [];
      }
      if(!filterParameter || filterParameter.trim()=="" )
      {
        console.log('inside filterParam...',_appliedFilters);
        if(_appliedFilters && _appliedFilters.length > 0)
        {
            console.log('inside _appliedFilters.length...');
            for(var i = 0; i< _appliedFilters.length ; i++)
            {
                var obj = _appliedFilters[i];
                var value = obj["changedValue"] ? obj["changedValue"] : obj["default_value"] ;
                filterParameter += obj["col_id"] + "=" + value + "&";
            }
        }
        else{
            console.log('next if else');
            filterParameter = this.dashboardService.getDefaultFilterParam(this.dashboardName, this.datasourceId);
        }
      }
      this.filterParameter = filterParameter;
      console.log('getCompData filterParameter::',filterParameter);
      console.log('final getCompData this.filterParameter::',this.filterParameter);
      this.respSubcription = this.dashboardService.getDashboardData(this.dashboardName,this.datasourceId, filterParameter, isRefresh, this.isDrillDown, isFilterApplied).subscribe(
              (dashboardData: any) => {
                 //console.log('dashboard:['+this.dashboardName+'] component Id:['+this.compConfig.id+']');
                 // console.log('result of servlet::',dashboardData);
                  console.log('END TIME 1',new Date());
                  if(dashboardData){
                      //this.compData["data"] = dashboardData;
                      this.compData["data"] = this.dashboardService.getFilteredDashboardData(this.dashboardName, this.datasourceId, filterParameter, dashboardData);
                      this.compData["title"] = this.compTitle;
                      this.refreshDate = new Date();
                      if(dashboardData.length == 0 || dashboardData.status == 'Failure' || (dashboardData.result && dashboardData.result.status == 'Failure') || (dashboardData.data && dashboardData.data.length == 0)){
                          this.isNullData = true;
                      }
                      else {
                          this.isNullData = false;
                          if(dashboardData.data){
                              this.compData["data"] = dashboardData.data;
                          }

                      }

                      if(dashboardData.reponse == "loading"){
                          this.loading = true;
                      }
                      else {
                          this.loaded = true;
                          this.loading = false;
                          console.log('loaded:[',this.loaded+"] loading:["+this.loading);
                          this.zone.run(() => {
                              console.log( 'view refreshed' );
                          } );
                      }
                      // Added by Mahesh Saggam on 07-SEP-21 [To call visuals from dashboard] Start
                      console.log('Print compType line 327:::: ['+this.compType+'] this.loading:: ['+this.loading+']');
                      console.log('Print compData line 328::::: ', this.compData);
                      if(this.compType == 'VISUAL' && !this.loading)
                      {
                        this.visualUpdOptions = undefined;
                        let optionsArr: any = [];
                        let columns: any = []

                        if(!this.isRefresh && this.compData.ColumnGroups)
                        {
                            this.compData.ColumnGroups.forEach( (elem: any) => {
                                if(elem['COLUMNS'] != undefined)
                                {
                                    if(elem['COLUMNS'] instanceof Object)
                                    {
                                        let columnArrObj: any = {};
                                        let columnArray = [];
                                        if(elem['COLUMNS']['COLUMN'] != undefined)
                                        {
                                            columnArrObj = elem['COLUMNS']['COLUMN'];
                                            if (columnArrObj instanceof Array)
                                            {
                                                columnArray = elem['COLUMNS']['COLUMN'];
                                            }
                                            else
                                            {
                                                columnArray.push(columnArrObj);
                                            }
                                        }

                                        if(columnArray != undefined)
                                        {
                                            let colsArray = [];
                                            for(let i = 0; i < columnArray.length; i++)
                                            {
                                                let columnsObj = {};;
                                                columnsObj = columnArray[i];
                                                if(columnsObj != undefined)
                                                {
                                                    colsArray.push(columnsObj)
                                                    // elem['COLUMNS'] = colsArray;
                                                    let colObj: any = {};
                                                    // colObj['uniqueName'] = elem['COLUMNS'][i]['id']
                                                    // colObj['caption'] = elem['COLUMNS'][i]['value']
                                                    colObj['uniqueName'] = columnsObj['id']
                                                    colObj['caption'] = columnsObj['value']
                                                    columns.push(colObj);
                                                }
                                            }
                                            if(colsArray != undefined && colsArray.length > 0)
                                            {
                                                elem['COLUMNS'] = colsArray;
                                            }
                                            let columnsArr: any = []
                                            columnsArr.push(columnArray);
                                            columnArray = columnsArr;
                                        }
                                    }
                                }
                            })
                            this.compData['columns'] = columns
                        }
                        this.isRefresh = false

                        if(this.compData.options != undefined)
                        {
                            this.compData.options.forEach( (elem: any) => {
                                let optionObj: any = {};
                                for(let key of Object.keys(elem))
                                {
                                    if( !(elem[key] instanceof Object && elem[key] instanceof Array) )
                                    {
                                        optionObj[key] = elem[key]
                                    }
                                }
                                optionsArr.push(optionObj);
                            } )
                        }
                        let updOptions = new VisualUpdateOptions();
                        updOptions['jsonData'] = this.compData['data'];
                        let jsonData = this.compData['data'];
                        for(const key of Object.keys(jsonData))
                        {
                            if(key == this.compData['component_root_name'])
                            {
                                if(jsonData[key] instanceof Object)
                                {
                                    let jsonDataObj: any = {};
                                    let jsonDataArray = [];
                                    jsonDataObj = jsonData[key];
                                    if (jsonDataObj instanceof Array)
                                    {
                                        updOptions['jsonData'] = jsonData[key];
                                    }
                                }
                            }
                        }
                        updOptions['visualLayout'] = this.compData;
                        updOptions['optionsArr'] = optionsArr;
                        updOptions['licenseKey'] = this.compData["licenseKey"];
                        updOptions['elemId'] = this.compData['metadataname'] + '-fm-grid-view' + this.compData['compId']
                        updOptions['isDashboard'] = true;

                        console.log('Print compDAta line 403::: ', this.compData)
                        this.visualUpdOptions = updOptions
                        console.log('Print visualData line 398::: ', this.visualUpdOptions);
                    }
                    // Added by Mahesh Saggam on 07-SEP-21 [To call visuals from dashboard] End
                  }
                  console.log('END TIME 2',new Date());
              }
      );
    //Changes By Prajyot 09FEB19 - For checking network availability and makes server call - Ends
  }

  openDashboardLinks(trigger: any){
      this.trigger = trigger;
      this.showLinks = !this.showLinks;
  }

  closeOverlay() {
      this.showLinks = false;
  }

  getImgSrc(link: any) {
      var thumbObj = "";
      var imgUrl;

      if(this.defaultLinks.indexOf(link.LinkType) === -1){
          imgUrl = this.hostUrl + "/ibase/CustomMenuImageServlet?fldValue=" +link.LinkTitle+ "&object="+thumbObj+"&objName="+this.obj_name;
      }else if(link.LinkType == 1){
          imgUrl = this.ASSET_IMG_URL + "/svg/link_view.svg";
      }

      return imgUrl;
  }

  //Added by Pravin K on 4-FEB-20 START
  performAction(link: any)
  {
  		if( link['feedData'] )
  		{
		     this.feedData = link['feedData'];
		  	 this.performLinkAction(link)
  		}
  }
//Added by Pravin K on 4-FEB-20  END
  performLinkAction(link: any){
      if(link.LinkType == 'CL'){
          console.log('In link type cl');
          link.handler();
      }
      //else if(link.LinkType == 'A' && this.isNullData){
      //    alert('No data');
      //}
      else if(link.LinkType == 'A'){
          this.dashboardService.invokeAngCompLink(link, this.feedData, this.obj_name, this.templatePortal, this.compData);
      }else if(link.LinkType == 3 || link.LinkType == 4 || link.LinkType == 7){
          this.dashboardService.invokeDashboardLink(link, this.feedData, this.obj_name);
      }else if(this.feedData){
	      var targetObj=this.feedData['target_obj_name'];
	      console.log('feedData in performLinkAction',this.feedData,Object.assign(link, {}),targetObj);
	      if(targetObj && targetObj.length > 0 && targetObj != '(blank)' ){
	          link.TargetObject=this.feedData['target_obj_name'];
	          console.log('inside perform action ::::::::: ',Object.assign(link, {}))
	      }
          this.dashboardService.invokeDashboardLink(link, this.feedData, this.obj_name);
      }else {
          alert('Please select a record.');
      }

      this.closeOverlay();
     }

  setSelectedFeed(selectedFeed: any){
      this.feedData = selectedFeed;
      this.onRowSelect.emit(this.feedData);
  }

  ngOnDestroy()
  {
      console.log('DashboardComponentComponent ngOnDestroy..', this.compTitle);
      // unsubscribe to ensure no memory leaks
      if( this.subscription ) this.subscription.unsubscribe();
      if( this.subscriptionFV ) this.subscriptionFV.unsubscribe();
  }

  setCompInfo() {
      this.compTitle = this.compConfig.ComponentTitle;
      this.compIcon = this.compConfig.component_icon;
      this.compType = this.compConfig.type;
      this.gridType = this.compConfig.grid_type;
      this.compName = this.compConfig.ComponentName;
      this.expIconPos = this.compConfig.layout && this.compConfig.layout.expansion_Icon_Position ? this.compConfig.layout.expansion_Icon_Position : 'right' ;
      this.compHTML = this.compConfig.layout ? this.compConfig.layout.html : null;
      this.compCss = this.compConfig.component_css ? this.compConfig.component_css : 'db-col-1';
      this.compWidth = this.compConfig.width ? this.compConfig.width : '';
      this.compHeight = this.compConfig.height ? this.compConfig.height : '';
      this.obj_name = this.compConfig.obj_name;
      this.obj_links = this.compConfig.obj_links;
      this.obj_actions = this.compConfig.obj_actions;
      this.datasourceId = this.compConfig.datasource;
      this.flatCompView = this.compConfig.flat_view == 'Y' ? true : false; // Its used in SNOP and CG-CRM Dashboard
      // this.vieWtype : flat - Customer Information
      // this.vieWtype : flatonly - Quick Access Dashboard, Course Library, Background Job
      this.flatView = ['flatonly'].includes(this.vieWtype);
      //Added by Saiprasad G for floating button on 30-MAR-20[START]
      this.floatingButton = this.compConfig.floating_button;
      if( !this.floatingButton ){
      	console.log('floatingButton:',this.floatingButton);
      	this.floatingButton ='N';
      }
	  //Added by Saiprasad G for floating button on 30-MAR-20[END]
      if(this.vieWtype == 'flat')
      {
          this.minHeight = '280px';
      }
      else
      {
//          this.minHeight = (this.compConfig.min_height || '300') + 'px';
            this.minHeight = (this.compConfig.min_height || '280') + 'px';
      }

      if(this.obj_links){
          console.log('object link ',this.obj_links);
          for(var i=0; i<this.obj_links.length; i++){
              console.log('link Data ',i);
              if(this.obj_links[i].AutoInvoke.includes('Y')){
                  console.log('autoinvoke is y ');
                  this.linkData=this.obj_links[i];
                  this.obj_links.splice(i, 1);
                  break;
              }
          }
          console.log('obj link after ',this.obj_links,this.linkData);
      }

      if(this.compHeight && (typeof this.compHeight === 'number')){
          this.compHeight = this.compHeight.toString()+'px';
      }

      if(this.compWidth && (typeof this.compWidth === 'number')){
          this.compWidth = this.compWidth.toString()+'px';
      }

      if(this.compConfig.columns){
          this.compData["columns"] = this.compConfig.columns;
      }

      if(this.compConfig.slice){
          this.compData["slice"] = this.compConfig.slice;
      }

      console.log("this.chartProperties --->>> " ,this.compConfig.chart_properties);
      if(this.compConfig.chart_properties){
          this.compData["chart_properties"] = this.compConfig.chart_properties;
      }
      if(this.compConfig.column_group){
          this.compData["column_group"] = this.compConfig.column_group ? this.compConfig.column_group : null;
      }

      if(this.compConfig.filterInfo){
          this.compData["filterInfo"] = this.compConfig.filterInfo;
      }

      if(this.compHTML){
          this.compData["compHTML"] = this.compHTML;
      }
      if(this.expIconPos){
          this.compData["expIconPos"] = this.expIconPos;
      }


      if(this.compConfig.FM_API_KEY){
          this.compData["licenseKey"] = this.compConfig.FM_API_KEY;
      }

      this.compData["metadataname"] = this.dashboardName;

      if(this.filterInfo){
          this.compData["filterInfo"] = this.filterInfo;
      }

      if(this.obj_name){
          this.compData["obj_name"] = this.obj_name;
      }

      if(this.obj_actions){
          this.compData["obj_actions"] = this.obj_actions;
      }

      if(this.gridType){
          this.compData["gridType"] = this.gridType;
      }

      this.compData["compId"] = this.compConfig.id;

      if(this.compConfig.feed){
        this.compData["feed"] = this.compConfig.feed;
      }

      if(this.compConfig.link_metadata|| this.compConfig.LINK_METADATA){
        this.compData["link_metadata"] = this.compConfig.link_metadata || this.compConfig.LINK_METADATA;
      }

      if(this.compConfig.explore_details){
        this.compData["explore_details"] = this.compConfig.explore_details;
      }

      if(this.compConfig.feeds_config){
        this.compData["feedsConfig"] = this.toJSON(this.compConfig.feeds_config);
      }

      if(this.compConfig.column_details){
        this.compData["columnsList"] = this.toJSON(this.compConfig.column_details);
      }
      //Added by Prajyot
      if(this.compConfig.column_config){
        this.compData["columnsConfig"] = this.toJSON( this.compConfig.column_config );
      }
      if(this.compConfig.chartType){
          this.compData["chartType"] = this.compConfig.chartType;
      }
      if(this.compConfig.showTotal){
          this.compData["showTotal"] = this.compConfig.showTotal;
      }
      if(this.compConfig.showDataLabels){
          this.compData["showDataLabels"] = this.compConfig.showDataLabels;
      }
      if(this.compConfig.showTitleVal && this.filterInfo){
         this.titleLabel = this.filterInfo.value;
         console.log('set titleLabel',this.filterInfo);
      }

      if(this.obj_links){
          this.compData["obj_links"] = this.obj_links;
      }

      if(this.compConfig.template){
          this.compData["template"] = this.compConfig.template;
      }

      if(this.compConfig.composite){
          this.compData["composite"] = this.compConfig.composite;
      }

      if(this.compConfig.layout){
          this.compData["layoutProtoType"] = this.compConfig.layout.protoType || 'card';
      }

      if(this.compConfig.options){
        this.compData["options"] = this.compConfig.options
      }

      if(this.compConfig.ColumnGroups)
      {
        this.compData["ColumnGroups"] = this.compConfig.ColumnGroups
      }

      if(this.compConfig.ID)
      {
        this.compData["ID"] = this.compConfig.ID
      }

      if(this.compConfig.component_root_name)
      {
        this.compData["component_root_name"] = this.compConfig.component_root_name;
      }
  }

  toJSON(jsonString: any)
  {
    var jsonObject = {};
    try
    {
        jsonObject = JSON.parse(jsonString);
    }
    catch(e)
    {
		jsonObject = eval( 'jsonObject = ' +  jsonString);
	    console.log('Inside catch toJSON ...', jsonString, jsonObject);
    }
    return jsonObject;
  }
  openDrillDown(selectedFieldInfo: any) {
    console.log('In openDrillDown',selectedFieldInfo,this.appliedFilters,this.filterInfo);
   	// Added By Pravin K on 12-JAN-20 [START]
    if(selectedFieldInfo.isDataRefresh){
        this.refreshData();
    }
   // Added By Pravin K on 12-JAN-20 [END]
    else if(this.isDrillDown){
		//Added By Prajyot 08-Jun-2020 [ROWData in case its missing - mainly FMChart case] - Starts
        if( this.filterInfo && ( this.compType == 'GRID' || this.compType == 'FMCHART' ) )
        {
            console.log(' Dashborad Component - isDrillDown : ', this.compType, this.filterInfo );
            var column = this.filterInfo.column ? this.filterInfo.column.toLowerCase() : this.filterInfo.column;
            var value = this.filterInfo.value;
            if( ! selectedFieldInfo.rowData )
            {
                selectedFieldInfo['rowData'] = { [column] : value };
            }
            else
            {
                selectedFieldInfo.rowData[column] = value;
            }
            // Carry forward applied filters i.e. Arguments of parent component to drilldown component
            var _appliedFilters = this.filterInfo['_appliedFilters'];
            if ( _appliedFilters )
            {
                selectedFieldInfo['_appliedFilters'] = _appliedFilters;
            }
            // Copy filterInfo.rowData to selectedFieldInfo for passing previously selected data to drilldown component
            var filterInfoRowData = this.filterInfo.rowData;
            if( filterInfoRowData )
            {
                Object.assign(selectedFieldInfo.rowData, filterInfoRowData);
            }
            console.log(' Dashborad Component - selectedFieldInfo : ', filterInfoRowData, selectedFieldInfo );
        }
		//Added By Prajyot 08-Jun-2020 [ROWData in case its missing - mainly FMChart case] - Ends
        this.dashboardService.getDashboardMetadata( selectedFieldInfo.linkMetadata ).subscribe(
            (result: any) => {
                var datasource = result.datasource;
                var filters =  result.filters;
                this.dashboardService.createDataSources(selectedFieldInfo.linkMetadata,datasource,filters);
                console.log('selectedFieldInfo.linkMetadata ', selectedFieldInfo.linkMetadata );
                var localdrillDown = localStorage.getItem('DrildropdownClick');
                var localdrillDown1 = localStorage.getItem('DrildropdownDoctorClick');
                console.log(' localdrillDown : ', localdrillDown );
                console.log(' localdrillDown   Changs : ', localdrillDown );
                if ( selectedFieldInfo.linkMetadata  !== "ranking" || localdrillDown == "ranking"  )
                {
                    console.log(' Dashborad Component inside loop **** : ', selectedFieldInfo.linkMetadata );
                    if ( localdrillDown == "ranking" && selectedFieldInfo.linkMetadata == "Brand-Doctor")
                    {

                            var Table = document.getElementById("DoctorData");
                            console.log(' Dashborad Component inside loop our new condition  : ', Table );

                            var Parenttable: any = document.getElementById("DoctorData");
                            while(Parenttable.hasChildNodes())
                            {
                                Parenttable.removeChild(Parenttable.firstChild);
                                if ( document.getElementById("DoctorData") !== null )
                                {
                                    console.log(' only table will be delete ');
                                    // document.getElementById("DoctorData").remove();
                                    document.getElementById("DoctorData")?.remove();
                                    console.log(' only table will be delete after  ', document.getElementById("DoctorData"));

                                }
                            }


                    }
                this.drillDownContainer.detach();
                    localStorage.setItem('DrildropdownClick', selectedFieldInfo.linkMetadata);
                }
                else
                {
                    console.log(' Dashborad Component inside else : ', selectedFieldInfo.linkMetadata );
                    localStorage.setItem('DrildropdownClick', selectedFieldInfo.linkMetadata);
                     var Table = document.getElementById("DoctorData");
                    console.log(' Dashborad Component inside loop Table eslse : ', Table );
                }
                 console.log(' Dashborad Component inside After  : ', selectedFieldInfo.linkMetadata );

                // localdrillDown1 = localStorage.getItem('DrildropdownDoctorClick');
                console.log(' Dashborad Component inside localdrillDown1  : ', localdrillDown1 );

                 console.log(' Dashborad Component inside After  : ', selectedFieldInfo.linkMetadata );
                 console.log( localdrillDown1 !=="Brand-Doctor" );

                console.log(' inside the condition   : ', localdrillDown1 );
                var compFactory =  this._componentFactoryResolver.resolveComponentFactory(DashboardViewComponent)
                this.compRef = this.drillDownContainer.createComponent(compFactory);
                this.compRef.instance.compRef = this.compRef;
                this.compRef.instance.viewData = result.view[0];
                this.compRef.instance.metadataname = selectedFieldInfo.linkMetadata;
                this.compRef.instance.filterInfo = selectedFieldInfo;
                this.compRef.instance.isDrillDown = true;
                this.compRef.instance.isCompositeDrillDown = selectedFieldInfo.isCompositeDrillDown;
                this.compRef.instance.filters = result.filters;
                this.compRef.instance.onDrillDownClose = new EventEmitter();
                this.compRef.instance.onDrillDownClose.subscribe(
                  (event: any) => {
                      console.log('On Drill Close Event',this.compRef);
                      this.compRef.destroy();
                  }
                );
            // }
            });
      }else {
          //Added by saiprasad G. adding condition[START]
          console.log('else condition',this.appliedFilters);
          if(selectedFieldInfo.rowData)
          {
              if( (selectedFieldInfo.rowData.link_metadata || selectedFieldInfo.rowData.LINK_METADATA) && selectedFieldInfo.rowData.link_metadata_filter == "Y")
              {
                console.log('Inside the linkMetaddata',selectedFieldInfo.rowData.link_metadata);
                selectedFieldInfo['_appliedFilters']='';
              }
              else
              {
                selectedFieldInfo['_appliedFilters'] = this.appliedFilters;
              }
          }
          else{
              console.log('No row data in selectedFieldInfo..')
              selectedFieldInfo['_appliedFilters'] = this.appliedFilters;
          }
          //Added by saiprasad G. adding condition[END]
          //selectedFieldInfo['_appliedFilters'] = this.appliedFilters;
          this.onDrillDown.emit(selectedFieldInfo);
      }
   }

  closeDrillDown() {
    console.log('On Drill Down Close',this.dashboardName);
    this.onDrillDownClose.emit();
  }



  applyFilters(filters: any,filterInfo: any){
      console.log( 'DashboardComponent applyFilters ', filters);
      // Added filterInfo.rowData condition by Pankaj R on 13-APR-21 for refresh on drilldown component default filter
      var filterParams = '';
      var isFilterApplied = false;
      if(filterInfo && filters && filters.filter && filterInfo.rowData)
      {
          var compData = filterInfo.rowData;
          var _appliedFilters = filterInfo._appliedFilters || [];
          filters.filter.forEach(
                  (filterVal: any) => {
                      var colVal = compData[filterVal.col_name];
                      //Added by Jatin M on 25-Apr-2022 [Filter column value not getting retrieved in case of Brand Campaign ranking card] - START
                      if(!colVal && compData.rowData)
                      {
                        colVal = compData.rowData[filterVal.col_name];
                      }
                      //Added by Jatin M on 25-Apr-2022 [Filter column value not getting retrieved in case of Brand Campaign ranking card] - END
                      //Added by sainath t. on 27/07/2020 [to resolve the sales review dashboard issue in iPad]-Start
                      console.log('_appliedFilters is array>>', _appliedFilters instanceof Array);
                      var _appliedFilter :any = {};
                      if(_appliedFilters instanceof Array)
                      {
                        _appliedFilter = _appliedFilters.filter( (fltr) => {
                            console.log('filter', fltr);
                            if( fltr.col_name === filterVal.col_name )
                                return fltr;
                        })[0];
                      }
                      //Added by sainath t. on 27/07/2020 [to resolve the sales review dashboard issue in iPad]-Start
                      console.log('_appliedFilter', _appliedFilter, ' and current filter ', filterVal.changedValue);
                      var _appliedChangedValue = _appliedFilter ? _appliedFilter.changedValue : '';
                      if(_appliedChangedValue && !isFilterApplied ){
                        isFilterApplied = (_appliedChangedValue !==  filterVal.changedValue);
                      }
                      if(filterVal.type == "4")
                      {
                          //var colVal = compData[filterVal.col_name];

                          if(_appliedChangedValue){
                              colVal = _appliedChangedValue;
                          }
                          var defaultDate = this.dashboardService.getDefaultDate(colVal);
                          var defaultDateStr = this.dashboardService.formatDate(defaultDate);
                          console.log('Final defaultDateStr:',defaultDate,defaultDateStr);
                          filterVal.changedValue = defaultDateStr;
                      }
                      else
                      {
                          //var colVal = compData[filterVal.col_name];
                          //if(_appliedChangedValue){
			  console.log('filterVal.col_name', filterVal, ' and   compData ', compData);
                          if(_appliedChangedValue && ((!compData['drill_col']) || (compData['drill_col'] && compData['drill_col'] != filterVal.col_name)) ){
                              filterVal.changedValue = _appliedChangedValue;
                          }else if(colVal){
                              filterVal.changedValue = colVal;
                          }else {
                              filterVal.changedValue = filterVal.default_value;
                          }
                      }
                      filterParams += filterVal.col_name + "=" + filterVal.changedValue + "&";
                  }
          );
      }
      console.log("filterParam==>",filterParams, ' isFilterApplied ', isFilterApplied)

      this.getCompData(filterParams, false, isFilterApplied);
      return filterParams;
  }

  setTotal(totalVal: any){
      console.log('Set Total in Dashboard Comp',totalVal);
      this.totalVal = totalVal;
  }

  onLinksCreation(links: any){
 /*     this.obj_links = [];
      console.log('In onLinksCreation',this.compConfig.obj_links,this.obj_links);
      if(this.obj_links){
          console.log('object link ',this.obj_links);
          for(var i=0; i<this.obj_links.length; i++){
              console.log('link Data ',i);
              if(this.obj_links[i].AutoInvoke && this.obj_links[i].AutoInvoke.includes('Y')){
                  console.log('autoinvoke is y ');
                  this.linkData=this.obj_links[i];
                  this.obj_links.splice(i, 1);
                  break;
              }
          }
          console.log('obj link after ',this.obj_links,this.linkData);
      }
      console.log('onLinksCreation links',links);
      if(links){
          for(var i=0; i<links.length; i++){
              this.obj_links.push(links[i]);
          }
      }
      */
      this.obj_links = links;
      console.log('onLinksCreation obj_links',this.obj_links);
  }

  invokeLink(linkData: any) {
      this.dashboardService.invokeAngCompLink(linkData.linkInfo, this.feedData, this.obj_name, this.templatePortal, linkData.compData);
  }

  drillDownCompositeInfo: any;
  openCompositeDrillDown(compositeInfo: any) {
    console.log('In openCompositeDrillDown',compositeInfo);
    if(compositeInfo.isDrillDownFromComposite){
        this.drillDownCompositeInfo = compositeInfo;  //To indicate Drilldown from Composite to another composite
    }
    else{
        compositeInfo['isCompositeDrillDown'] = true; //To indicate Drilldown from Composite to other dashboard
        this.openDrillDown(compositeInfo);
    }
  }

  public refreshData()
  {
    console.log('Inside refreshData()  '+this.dashboardName+" dashboard");
    this.getCompData(this.filterParameter, true, false);
  }

    getAppliedFilters(filterDef: any)
    {
		console.log('filterDef :: ',filterDef);
		filterDef.forEach(
        (filterVal: any) => {
            console.log('filterVal ',filterVal);
            if(filterVal.type == "4")
            {
                var colVal = this.compData[filterVal.col_name];
                //added by Sainath to resolve coaching activity dashboard old data issue-start
                if( !colVal || colVal == undefined )
                {
                    colVal = filterVal.default_value;
                }
                console.log('colVal 001==>',colVal);
                //added by Sainath to resolve coaching activity dashboard old data issue-end
                var defaultDate = this.dashboardService.getDefaultDate(colVal);
                var defaultDateStr = this.dashboardService.formatDate(defaultDate);
                console.log('Final defaultDateStr:',defaultDate,defaultDateStr);
                filterVal.changedValue = defaultDateStr;
				filterVal.default_value = defaultDateStr;
            }
            else
            {
                var colVal = this.compData[filterVal.col_name];
                if(colVal){
                    filterVal.changedValue = colVal;
					filterVal.default_value = colVal;
                }else {
                    filterVal.changedValue = filterVal.default_value;
					filterVal.default_value = filterVal.default_value;
                }
            }
        }
		);

		console.log('filterDef 2 :: ',filterDef);
		this.appliedFilters = filterDef;
	}
}


