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

@Component({
  selector: 'app-processwiseproductionreport',
  templateUrl: './processwiseproductionreport.component.html',
  styleUrls: ['./processwiseproductionreport.component.css']
})
export class ProcesswiseproductionreportComponent implements OnInit {
  @ViewChild(DxDataGridComponent, { static: false }) dataGrid: DxDataGridComponent;

  Originallst: any= [];
  Processwiseproducationlst: any =[];
  jobProductTypeList : any=[];
   _ddlProjecttypeSettings: {};
   _ddljobSettings :{};
   userid: string = localStorage.getItem('userid');
   _userselectedItems: any[] = [];
   metaall: any[] = [];
   startdate:any;
   enddate:any;
   projectdefinitionid:number;
   projectdefinitionid_p: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;
   alljob : boolean = false;
   singlejob :boolean = false;
   export_option : boolean =true;
   mode=0;
   org_joblist: any= [];
   isarchive=1;	
  constructor(private datepipe :DatePipe,
    private jobmasterservice: JobmasterService,
    private toastr: ToastrService,
    private processwiseproductionreport : ProcesswiseproductionreportserviceService,
    private router: Router,
    private route: ActivatedRoute,
    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.jobid = 0;
    this.route.queryParams.subscribe((params) => {
      debugger;
      this.mode = params.mode;
      console.log(params.pid)
      this.p_projectdefinitionid =params.pid;
    });
    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]);
            if(this.p_mode === 'dashboard'){
              this._userselectedItems=this.jobProductTypeList.filter(x=>x.projectdefinitionid == this.p_projectdefinitionid);
            this.projectdefinitionid=this.p_projectdefinitionid;
            this.dateRange = [new Date(this.p_startdate), new Date(this.p_enddate)];
            this.onrepdateValueChange(this.dateRange);
            }else{
              if(this.mode==1){
                var selected_pj=[];
                var mult_pid=this.p_projectdefinitionid.toString().split(",");
                mult_pid.forEach(element => {
                   selected_pj.push(this.jobProductTypeList.filter(x=>x.projectdefinitionid == Number(element))[0]);
                  this._userselectedItems=selected_pj;               
                });
                 var today=new Date();
                this.dateRange = [new Date(today), new Date(today)];
                //this.dateRange = [new Date('01-Sep-2023'), new Date('07-Sep-2023')];
                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 {
    debugger;
    this._jobselectedItems = [];
    this.Processwiseproducationlst = [];
    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');
      }
    }
  } 

  onItemSelect(item: any,mode) {
    if(mode === 'prodefid'){
    this.projectdefinitionid=item.projectdefinitionid;
    console.log(item);
    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.dataGrid.instance.beginCustomLoading('Loading Please wait...');
          this.export_option = false;
          this.getproductionreport(this.projectdefinitionid);
      }
  }
  }

  onItemDeSelect(item: any,mode) {
    if(mode === 'job'){
      if(this._jobselectedItems.length === 0){
        this.Processwiseproducationlst = [];
      }else{
        //start loading screen dx-grid.
        this.dataGrid.instance.beginCustomLoading('Loading Please wait...');
          this.jobid = item.jobid; 
          this.export_option = false;
          this.projectdefinitionid=this.org_joblist.filter(x=>x.jobid==item.jobid)[0].projectdefinitionid;
          this.getproductionreport_deselect(this.projectdefinitionid); 
      }
    }else{
      debugger;
      this.Processwiseproducationlst=this.Processwiseproducationlst.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,
      mode_report: 'process',
      multipleprojectid_p:multiple_prodefid,
      p_isarchive:this.isarchive		
    });
    
    this.processwiseproductionreport.GetProcesswiseProductionReport(inputdata[0]).subscribe(res=>{
      this.SpinnerService.hide();
      debugger;
      if(res.body != null && res.body != undefined){
        let resarr=[];
        let incremnt :any =0;
        let temp_lst = [];
        let loading_datagrid = false;
        if(this.jobid === 0){
          resarr=res.body;
          this.Originallst=[];
          resarr.forEach(val => {   
            this.Originallst.push(JSON.parse(val));
          });
        this.Processwiseproducationlst = this.Originallst;    
        this.p_mode = '';   
        }else{
          if(this.alljob === true){
            this.singlejob = true;
            this.alljob = false;
            this.Processwiseproducationlst = [];
          }
          if(this.Processwiseproducationlst.length === 0){
            resarr=res.body;
            if(resarr.length !=0){
              this.Originallst=[];
              resarr.forEach(val => {   
                this.Originallst.push(JSON.parse(val));
              });
            this.Processwiseproducationlst = this.Originallst;
            }
          this.dataGrid.instance.endCustomLoading(); 
          this.export_option = true;
          this.p_mode = ''; 
          }else{
            resarr=res.body;
            if(resarr.length !=0){
              this.Originallst=[];
            resarr.forEach(val => {   
              this.Originallst.push(JSON.parse(val));
            });
          temp_lst = this.Originallst;    
          temp_lst.forEach(i=>{
            this.Processwiseproducationlst.forEach(j=>{
              if(i.Process === j.Process){
                j.WIP = j.WIP + i.WIP;
                j.Completed = j.Completed + i.Completed;
                j.Bypassed = j.Bypassed + i.Bypassed;
                j.YTS = j.YTS + i.YTS;
              }
              
              else{
                incremnt = incremnt + 1;
              }
              if(this.Processwiseproducationlst.length === incremnt){
                this.Processwiseproducationlst.push(i);
                incremnt = 0;
              }
            });
            incremnt = 0;
            loading_datagrid = true;
          });
          this.p_mode = ''; 
          if(loading_datagrid){
            this.dataGrid.instance.endCustomLoading();
            this.export_option = true;
          }    
            }
            this.dataGrid.instance.endCustomLoading();
            this.export_option = true;
          }
        }
      }
    }, 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:false,
      p_userid:this.userid	
    });
    
    this.processwiseproductionreport.GetJobTitle(input[0]).subscribe(res=>{
      debugger;
      if(res.body!=null && res.body != undefined){
        debugger;
        this.joblst= [];
        this._jobselectedItems = [];
       // this.joblst = JSON.parse(res.body);
       if(res.body[0]!=null){
        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.Processwiseproducationlst = [];
          this.getproductionreport(this.projectdefinitionid);
        }
        if(this.jobid === 0 && type=="onselall"){
          this.alljob = true;
          this.Processwiseproducationlst = [];
          this.getproductionreport(this.projectdefinitionid)
        }   
      }
    });
  }
  selectarchivejob(evt){
    debugger;
    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('Process 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' }), 'Processwisereport_'+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.Processwiseproducationlst = [];
    }else{
      this.Processwiseproducationlst = [];
      this.joblst=[];
      this.org_joblist=[];
    }

  }
  
  getproductionreport_deselect(prodefid){
    const inputdata= [];
    inputdata.push({
      p_projectdefinitionid: prodefid,
      p_startdate:this.startdate,
      p_enddate: this.enddate,
      p_jobid : this.jobid,
      mode_report: 'process',
      multipleprojectid_p:prodefid.toString()
    });
    
    this.processwiseproductionreport.GetProcesswiseProductionReport(inputdata[0]).subscribe(res=>{
      debugger;
      if(res.body != null && res.body != undefined){
        let resarr=[];
        let incremnt :any =0;
        let temp_lst = [];
        let loading_grid = false;
          resarr=res.body;
          if(resarr.length !=0){
            this.Originallst=[];
            resarr.forEach(val => {   
              this.Originallst.push(JSON.parse(val));
            });
            temp_lst = this.Originallst;    
          this.p_mode = '';   
          temp_lst.forEach(i=>{
            this.Processwiseproducationlst.forEach(j=>{
              debugger;
              if(i.Process === j.Process && i.Workflow === j.Workflow){
                j.WIP = j.WIP - i.WIP;
                if(j.WIP < 0)
                    j.WIP = Math.abs(j.WIP);
    
                j.Completed = j.Completed - i.Completed;
                if(j.Completed < 0)
                    j.Completed = Math.abs(j.Completed);
    
                j.Bypassed = j.Bypassed - i.Bypassed;
                if(j.Bypassed < 0)
                    j.Bypassed = Math.abs(j.Bypassed);
                    
                j.YTS = j.YTS - i.YTS;
                if(j.YTS < 0)
                    j.YTS = Math.abs(j.YTS);
              }
              loading_grid =true;
    
            });
          });
          if(loading_grid){
            this.dataGrid.instance.endCustomLoading();
            this.export_option = true;
          }
          }
          this.dataGrid.instance.endCustomLoading();
            this.export_option = true;
      }
    });
    
  }

}
