import { Component, OnInit, OnChanges, Input,NgZone, ChangeDetectorRef, ViewChild} from '@angular/core';
import { SellPlanningService } from '../../sell-planning.service';
import { Observable } from 'rxjs';
import { MatTableDataSource, MatTable } from '@angular/material/table';
//import { MatTableDataSource, MatTable } from '@angular/material';

@Component({
  selector: 'sell-performance',
  templateUrl: './sell-performance.component.html',
  styleUrls: ['./sell-performance.component.css']
})
export class SellPerformanceComponent implements OnInit, OnChanges {
  dataSource = new MatTableDataSource<any>([]);
  secondHeaderTop: number = 0;
  displayedColumns : string [] = [];
  headerLabels: string []  = [];
  inputType : string []  = [];
  // columnProperties: any[];
  columnProperties: any;
  selMonth = "";
  @Input() definedCellTotalJson = {}
  actualYearValueMap: any = {};
  @Input('dashBoardData') ELEMENT_DATA:any[] = [];
  @Input() clearAllParameters:boolean = false;

  _sumofKeys = ['SELL_OUT_MONTH_QTY','SELL_OUT_MONTH_VALUE','SELL_OUT_YTD_QTY','SELL_OUT_YTD_VALUE'];
  // mktrValues: string[];
  mktrValues: any;
  grpCode = 'GROUP_CODE';
  display = "TO_DISPLAY";
  columnCountForAvg: number = 0;
  @Input() period = "";
  lastRowFocusId: any = null;
  dashboardDataAvail: boolean = false;
  periodCode: string = "";
  dashBoardCall: boolean = false;
  grandTotalMap: any = {};
  
  @Input('data') dashboardData: any;
  @Input("filterParameter") filterParameter: any;
  @ViewChild(MatTable) performanceTable: MatTable<any> | any;
  constructor(private _stockSellService:SellPlanningService,private chgDetectorRef: ChangeDetectorRef) { }
        
  ngOnInit() 
  {
    console.log('Inside ngOnIt of SellPerformanceComponent>>'+this.ELEMENT_DATA.length + '  dashboardData>>'+JSON.stringify(this.dashboardData));
    this.initComponent();
    //console.log('Inside ngOnIt of SellPerformanceComponent>>'+JSON.stringify(this.ELEMENT_DATA));
    this.getGrandTotal();
  }
  initComponent()
  {
    console.log('initComponent sell performance!!');
    if(this.ELEMENT_DATA.length == 0)
    {
      this.dashBoardCall = true;
      this.ELEMENT_DATA = this.dashboardData.data;
      var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
      var month = this.filterParameter.substring(this.filterParameter.indexOf('PRD_CODE=')+13,this.filterParameter.indexOf('PRD_CODE=')+15);
      this.selMonth = months[Number(month) - 1];
       console.log("selMonth001>>"+this.selMonth);
    }
    if(this.ELEMENT_DATA)
    {
      if(!this.dashBoardCall)
      {
        this.selMonth = this.period.substring(0, this.period.indexOf(' '));
      }
      this.configureTableData(this.ELEMENT_DATA);
      this.dataSource = new MatTableDataSource<any>(this.ELEMENT_DATA);

      //this.dataSource = this.ELEMENT_DATA;
      this.dataSource.data.reduce((accum, curr) => {
        var grpCode:string= curr['GROUP_CODE'];
        var mainGrp:string= curr['MAIN_GRP'];
        if( grpCode.indexOf('_TOTAL') != -1 || mainGrp.trim() == "LN")
        {
          this.columnCountForAvg++;
        }
      }, 0);
      this.dashboardDataAvail = true;
    }
  }

  ngOnChanges()
  {
    console.log('sell perfomrance dashboardData>> ngOnChanges'+this.dashboardData+ ' filterParameter>>'+this.filterParameter);
   if(this.clearAllParameters || this.dashboardData)
   {
     this.initComponent();
   }
   this.updateActualMonthTotal(this.definedCellTotalJson);
   this.getGrandTotal();
   if( (this.clearAllParameters || this.dashboardData) && this.performanceTable && this.performanceTable != undefined )
   {
     console.log('performanceTable!!!!!!!');
     this.performanceTable.removeFooterRowDef(null);
     this.performanceTable.renderRows();
   }

  }
  // updateActualMonthTotal(definedCellTotalJson: {}) 
  updateActualMonthTotal(definedCellTotalJson: any) 
  {
    var mktr = definedCellTotalJson['MKTR'];
    var totalValue = definedCellTotalJson['TOTAL'];
    var groupId = definedCellTotalJson['GROUP_CODE'];
    var totalQty = definedCellTotalJson['TOTAL_QTY'];
    console.log('totalQty>>'+totalQty+ ' totalValue'+totalValue);
    var valueFlag = false;
    if(mktr == "Y")
    {
      valueFlag = true;
    }
    if( groupId )
    {
      var dataSource = this.dataSource.data;
      var colCount = 0;
      for(let row of dataSource)  
      {
        colCount ++;
        if(row['GROUP_CODE'] == groupId) 
        {
          row['FOCUS'] = true;
          this.setFocus(colCount);
          if(valueFlag)
          {
            row['SELL_OUT_MONTH_VALUE'] = totalValue;
           	//Chnaged by Sainath T. on 29-02-2020-Start
            row['SELL_OUT_MONTH_QTY'] = totalQty;
            //console.log("row['MONTH_TRGT']>>"+row['MONTH_TRGT']+" Number(totalValue*1000)>>"+Number(totalValue*1000))
            var achievedMonthPerc = this.calculateAchievedMonthPercent(groupId,Number(totalValue*1000), row['MONTH_TRGT']);
            //Chnaged by Sainath T. on 29-02-2020-End
            row['MTH_ACHIEVEMENT'] = achievedMonthPerc;
            var curentCellInYear =  this.actualYearValueMap[groupId+"VALUE"] + Number(totalValue);
            row['SELL_OUT_YTD_VALUE'] = curentCellInYear; 
            
            //Chnaged by Sainath T. on 29-02-2020-Start
            var currentCellInYearQty = (this.actualYearValueMap[groupId+"QTY"] + Number(totalQty));
            row['SELL_OUT_YTD_QTY'] = currentCellInYearQty; 
            //console.log("row['YTD_TRGT']>>"+row['YTD_TRGT']+" Number(totalValue*1000)>>"+Number(curentCellInYear*1000))
            var achievedYearPerc = this.calculateAchievedYearPercent(groupId,curentCellInYear*1000,row['YTD_TRGT'])
            //Chnaged by Sainath T. on 29-02-2020-End
            row['YTD_ACHIEVEMENT'] = achievedYearPerc;
          }
          else if(!valueFlag)
          {
            row['SELL_OUT_MONTH_VALUE'] = totalValue;
            row['SELL_OUT_MONTH_QTY'] = totalQty; 

            var achievedMonthPerc = this.calculateAchievedMonthPercent(groupId,Number(totalQty), row['MONTH_TRGT']);
            row['MTH_ACHIEVEMENT'] = achievedMonthPerc;
            var curentCellInYear =  this.actualYearValueMap[groupId+"VALUE"] + Number(totalValue);

            row['SELL_OUT_YTD_VALUE'] = curentCellInYear; 

            var currentCellInYearQty = (this.actualYearValueMap[groupId+"QTY"] + Number(totalQty));
            row['SELL_OUT_YTD_QTY'] =currentCellInYearQty; //new calculated qty value
            var achievedYearPerc = this.calculateAchievedYearPercent(groupId,currentCellInYearQty,row['YTD_TRGT']);
            //console.log('achievedYearPerc>>>'+achievedYearPerc);
            row['YTD_ACHIEVEMENT'] = achievedYearPerc;
          }
          this.calculateMainGrpTotal(dataSource, row, valueFlag);
        } 
        else
        {
          row['FOCUS'] = false;
        }
      }
      this.dataSource.data = dataSource;
    }
  }

  private calculateAchievedMonthPercent(itemCode: string, totalValue: number,monthTarget: any) 
  {
    if(monthTarget && monthTarget != 0)
    {
      return (totalValue / monthTarget) * 100;
    }
    else
    {
      return 0;
    }
  }
  private calculateAchievedYearPercent(itemCode: string, curentCellInYear: number, yearTarget: any) 
  {
    if(yearTarget && yearTarget != 0)
    {
      return (curentCellInYear / yearTarget) * 100;
    }
    else
    {
      return 0;
    }
  }
  private createActualYearValuMap() 
  {
    for(let row of this.ELEMENT_DATA)
    {
      this.actualYearValueMap[row['GROUP_CODE']+'VALUE'] = Number(row['SELL_OUT_YTD_VALUE']) - Number(row['SELL_OUT_MONTH_VALUE']); 
      this.actualYearValueMap[row['GROUP_CODE']+'QTY'] = Number(row['SELL_OUT_YTD_QTY']) - Number(row['SELL_OUT_MONTH_QTY']); 
    }
  }
  getRowTop()
  {
    var eleYTD = document.getElementById('sell_performance_YTD');
    if(eleYTD)
    {
      if(this.secondHeaderTop == 0 || this.secondHeaderTop !=  eleYTD.offsetHeight)
      {
        this.secondHeaderTop = eleYTD.offsetHeight;
      }
    }
    return this.secondHeaderTop+'px';
  }

  private configureTableData(ELEMENT_DATA: any[]) {
    if( ELEMENT_DATA)
    {
      var colCount = 0;
      this.displayedColumns = ['GROUP_DESCR', 'SELL_OUT_MONTH_QTY','SELL_OUT_MONTH_VALUE', 'MTH_ACHIEVEMENT','SELL_OUT_YTD_QTY','SELL_OUT_YTD_VALUE','YTD_ACHIEVEMENT'];
      this.headerLabels=  ['Group', 'Qty','Value in INR(‘000)', 'Achv.','Qty','Value in INR(‘000)','Achv.'];
      //Added by Sainath T on 18/06/2020 -Start
      if(this.dashBoardCall)
      {
        this.displayedColumns = [];
        this.displayedColumns = ['FULL_GROUP_DESCR', 'SELL_OUT_MONTH_QTY','SELL_OUT_MONTH_VALUE', 'MTH_ACHIEVEMENT','SELL_OUT_YTD_QTY','SELL_OUT_YTD_VALUE','YTD_ACHIEVEMENT'];
        this.headerLabels = [];
        this.headerLabels=  ['Group', 'Quantity','Value in INR(‘000)', 'Achievement','Quantity','Value in INR(‘000)','Achievement'];
      }
      //Added by Sainath T on 18/06/2020 - End
      this.inputType= ['text', 'number','number', 'number', 'number', 'number', 'number'];
      this.mktrValues = ['N', 'N','Y', 'N','N','Y','N'];

      this.columnProperties = []; 
      
      for( var key of this.displayedColumns )
      {
        var headerObj = {'name':key,'display':this.headerLabels[colCount], 'width': '100px', 'inputType':this.inputType[colCount]
        ,'format':this.mktrValues[colCount]};
        this.columnProperties.push(headerObj);
        colCount++;
      }
    }
    this.createActualYearValuMap();
  }

  getHiddenFlag(columnName: any)
  {
    //added by saunath t. on 18/04/2020
    if(columnName == 'GROUP_DESCR' || columnName == 'FULL_GROUP_DESCR')
    {
      return true;
    }
    else
    {
      return false;
    }
  }

  calculateMainGrpTotal(dataSource: any[], row:any, valueFlag:boolean) 
  {
  
    var mainGrp = row['MAIN_GRP'];
    //console.log("mainGrp>>"+mainGrp);
    var monthQtyTotal = 0;
    var monthValueTotal = 0;
    var ytdQtyTotal = 0;
    var ytdValueTotal = 0;
    for(let r = 0; r < dataSource.length; r++)
    {
      var row = dataSource[r];
      if( row["MAIN_GRP"] == mainGrp && row['GROUP_CODE'] != mainGrp+"_TOTAL" )
      {
        monthQtyTotal = monthQtyTotal + Number(row["SELL_OUT_MONTH_QTY"]);
        monthValueTotal = monthValueTotal + Number(row["SELL_OUT_MONTH_VALUE"]);
        ytdQtyTotal = ytdQtyTotal + Number(row["SELL_OUT_YTD_QTY"]);
        ytdValueTotal = ytdValueTotal + Number(row["SELL_OUT_YTD_VALUE"]);
      }
      else if( row["MAIN_GRP"] == mainGrp && row['GROUP_CODE'] == mainGrp+"_TOTAL" )
      {
        row["SELL_OUT_MONTH_QTY"] = monthQtyTotal;
        row["SELL_OUT_MONTH_VALUE"] = monthValueTotal;
        row["SELL_OUT_YTD_QTY"] = ytdQtyTotal;
        row["SELL_OUT_YTD_VALUE"] = ytdValueTotal;
        if(valueFlag)
        {
          //Chnaged by Sainath T. on 29-02-2020-Start
          row["MTH_ACHIEVEMENT"] = this.calculateAchievedMonthPercent("",Number(monthValueTotal*1000), Number(row['MONTH_TRGT']));
          row['YTD_ACHIEVEMENT'] = this.calculateAchievedYearPercent("",Number(ytdValueTotal*1000), Number(row['YTD_TRGT']));
          //Chnaged by Sainath T. on 29-02-2020-End
        }
        else
        {
          row["MTH_ACHIEVEMENT"] = this.calculateAchievedMonthPercent("",Number(monthQtyTotal), Number(row['MONTH_TRGT']));
          row['YTD_ACHIEVEMENT'] = this.calculateAchievedYearPercent("",Number(ytdQtyTotal), Number(row['YTD_TRGT']));
        }
      }
    }
  }

  setFocus(rowId: any)
  {
    var rowElement = document.getElementById('row_'+(rowId - 1));
    if((this.lastRowFocusId == null || this.lastRowFocusId != (rowId - 1 )) && rowElement) //(this.lastRowFocusId == null || this.lastRowFocusId != rowId )
    {
      if(rowId <= ((this.dataSource.data.length) / 2) )
      {
        rowElement.scrollIntoView(false);
      }
      else
      {
        rowElement.scrollIntoView(true);
      }
      this.lastRowFocusId = rowId - 1;
    }
  }
  //Added byy Sainath T. on 18/04/2020 [FOr dashboard call related changes]-Start
  // getDashboardData()
  // {
  //    var year:any = new Date().getFullYear(); //2020
  //    var month:any = new Date().getMonth() + 1; //3
  //    var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
     
  //    if(month < 10)
  //    {
  //       month = "0"+month;
  //    }
  //    this.periodCode = ""+year+month;

  //     var jsonData = {
  //       'stan_code' : '',
  //       'prd_code' : this.periodCode,
  //       'pos_code' :''
  //     }
  //     this._stockSellService.getSellPerformanceDashboardData(jsonData).subscribe( 
  //       dashData =>
  //       {
  //         this._stockSellService.setLoading(true);
  //         setTimeout(() => {
  //           console.log('dashboard data001>>'+dashData);
  //          this.ELEMENT_DATA = JSON.parse((<any>dashData)._body);
  //          this.initComponent();
  //          this.selMonth = months[Number(month) - 1];
  //           console.log("selMonth>>"+this.selMonth);
  //           //Sai
  //           this.getGrandTotal();

  //          this._stockSellService.setLoading(false);
  //         },200);
  //       }
  //     );
  // }
  
  //Added byy Sainath T. on 18/04/2020 [FOr dashboard call related changes]-End
  getGrandTotal()
  {
    this.grandTotalMap = {};
    for(let colIdx = 0; colIdx < this.displayedColumns.length; colIdx++)
    {
        let columName = this.displayedColumns[colIdx];
        console.log('columName>>'+columName+'colIdx'+colIdx);
        var total = 0;
        var percentageFlag = false;
        var resp :any ;
        if(colIdx != 0)
        {
        var currValue:any = null;
        this.dataSource.data.reduce((accum, curr) => 
        {
          var grpCode:string= curr['GROUP_CODE'];
          var mainGrp:string= curr['MAIN_GRP'];
          if( grpCode.indexOf('_TOTAL') != -1 || mainGrp.trim() == 'LN')
          {
            currValue = Number(curr[columName]);
              if(columName == 'MTH_ACHIEVEMENT' || columName == 'YTD_ACHIEVEMENT')
              {
                percentageFlag = true;
                total = (total + currValue);
              }
              else
              {
                percentageFlag = false;
                total = total + currValue
              }
            }
            }, 0);
            if(percentageFlag)
            { 
              resp = Math.round((total/this.columnCountForAvg));
        }
        else
        {
          resp =  Number(total);
        }
      }
      else if(colIdx == 0)
      {
        resp =  "Total";
      }
      else
      {
        resp =  "";
      }
      this.grandTotalMap[colIdx] = resp;
      this.chgDetectorRef.detectChanges();
    }
  }
}

