

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 { NgxSpinnerService } from 'ngx-spinner';
import{JobcreationreportService} from './jobcreationreport.service';
@Component({
  selector: 'app-jobcreationreport',
  templateUrl: './jobcreationreport.component.html',
  styleUrls: ['./jobcreationreport.component.css']
})
export class JobcreationreportComponent implements OnInit {
   //customers: Customer[];
   jobstatusreport_list:any=[];
  _ddlProjecttypeSettings: {};
  jobProductTypeList: any[];
   original_jpList: any[];					 
  userid: string = localStorage.getItem('userid');
  _userselectedItems: any[] = [];
  metaall: any[] = [];
  startdate:any;
  enddate:any;
  projectdefinitionid:number;
  SNOHeaderFilter: any;
  isarchive=1;
  columns: any[] = [];
  jobcreationreportService: any;
  constructor( private datepipe :DatePipe,
    private jobmasterservice: JobmasterService,
    private JobcreationreportService: JobcreationreportService,
    private toastr: ToastrService,
    private dashboardservice: DashboardService,
    private SpinnerService: NgxSpinnerService
    ) { }

  ngOnInit(): void {   
    this.loadProductType();
  }
  loadProductType() {
    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 )
                this._userselectedItems=this.jobProductTypeList.filter(x=>x.projectdefinitionid == this.jobProductTypeList[0].projectdefinitionid);
               this.projectdefinitionid=this.jobProductTypeList[0].projectdefinitionid;
            }
        }
    }
    );
}
onItemSelect(item: any) {
  if(this._userselectedItems.length !=0 && this.startdate !=null && this.startdate !=undefined &&
      this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined ){
 this.getjobstatusreport(this.projectdefinitionid);
     
  }

}
onDeSelectAll(item:any){
this.jobstatusreport_list = [];
}
onSelectAll(item:any){
  if(this._userselectedItems.length !=0 && this.startdate !=null && this.startdate !=undefined &&
    this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined ){
      this._userselectedItems = item;
      this.getjobstatusreport(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.getjobstatusreport(this.projectdefinitionid);
  }else{
    if(this._userselectedItems.length ==0){
      this.jobstatusreport_list = [];
    }
  }

}
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._userselectedItems.length!=0 && this.startdate !=null && this.startdate !=undefined &&
      this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined ){
     this.getjobstatusreport(this.projectdefinitionid);
    }
  } 


getlotmetadata(pdid){
  debugger
  let input = [];
  input.push({pwdid:pdid });
  this.dashboardservice.getlotmeta(input[0]).subscribe(res=> {
    debugger;
    if (res.body !== undefined && res.body !== null) {
      debugger;
      this.metaall= res.body;
      this.getjobstatusreport(pdid);
      //console.log(this.metaall);
      }
  }, err => { this.toastr.error(err); });
}
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.getjobstatusreport(this.projectdefinitionid);
  }
  } 
getjobstatusreport(pdid){
  debugger;
  this.SpinnerService.show();
  const input = [];
  let  multiple_prodefid :string = "";
  this._userselectedItems.forEach(element => {
    if(multiple_prodefid == ""){
      multiple_prodefid = element.projectdefinitionid.toString();
    }else{
      multiple_prodefid =multiple_prodefid + ','+element.projectdefinitionid.toString();
    }
  });
  input.push({p_projectdefinitionid:pdid,
    p_startdate:this.startdate,
    p_enddate:this.enddate,
    multipleprojectid_p:multiple_prodefid,
    p_isarchive:this.isarchive});
  this.JobcreationreportService.getjobstatusreport(input[0]).subscribe(res => {
  this.SpinnerService.hide();
      let resarr=[];
      resarr=res.body;
      this.jobstatusreport_list=[];
    this.original_jpList=[];
      resarr.forEach(val => {   
      // this.jobstatusreport_list.push(JSON.parse(val));
           this.original_jpList.push(JSON.parse(val));
      });
         this.original_jpList.forEach(element => {
          console.log(element)
            if( element['Lot Status']!=null &&  element['Lot Status']!= undefined &&  element['Lot Status']!= ''){ 
              if( element['Lot Status'].includes('Assigned to vendor')){
                element['Lot Status']= 'Assigned to vendor';
            } 
          }
            this.jobstatusreport_list.push(element);										
          });	
          this.generateColumns(this.jobstatusreport_list);
      }, err => { 
        this.SpinnerService.hide();
        this.toastr.error(err); });

}
  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)  };

        // 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 === '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);
  }
onExporting(e) {
  debugger;
  console.log(e.component)
      const workbook = new Workbook();
      const worksheet = workbook.addWorksheet('Job Status 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 == "CreationDate" || gridCell.column.dataField == "CompletionDate" || gridCell.column.dataField == "FollowUpDate") &&  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' }), 'Job_Status_Report_'+datetime+'.xlsx');
        });
      });
      e.cancel = true;
    }
}
