import { Component, OnInit,ViewChild } from '@angular/core';
import { DatePipe } from '@angular/common';
import { exportDataGrid } from "devextreme/exporter/exceljs/excelExporter";
import { Workbook } from 'exceljs';
import { saveAs } from 'file-saver';
import { JobmasterService } from 'src/app/jobconfiguration/jobmaster/jobmaster.service';
import { ToastrService } from 'ngx-toastr';
import { DashboardService } from 'src/app/dashboard/dashboard.service';
import { ProductiondashboardstagewisereportService } from './productiondashboardstagewisereport.service';
import { get } from 'http';
import { Router} from '@angular/router';
import { stat } from 'fs';
import { NgxSpinnerService } from 'ngx-spinner';

@Component({
  selector: 'app-productiondashboardstagewisereport',
  templateUrl: './productiondashboardstagewisereport.component.html',
  styleUrls: ['./productiondashboardstagewisereport.component.css']
})
export class ProductiondashboardstagewisereportComponent implements OnInit {
  dateRange:any;
  Originallst: any= [];
  Productionstagewiselst: any =[];
  jobProductTypeList : any=[];
   _ddlProjecttypeSettings: {};
   _ddlTimeTakenSettings :{};
   userid: string = localStorage.getItem('userid');
   _userselectedItems: any[] = [];
   metaall: any[] = [];
   startdate:any;
   enddate:any;
   projectdefinitionid:number;
   p_projectdefinitionid:number;
   p_startdate:any;
   p_enddate:any;
   p_mode:any;
   p_jobid:any;
   p_filterValue: any;
   isarchive=1;
   
  constructor(private datepipe :DatePipe,
    private jobmasterservice: JobmasterService,
    private toastr: ToastrService,
    private productiondashboardstagewisereportservice: ProductiondashboardstagewisereportService,
    private router: Router,
    private SpinnerService: NgxSpinnerService) { 
      const navigation = this.router.getCurrentNavigation();
      const state = navigation.extras.state as {
        workflowid: any,
        fromdate: any,
        todate: any,
        jobid: any,
        mode: any,
        job_title:any,
      };
      if (state !== null && state !== undefined) {
        this.p_projectdefinitionid = state.workflowid;
        this.p_startdate = state.fromdate;
        this.p_enddate = state.todate;
        this.p_jobid = state.jobid;
        this.p_mode = state.mode;
        this.p_filterValue = state.job_title;
      }

    }

  ngOnInit(): void {
  this.onload();
  }

  onload(){
    this._ddlProjecttypeSettings = {
      singleSelection: false,
      idField: 'projectdefinitionid',
      textField: 'project_subtitle',
     // selectAllText: 'Select All',
     // unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true
  };
  this.jobmasterservice.getJobProductType(this.userid).subscribe(res => {
      if (res !== undefined && res !== null && res[0] !== undefined && res[0] !== null) {
          if (JSON.parse(res[0]).length > 0) {
              this.jobProductTypeList = JSON.parse(res[0]);
              //console.log( this.jobProductTypeList )
              if(this.p_mode == "dashboard"){
                this._userselectedItems=this.jobProductTypeList.filter(x=>x.projectdefinitionid == this.p_projectdefinitionid);
                this.projectdefinitionid=this.jobProductTypeList[0].projectdefinitionid;
                this.dateRange = [new Date(this.p_startdate), new Date(this.p_enddate)]; 
              this.onrepdateValueChange(this.dateRange);
              }else{
                this._userselectedItems=this.jobProductTypeList.filter(x=>x.projectdefinitionid == this.jobProductTypeList[0].projectdefinitionid);
                this.projectdefinitionid=this.jobProductTypeList[0].projectdefinitionid;
              }       
          }
      }
  }
  );
  }

  onrepdateValueChange(value: Date): void {
    this.startdate = this.datepipe.transform(value[0], 'dd-MMM-yyyy');
    this.enddate = this.datepipe.transform(value[1], 'dd-MMM-yyyy');
    if(this.p_mode == "dashboard"){
      let pdid=this.p_projectdefinitionid;
      this.projectdefinitionid=pdid;
    }
      if(this.projectdefinitionid!=0 && this.startdate !=null && this.startdate !=undefined &&
        this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined ){
          this.getproductionreport(this.projectdefinitionid);
      } 
  } 

  onItemSelect(item: any) {
    this.projectdefinitionid=item.projectdefinitionid;
    if(this.projectdefinitionid!=0 && this.startdate !=null && this.startdate !=undefined &&
        this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined ){
          this.getproductionreport(this.projectdefinitionid);
    }
  }

  onDeSelectAll(item:any){
    this.Productionstagewiselst = [];
    }
    onSelectAll(item:any){
      if(item.length !=0 && this.startdate !=null && this.startdate !=undefined &&
        this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined ){
          this._userselectedItems = item;
       this.getproductionreport(this.projectdefinitionid);
      }
    }
    onItemDeSelect(item: any) {
     
      if(this._userselectedItems.length !=0 && this.startdate !=null && this.startdate !=undefined &&
        this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined ){
       this.getproductionreport(this.projectdefinitionid);
      }else{
        if(this._userselectedItems.length ==0){
          this.Productionstagewiselst = [];
        }
      }
    
    }
    onContentReady(e) {
   console.log(e.component.pageIndex());//page click startin 0..
   console.log(e.component.pageSize());//no of row
  // alert("Page Click");
  	}

  getproductionreport(prodefid){
    this.SpinnerService.show();
    const inputdata= [];
    let  multiple_prodefid :string = "";
    let index =0;

    this._userselectedItems.forEach(element => {
    index = index+1;
    if(index == 1){
      multiple_prodefid = element.projectdefinitionid.toString();
    }else{
      multiple_prodefid =multiple_prodefid + ','+element.projectdefinitionid.toString();
    }
    });
    inputdata.push({p_projectdefinitionid:prodefid,
    p_startdate:this.startdate,
    p_enddate:this.enddate,
    multipleprojectid_p:multiple_prodefid,
    p_isarchive:this.isarchive
  });

    this.productiondashboardstagewisereportservice.GetProductionDashboardStagewiseReport(inputdata[0]).subscribe(res=>{
      this.SpinnerService.hide();
      debugger;
      if(res.body != null && res.body != undefined){
        let resarr=[];
          resarr=res.body;
          this.Originallst=[];
          resarr.forEach(val => {   
            this.Originallst.push(JSON.parse(val));
          });
        this.Productionstagewiselst = this.Originallst;        
      }
    }, err => { 
      this.SpinnerService.hide();
      this.toastr.error(err.message); });
  }
  selectarchivejob(evt){
    if(evt.target.checked==true){
      this.isarchive=0;
    }else{
      this.isarchive=1;
    }
    if(this._userselectedItems.length!=0 && this.startdate !=null && this.startdate !=undefined &&
      this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined ){
     this.getproductionreport(this.projectdefinitionid);
    }
    } 
  onExporting(e) {
    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet('Stage wise Report');
    exportDataGrid({
      component: e.component,
      worksheet,
      showBorders: true,
      autoFilterEnabled: true,
      rowAlternationEnabled:true,
      columnAutoWidth:true,
      customizeCell(options) {
        const { gridCell } = options;
        const { excelCell } = options;
        const m = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
        if (gridCell.rowType == "header") {
          excelCell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: '2b4c81' } };
          excelCell.font = { color: { argb: 'FFFFFF' }, 'bold': true };
      }
      if (gridCell.rowType === 'header' || gridCell.rowType === 'data') {
        if (excelCell.fullAddress.row % 2 === 0) {
          excelCell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'dbedf2' } };
        }
      }
      if (gridCell.column.dataField == "JobCreationDate" &&  gridCell.rowType === 'data') {
        if(gridCell.value != undefined && gridCell.value != "" && gridCell.value != null){
          const day = new Date(gridCell.value);
           excelCell.value =day.getDate() + '-' + m[day.getMonth()] + '-' + day.getFullYear();
        }
      }
      excelCell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' }, color: { argb: '000000' } };
      }
    }).then(() => {
      var currentdate = new Date();
      var datetime = currentdate.getDate() + "-" + (currentdate.getMonth() + 1) + "-" + currentdate.getFullYear()
          + "_" + currentdate.getHours() + "" + currentdate.getMinutes() + "" + currentdate.getSeconds();
      workbook.xlsx.writeBuffer().then((buffer) => {
        saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'StagewiseReport_'+datetime+'.xlsx');
      });
    });
    e.cancel = true;
  }
}
