import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { DxDataGridModule } from 'devextreme-angular';
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 { ProjectDefinition } from 'src/app/projectconfiguration/projectconfiguration/projectdefinition';
import { ProcesswiseproductionreportserviceService } from '../processwiseproductionreport/processwiseproductionreportservice.service';
import { UserwiseproductionreportserviceService } from './userwiseproductionreportservice.service';
import { Router } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-userwiseproductionreport',
  templateUrl: './userwiseproductionreport.component.html',
  styleUrls: ['./userwiseproductionreport.component.css']
})
export class UserwiseproductionreportComponent implements OnInit {
																				   

  
  Originallst: any= [];
  Userwiseproducationlst: any =[];
  jobProductTypeList : any=[];
   _ddlProjecttypeSettings: {};
   _ddljobSettings :{};
   userid: string = localStorage.getItem('userid');
   _userselectedItems: any[] = [];
   metaall: any[] = [];
   startdate:any;
   enddate:any;
   projectdefinitionid:number;
   joblst: any;
   _jobselectedItems: any = [];
   jobid: any;
   p_filterValue: any;
   p_projectdefinitionid: any;
   p_startdate:any;
   p_enddate:any;
   p_jobid:any;
   p_mode:any;
   dateRange:any;
   org_joblist: any= [];
   alljob : boolean = false;
   isarchive=1;					  
   roleid: string = localStorage.getItem('roleid');
   normal_userid: string = environment.normal_userid;
   isnormaluser=false;						 
   
						
  constructor(private datepipe :DatePipe,
    private jobmasterservice: JobmasterService,
    private toastr: ToastrService,
    private processwiseproductionreport : ProcesswiseproductionreportserviceService,
    private userwiseproductionreport: UserwiseproductionreportserviceService,
    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.org_joblist=[];
    if(this.roleid==this.normal_userid)this.isnormaluser=true;   
    this._ddljobSettings = {
      singleSelection: false,
      idField: 'jobid',
      textField: 'title',
     // selectAllText: 'Select All',
     // unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true
  };
    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._jobselectedItems = [];
    this.Userwiseproducationlst = [];
    this.org_joblist=[];
    this.startdate = this.datepipe.transform(value[0], 'dd-MMM-yyyy');
    this.enddate = this.datepipe.transform(value[1], 'dd-MMM-yyyy');
    if(this.projectdefinitionid!=0 && this.startdate !=null && this.startdate !=undefined &&
      this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined && this.jobid != null
      && this.jobid != undefined && this.jobid !=0){
        this.getproductionreport(this.projectdefinitionid);

		 /* if(this._userselectedItems.length > 0){
          this._userselectedItems.forEach(element => {

            this.jobid =0;
            this.alljob = true;
            this.loadjob(element.projectdefinitionid,'all');  
          });
        } else{
          this.loadjob(this.projectdefinitionid,'all');
        }
        if(this._jobselectedItems.length === 0){
          this.jobid = 0;
          this.getproductionreport(this.projectdefinitionid);
        }  */
         //this.getjobstatusreport(this.projectdefinitionid);
      // this.getlotmetadata(this.projectdefinitionid);
    }else if(this.projectdefinitionid!=0 && this.startdate !=null && this.startdate !=undefined &&
      this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined){
	 if(this._userselectedItems.length > 0){
        this._userselectedItems.forEach(element => {
          this.jobid =0;
          this.alljob = true;
          this.loadjob(element.projectdefinitionid,'all');  
        });
        this.getproductionreport(this.projectdefinitionid);
      } else{
        this.loadjob(this.projectdefinitionid,'onselall');
      }
    }
    // let current_date =this.datepipe.transform(date, 'dd-MMM-yyyy');
     //console.log("start="+this.datepipe.transform(value[0], 'dd-MMM-yyyy'))
    // console.log("end="+this.datepipe.transform(value[1], 'dd-MMM-yyyy'))
  } 

  onItemSelect(item: any,mode) {
    if(mode === 'prodefid'){
    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.jobid !=null
        && this.jobid != undefined){
       this.loadjob(this.projectdefinitionid,'onselall');
    }else if(this.projectdefinitionid!=0 && this.startdate !=null && this.startdate !=undefined &&
      this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined){
      this.loadjob(this.projectdefinitionid,'onselall');
    }
  }else if(mode ==='job'){
    this.jobid = item.jobid;
      if(this.projectdefinitionid!=0 && this.startdate !=null && this.startdate !=undefined &&
        this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined && this.jobid !=null
        && this.jobid != undefined){						 
          this.getproductionreport(this.projectdefinitionid);
      }
  }
  }

  onItemDeSelect(item: any,mode) {
    //console.log(item);
									   
    if(mode === 'job'){

      if(this._jobselectedItems.length === 0){
      this.Userwiseproducationlst = [];
      }else{
        //start loading screen dx-grid.
          this.jobid = item.jobid; 
          this.projectdefinitionid=this.org_joblist.filter(x=>x.jobid==item.jobid)[0].projectdefinitionid;
         this.joblst=this.joblst.filter(x=> x.projectdefinitionid != item.projectdefinitionid);
         //this.Userwiseproducationlst=this.Userwiseproducationlst.filter(x=> x.Workflow != item.project_subtitle);
        }		   
	   
    }else{
      debugger;
this.Userwiseproducationlst=this.Userwiseproducationlst.filter(x=> x.Workflow != item.project_subtitle);
        this.joblst=this.joblst.filter(x=> x.projectdefinitionid != item.projectdefinitionid);
        if(this.joblst.length==0)this.org_joblist=[];
    }
  }

  getproductionreport(prodefid){
    this.SpinnerService.show();
	    let  multiple_prodefid :string = "";
    this._userselectedItems.forEach(element => {
      if(multiple_prodefid == ""){
        multiple_prodefid = element.projectdefinitionid.toString();
      }else{
        multiple_prodefid =multiple_prodefid + ','+element.projectdefinitionid.toString();
      }
    });   
    const inputdata= [];
    inputdata.push({
      p_projectdefinitionid: prodefid,
      p_startdate:this.startdate,
      p_enddate: this.enddate,
      p_jobid : this.jobid,
	   multipleprojectid_p:multiple_prodefid,
     p_isarchive:this.isarchive,
     isnormaluser:this.isnormaluser,
     p_userid:this.userid					   
    });
    this.userwiseproductionreport.GetUserwiseProductionReport(inputdata[0]).subscribe(res=>{
      debugger;
      this.SpinnerService.hide();
      if(res.body != null && res.body != undefined){
        let resarr=[];
        this.Userwiseproducationlst = [];
          resarr=res.body;
          if(this.jobid === 0 || this._jobselectedItems.length ==1){
            this.Originallst=[];
          }
          resarr.forEach(val => {   
            this.Originallst.push(JSON.parse(val));
          });
        this.Userwiseproducationlst = this.Originallst;    												
        this.p_mode = '';
      }
    }, err => { 
      this.SpinnerService.hide();
      this.toastr.error(err); });
  }

  loadjob(prodefid,type){
    let  multiple_prodefid :string = "";
    this._userselectedItems.forEach(element => {
      if(multiple_prodefid == ""){
        multiple_prodefid = element.projectdefinitionid.toString();
      }else{
        multiple_prodefid =multiple_prodefid + ','+element.projectdefinitionid.toString();
      }
    });
    const input=[];
    input.push({
      p_projectdefinitionid: prodefid,
      p_startdate:this.startdate,
      p_enddate: this.enddate,
      p_isarchive:this.isarchive,
      multipleprojectid_p:multiple_prodefid,
      isnormaluser:this.isnormaluser,
      p_userid:this.userid
    });

    this.processwiseproductionreport.GetJobTitle(input[0]).subscribe(res=>{
      debugger;
      if(res.body!=null && res.body != undefined){
        this.joblst= [];
        this._jobselectedItems = [];
        if(res.body[0]!=null){
        //this.joblst = JSON.parse(res.body);
        let result=JSON.parse(res.body);
        result.forEach(element => {
        this.org_joblist.push(element);
      });
    }

        this.joblst=this.org_joblist.filter(x=>x);
        if(this.p_mode === 'dashboard'){
          this._jobselectedItems = this.joblst.filter(x=>x.jobid === this.p_jobid);
          this.jobid = this.joblst[0].jobid;
          this.Userwiseproducationlst = [];
          this.getproductionreport(this.projectdefinitionid);
        }
        if(this.jobid === 0 && type=="onselall"){
          this.alljob = true;
          this.Userwiseproducationlst = [];
          this.getproductionreport(this.projectdefinitionid)
        }
      //  this.getproductionreport(this.projectdefinitionid);
        // let resarr=[];
        // resarr=res.body;
        // this.joblst=[];
        // resarr.forEach(val => {   
        //   this.joblst.push(JSON.parse(val));
        // });
        // console.log('joblst:',this.joblst);
      //this.Processwiseproducationlst = this.Originallst;    
      }
    });
  }

  selectarchivejob(evt){
    if(evt.target.checked==true){
      this.isarchive=0;
    }else{
      this.isarchive=1;
    }
    this.jobid =0;
    if(this.jobid==0)this.org_joblist=[];
    if(this._jobselectedItems.length ==1)this.alljob = true;
    if(this.projectdefinitionid!=0 && this.startdate !=null && this.startdate !=undefined &&
      this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined && this.jobid != null
      && this.jobid != undefined && this.jobid !=0){
        this.getproductionreport(this.projectdefinitionid);

		 /* if(this._userselectedItems.length > 0){
          this._userselectedItems.forEach(element => {

            this.jobid =0;
            this.alljob = true;
            this.loadjob(element.projectdefinitionid,'all');  
          });
        } else{
          this.loadjob(this.projectdefinitionid,'all');
        }
        if(this._jobselectedItems.length === 0){
          this.jobid = 0;
          this.getproductionreport(this.projectdefinitionid);
        }  */
         //this.getjobstatusreport(this.projectdefinitionid);
      // this.getlotmetadata(this.projectdefinitionid);
    }else if(this.projectdefinitionid!=0 && this.startdate !=null && this.startdate !=undefined &&
      this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined){
	 if(this._userselectedItems.length > 0){
        this._userselectedItems.forEach(element => {
          this.jobid =0;
          this.alljob = true;
          this.loadjob(element.projectdefinitionid,'all');  
        });
        this.getproductionreport(this.projectdefinitionid);
      } else{
        this.loadjob(this.projectdefinitionid,'onselall');
      }
    }
    } 
  onExporting(e) {
    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet('User wise Report');
    exportDataGrid({
      component: e.component,
      worksheet,
      showBorders: true,
      autoFilterEnabled: true,
      rowAlternationEnabled:true,
      columnAutoWidth:true,
      customizeCell(options) {
        const { gridCell } = options;
        const { excelCell } = options;
      
        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' } };
        }
      }
      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' }), 'Userwisereport_'+datetime+'.xlsx');
      });
    });
    e.cancel = true;
  }

  onSelectAll(item: any,mode){
    if(mode === 'job'){
      if(this.projectdefinitionid!=0 && this.startdate !=null && this.startdate !=undefined &&
        this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined){
        this.jobid =0;
        this.alljob = true;
        this.getproductionreport(this.projectdefinitionid);
      }
    }else{
      debugger;
      this._userselectedItems=this.jobProductTypeList;
        if(this.jobProductTypeList.length > 0){
          this.jobProductTypeList.forEach(element => {
            debugger;
            this.jobid =0;
            this.alljob = true;
            this.loadjob(element.projectdefinitionid,'all');  
          });
          this.getproductionreport(this.projectdefinitionid);
        } 

    }
  }
  onDeSelectAll(item: any,mode){
    if(mode === 'job'){
      this.Userwiseproducationlst = [];
    }else{
      this.Userwiseproducationlst = [];
      this.joblst=[];
      this.org_joblist=[];
    }
  }
}
