import { Component, OnInit, ViewChild } from '@angular/core';
import { DatePipe } from '@angular/common';
import { DxDataGridComponent, 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 { UserwiseproductionlogreportService } from './userwiseproductionlogreport.service';
import { ProcesswiseproductionreportserviceService } from '../processwiseproductionreport/processwiseproductionreportservice.service';
import { Router } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import { environment } from 'src/environments/environment';

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

 Originallst: any= [];
 userwiseprologlst: any =[];
 jobProductTypeList : any=[];
  _ddlProjecttypeSettings: {};
  _ddlTimeTakenSettings :{};
  userid: string = localStorage.getItem('userid');
  roleid: string = localStorage.getItem('roleid');
  normal_userid: string = environment.normal_userid;
  isnormaluser=false;
  _userselectedItems: any[] = [];
  metaall: any[] = [];
  startdate:any;
  enddate:any;
  projectdefinitionid:number;
  timetakenlst: any;
  _timeselectedItems: any = [];
currentFilter : any= [];
filterValue : any = [];
_ddljobSettings : any =[];
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;
   isarchive=1;
   myArray:any=[];
   columns: any[] = [];
  constructor(private datepipe :DatePipe,
    private jobmasterservice: JobmasterService,
    private toastr: ToastrService,
    private userwiseproductionlogreportservice : UserwiseproductionlogreportService,
    private processwiseproductionreport : ProcesswiseproductionreportserviceService,
    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,
      };
      debugger;
      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 {
    if(this.roleid==this.normal_userid)this.isnormaluser=true;
    this._ddljobSettings = {
      singleSelection: true,
      idField: 'jobid',
      textField: 'title',
     // selectAllText: 'Select All',
     // unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true
  };
    
  this._ddlTimeTakenSettings = {
    singleSelection: true,
    idField: 'value',
    textField: 'text',
   // selectAllText: 'Select All',
   // unSelectAllText: 'UnSelect All',
    itemsShowLimit: 7,
    allowSearchFilter: true
};
  
    this.timetakenlst = [{
      id: '1',
      text: 'Less than 3 min',
      value: ['TotalMinutes','<',3]
    }, {
      id: '2',
      text: 'Less than 5 min',
      value:[
        'TotalMinutes', '<', 5
      ],
    }, {
      id: '3',
      text: 'Greater than 10 min',
      value: [
        'TotalMinutes','>=',10
      ],
    }, {
      id: '4',
      text: 'Greater than 15 min',
      value: [
        'TotalMinutes','>=',15
      ],
    }];
  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.p_filterValue ='';
              this._userselectedItems=this.jobProductTypeList.filter(x=>x.projectdefinitionid == this.jobProductTypeList[0].projectdefinitionid);
              this.projectdefinitionid=this.jobProductTypeList[0].projectdefinitionid;
            }  
             
          }
      }
  }
  );
  }

  //date selection
  onrepdateValueChange(value: Date): void {
   
    this._jobselectedItems = [];
    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.getuserwiseproductionreport(this.projectdefinitionid);
    }
  } 

  onItemSelect(item: any) {
  
    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.getuserwiseproductionreport(this.projectdefinitionid);
          // this.getuserwiseproductionreport(this.projectdefinitionid);
   //this.getjobstatusreport(this.projectdefinitionid);
        // this.getlotmetadata(this.projectdefinitionid);

  }
}
onDeSelectAll(item:any){
  this.userwiseprologlst = [];
  }
  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.getuserwiseproductionreport(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.getuserwiseproductionreport(this.projectdefinitionid);
    }else{
      if(this._userselectedItems.length ==0){
        this.userwiseprologlst = [];
      }
    }
  
  }

  getuserwiseproductionreport(prodefid){
    this.SpinnerService.show();
    let input = [];
    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();
    }
  });
  input.push({p_projectdefinitionid:prodefid,
    p_startdate:this.startdate,
    p_enddate:this.enddate,
    multipleprojectid_p:multiple_prodefid ,
    p_isarchive:this.isarchive,
    isnormaluser:this.isnormaluser,
    p_userid:this.userid
  });

    this.userwiseproductionlogreportservice.Getuserwiseproductionlogreport(input[0]).subscribe(res=>{
      this.SpinnerService.hide();
      if(res.body != null && res.body != undefined){
        let resarr=[];
          resarr=res.body;
          this.Originallst=[];
          resarr.forEach(val => {   
            this.Originallst.push(JSON.parse(val));
          });
        this.userwiseprologlst = this.Originallst; 
        let index =0;
       /*    this.userwiseprologlst.forEach(element => {
            if(index != this.userwiseprologlst.length){
              index = index +1;
              element.SNo = index;
            }
          }, err => { 
            this.SpinnerService.hide();
            this.toastr.error(err); }); */
            this.generateColumns(this.userwiseprologlst);
        console.log('userwiseproductionreport',this.userwiseprologlst)
      }
    });
  }
  generateColumns(data: any[]) {
    if (data.length > 0) {
      const sampleData = data[0];
      this.columns = Object.keys(sampleData).map(key => {
        let columnConfig: any = { dataField: key, caption: key,
          visible: this.shouldColumnBeVisible(key)  };
        //this.formatCaption(key)
        // If the field is a date, add date formatting
        if (this.isDateField(key)) {
          columnConfig.dataType = 'date';
          columnConfig.format = 'dd-MMM-yyyy';
          //columnConfig.filterOperations = ['=', '<>', '<', '>', '<=', '>='];
        }

        return columnConfig;
      });
    }
  }
  formatCaption(key: string): string {
    // Check if the key is all uppercase
 if (key === key.toUpperCase()) {
   return key;
 }
// Handle specific cases
/*  if (key === 'ProjectID' ) {
 return 'Project ID';
 }
 if (key === 'EmpID') {
  return 'Emp ID';
  }
 if (key === 'SNo') {
   return 'SNo';
   } */
 // Format the key into a more human-readable caption
 return key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());
 }
 isDateField(key: string): boolean {
   // Add logic to identify if a field is a date field, e.g., by checking key names
   const dateFieldNames = ['Creation Date', 'FollowUpDate', 'Completion Date','Start Date','End Date','Bid Date','Pre-Bid Date','Follow Up Date']; // Add more as needed
   return dateFieldNames.includes(key);
 }
 shouldColumnBeVisible(key: string): boolean {
   //const columnsToHide = ['JobTitle'];
   const columnsToHide = [''];
   return !columnsToHide.includes(key);
 }
  selectarchivejob(evt){
    if(evt.target.checked==true){
      this.isarchive=0;
    }else{
      this.isarchive=1;
    }
    if(this.projectdefinitionid!=0 && this.startdate !=null && this.startdate !=undefined &&
      this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined){
        this.getuserwiseproductionreport(this.projectdefinitionid);
    }
    } 
  loadjob(prodefid){
    const input=[];
    input.push({
      p_projectdefinitionid: prodefid,
      p_startdate:this.startdate,
      p_enddate: this.enddate
    });

    this.processwiseproductionreport.GetJobTitle(input[0]).subscribe(res=>{
      debugger;
      if(res.body!=null && res.body != undefined){
        this.joblst= [];
        this.joblst = JSON.parse(res.body);
      //  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;    
      }
    });
  }


  onExporting(e) {
    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet('Userwise Log 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 == "StartDate" || gridCell.column.dataField == "EndDate" ) &&  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' }), 'UserwiseLogReport'+datetime+'.xlsx');
      });
    });
    e.cancel = true;
  }

  applyFilter(item) {
  debugger;
console.log('select time',this._timeselectedItems);
this.filterValue = [
  item.value[0],item.value[1],item.value[2]
];
  }
}
