import { Component,  OnInit, Input, ViewChild, ElementRef,OnDestroy, ViewEncapsulation, OnChanges, DoCheck, NgZone, Output, EventEmitter } from '@angular/core';
import { FlexmonsterPivot } from "../flexmonster/flexmonster.angular4";
import {  RESIZE_EVENT } from '../window-resize';

import { DashboardService } from '../../dashboard/dashboard.service';
import * as moment from 'moment';

declare var exportToFile :any;
declare var removeClass :any;


@Component({
  selector: 'pivot-grid',
  templateUrl: './pivot-grid.component.html',
  styleUrls: ['./pivot-grid.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class PivotGridComponent implements OnInit,OnDestroy {
  
  @Input('data') reportData : any;
  @Input('elWidth') elWidth: any;
  
  @ViewChild('pivotGrid') pivotGrid: FlexmonsterPivot | any;
  @Output() onDrillDown: EventEmitter<any> = new EventEmitter<any>();
  @Output() onRowSelect: EventEmitter<any> = new EventEmitter<any>();

  isOpened: boolean = false;
  isExpanded: boolean = false;
  isTreeStyleRows: boolean = false;
  pivotDataSource: any;
  clientWidth: any;
  isRefreshed: any;
  hostUrl: any;
  contWidth: any;
  licenseKey: any;
  linkedColumns: any = [];
  customizeCellFunc = this.customizeCellFunction.bind(this);
  selectedRowIndex: any;
  //selectedRowData;
  //columnDataTypes;
  selectedRowData: any={};
  columnDataTypes: any={};
  data: any;
  showExport: any;
  
  constructor(private dashboardService: DashboardService, public zone: NgZone){}
  
  onPivotReady(): void {
        console.log("PivotGridComponent [ready]", this.pivotGrid );
        //removeClass('fm-pivot-view','fm-ui-element');
  }
  
  ngOnInit() {
      this.hostUrl = this.dashboardService.getHostURL();
      this.licenseKey = this.reportData.licenseKey;
      this.data = Object.assign([], this.reportData.data, []);
      
      this.showExport = this.reportData.columnsConfig ? this.reportData.columnsConfig.showExport : false;
      console.log("PivotGridComponent [ngOnInit]",this.licenseKey, this.reportData );
      if(this.hostUrl){            
          RESIZE_EVENT.subscribe(
                  (clientWidth: any) => {
                      console.log('on device width resize',clientWidth);
                      this.elWidth = clientWidth;
                      if( this.pivotGrid )
                      {
                          this.pivotGrid.flexmonster.refresh();
                          this.zone.run(() => {
                              console.log( 'view refreshed' );
                          } );
                      }
                  }
          );
      }
          
         //TO DISPLAY DATE IN FORMATED FORM AS dd/MM/yy START 
          var column;
          var colTypeId: any;
          var columnGroup=this.reportData.column_group;
          if(columnGroup[2] !=null){
              for(var colGroup of columnGroup){
                  var columns=colGroup.columns;
                  console.log('columns>>>>',columns)
                  if( columns != null ){
                      if( columns instanceof Array ){
                          for(var colms of columns){
                              console.log('columns::::',colms)
                              var colId=colms.id;
                              console.log("colId for coloumn==>",colId);
                              var typeOfColumn=colms.type;
                              if(typeOfColumn === 'date string'){
                                  colTypeId = colId
                                  console.log("colId for type date=>",colTypeId);
                              }
                              console.log("typeOfColumn for coloumn==>",typeOfColumn);
                          }
                          
                      }
                  }
              }
          }
          
          if(this.reportData.data){
              this.reportData.data.forEach(
                      (optVal: any) => {
                          if(colTypeId && optVal[colTypeId]){                          
                             console.log("date format for optVal.LAST_RCP_DATE ==",optVal[colTypeId]);
                             var dateFormat = (window as any)['e12navigator'].applDateFormat.toUpperCase();
                             console.log("Check dateFormat for appl == >",dateFormat,optVal[colTypeId],dateFormat);
                             optVal[colTypeId] = moment(optVal[colTypeId],dateFormat).toDate();
                             console.log("date format>>>>>>>>",optVal);
                          }
                      }
              );
              console.log(" this.reportData.data>>>>>>>", this.reportData.data);
          }

      
    //TO DISPLAY DATE IN FORMATED FORM AS dd/MM/yy END

      if(this.reportData.column_group){
            this.reportData.column_group.forEach(
                    (column_group: any) => {
                        if(column_group.link_metadata && Object.keys(column_group.link_metadata).length > 0 && column_group.link_metadata != ""){
                            this.linkedColumns.push(column_group.id);
                        }
                        if(column_group.columns && column_group.columns.length > 0){
                            var column = column_group.columns[0];
                            var columnFormat: any = {};
                            columnFormat["type"] = column.type;
                            this.columnDataTypes[column.id] = columnFormat;                           
                        }
                    }
            );
            
            this.data.unshift(this.columnDataTypes);
            console.log('columnDataTypes:: ',this.columnDataTypes,this.reportData.data);
      }
      
      console.log('linkedColumns:: ',this.linkedColumns);      
  }
  
  ngOnChanges() {
      if(!this.hostUrl && this.elWidth != 0 && this.contWidth != this.elWidth && this.pivotGrid && this.pivotGrid.flexmonster){
          console.log('on element width resize');
          this.contWidth = this.elWidth;
          this.pivotGrid.flexmonster.refresh();
      }
  }
  
  exportToExcel()
  {
    try
    {
        var fileName = this.reportData.title.replace(/[&\/\\|#,+()$~%.'":*?<>{}]/g, '');
        
        var params = {
            filename: '' + fileName,
            destinationType:'file',
            excelSheetName: 'Report',
            showFilters: true
        };
        console.log('exportToExcel', exportToFile);
        if( this.pivotGrid )
        {
            this.pivotGrid.flexmonster.expandAllData();
            setTimeout( () =>{
                this.pivotGrid.flexmonster.exportTo('excel', params, exportToFile);  
            }, 2000);
        }
    }
    catch(e)
    {
        console.log('exportToExcel', e);
    }
    
  }

  onReportComplete(): void {
   var reportConfig = {
         dataSource: {
            dataSourceType: "json",
            data: this.data
         },
         options: {
             grid: {
                type:  this.reportData.gridType ? this.reportData.gridType : 'compact',
                showHeaders: false,
                showFilter: false
             },
             datePattern: "dd/MM/yy", 
             configuratorButton : false, // As per KB sir, no need to parameterized.
             drillThrough: false,
             showGrandTotals : this.reportData.slice ? this.reportData.slice.showGrandTotals : 'off',
             showTotals : this.reportData.slice ? this.reportData.slice.showTotals : 'off',
             showCalculatedValuesButton: false,
             showDrillThroughConfigurator: false
         },
         formats: [
           {
             name: "",
             thousandsSeparator: ""
           }
         ],
         rows: this.reportData.slice ? this.reportData.slice.rows : [],
         columns: this.reportData.slice ? this.reportData.slice.columns : [],
         measures: this.reportData.slice ? this.reportData.slice.measures : []
    };
    
    if( this.pivotGrid )
    {
        this.pivotGrid.flexmonster.off("reportcomplete");
        console.log('pivotGrid reportConfig:::',reportConfig);
        this.pivotGrid.flexmonster.setReport(reportConfig);
        if(this.reportData.filterInfo){                
            var column = this.reportData.filterInfo.column;
            var value = this.reportData.filterInfo.value;
            this.pivotGrid.flexmonster.setFilter(
                    column, this.getColumnVals(column,value)
            );
        }   
        console.log('pivotGrid:::',this.pivotGrid);
    }
  }
  

  onChangeRowsDisplayStyle(): void {
		this.isTreeStyleRows = !this.isTreeStyleRows;
    var options = {
        grid: {
          type: this.isTreeStyleRows?'classic' : 'compact'
      }
    }
    if( this.pivotGrid )
    {
        this.pivotGrid.flexmonster.setOptions( options );
        this.pivotGrid.flexmonster.refresh();
    }

     return ;
  }
  
  onChangeState(): void {
     this.isExpanded = !this.isExpanded;
     console.log("on chenge event");
     if( this.isExpanded )
     {
          this.pivotGrid.flexmonster.expandAllData();
     }else
     {
           this.pivotGrid.flexmonster.collapseAllData();
     }
     return ;
  }
  openFieldsList() {
      console.log('pivotGrid openFieldsList:::');
      if( this.pivotGrid )
      {
          this.pivotGrid.flexmonster.openFieldsList();
      }
 }
  
  ngOnDestroy() 
  {
      console.log('pivot grid ngOnDestroy..');
  }
  

  customizeCellFunction(cell: any, data: any) {        
      if (data.hierarchy && this.linkedColumns.indexOf(data.hierarchy.uniqueName) > -1 && data.type == "value") {
          var el = document.createElement( 'div' );
          el.innerHTML = cell.text;
          cell.text = "<span class='drill-down-link'>"+ el.innerText +"</span>";
      }
      if(data.rowIndex == this.selectedRowIndex){
          cell.classes.push('highlight-cell');
          this.selectedRowData[data.hierarchy.uniqueName.trim().toLowerCase()] = data.label;
      }
      if (data.type == "value") {
          if (data.rowIndex % 2 == 0) {
            cell.addClass("alter1");
          } else {
            cell.addClass("alter2");
          }
      }
  }
    
  onCellClick(cell: any){
      console.log('selectedRowData ::',this.selectedRowData);
      console.log("cellHierarchy====>",cell,this.linkedColumns);
      if (cell.hierarchy && this.linkedColumns.indexOf(cell.hierarchy.uniqueName) > -1 && cell.type == "value") {
          console.log("cellHierarchy")
          this.selectedRowIndex = cell.rowIndex;
          this.pivotGrid.flexmonster.refresh();
          var columnGroup = this.reportData.column_group.find( (columnGroup: any) => columnGroup.id === cell.hierarchy.uniqueName);
          console.log('On Cell Click: [Cell & linkMetadata]',cell,columnGroup.link_metadata);           
      
          var selectedFieldInfo = {
            "column" :  cell.hierarchy.uniqueName,
            "value" : cell.label,
            "linkMetadata" : columnGroup.link_metadata,
            "rowData" : this.selectedRowData
          };
          
          this.onDrillDown.emit(selectedFieldInfo);
      }
      
      /*if(this.reportData.obj_name){
          this.selectedRowIndex = cell.rowIndex;
          this.pivotGrid.flexmonster.refresh();
      } */ 
      this.selectedRowIndex = cell.rowIndex;
      this.pivotGrid.flexmonster.refresh();
  }
  
  getColumnVals(column: any, value: any) {
      var filterValues:any = [];
      var formattedVal = column+'.['+value+']'
      filterValues.push(formattedVal);    
      console.log('filterValues',filterValues);
      return filterValues;
  }
  
  onAfterGridDraw(){
      console.log('After Grid Draw ::');
      
      if(this.selectedRowData && Object.keys(this.selectedRowData).length > 0){
          this.onRowSelect.emit(this.selectedRowData);
      }
  }
  
}
