import { Component, OnInit } from '@angular/core';
import * as moment from 'moment';
import { PageapiService } from '../pageapi.service';
import { Router } from '@angular/router';
import * as html2pdf from 'html2pdf.js'
import { NbDialogService, NbToastrService, NbWindowControlButtonsConfig, NbWindowRef, NbWindowService } from '@nebular/theme';
import { SummaryDetailsComponent } from './summary-details/summary-details.component';
@Component({
  selector: 'ngx-summary-list',
  templateUrl: './summary-list.component.html',
  styleUrls: ['./summary-list.component.scss']
})
export class SummaryListComponent implements OnInit {
  dDate: string | null = this.reduceDate(localStorage.getItem('dDate'));
  dId: string | null = localStorage.getItem('dId');
  ranges: any = {
    'Today': [moment(), moment()],
    // 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
    // 'Last 7 Days': [moment().subtract(6, 'days'), moment()],
    // 'Last 30 Days': [moment().subtract(29, 'days'), moment()],
    // 'This Month': [moment().startOf('month'), moment().endOf('month')],
    // 'Last Month': [
    //   moment().subtract(1, 'month').startOf('month'),
    //   moment().subtract(1, 'month').endOf('month')
    // ]
  };selectDate:any =[];driverId:any =[];DateDisplay:any =[];driverName:any =[];
  selectedDateRange:any =[];drivers:any =[];summaryaData:any=[];driverval:any=[];returnSummary:any =[];

  minimize = false;
  maximize = false;
  fullScreen = true;
  close = true;
  constructor(public _api:PageapiService, private router:Router,private windowService: NbWindowService,) {
    if(localStorage.getItem('dDate'))
    {
       this.dDate = this.reduceDate(localStorage.getItem('dDate'));
       this.dId = localStorage.getItem('dId');
    }
   }

  ngOnInit(): void {
    this.selectedDateRange =[];
    console.log(moment()['_d'])
   
    this.getDriverlistApi()
  }

reduceDate(date){
// Create a Date object from the input date string
const inputDate = new Date(date);

// Subtract one day (24 hours) from the input date
const newDate = new Date(inputDate.getTime() - 24 * 60 * 60 * 1000);

// Format the new date as a string
const formattedDate = newDate.toString();
  
  return formattedDate;
}


  back(){

  }
  save(){

  }

  generatePDF(data){


  }
  dateWiseFilter(){
    console.log(this.selectedDateRange,this.driverval)
    if(this.selectedDateRange.length!=0){


   
  }
    //this.getDriverSummaryAdminList(result)

  }

  mergeOrders(orderItems: any[]) {
    this.summaryaData = orderItems.reduce((acc, curr) => {
      const existingOrder = acc.find((order) => order.orderId === curr.orderId);
      if (existingOrder) {
        existingOrder.total_qty += curr.total_qty;
      } else {
        acc.push(curr);
      }
      return acc;
    }, []);
  }
  getDriverlistApi(){
   // console.log(this.selectedDateRange)
    let param ={}
    this._api.getusers(param).subscribe(res => {
      console.log(res)
      if(res.status == 200){
  
       let passData =  res.data
       let driver = passData.filter(arr=>{return arr.role == 'DRIVER'}) 
       driver.sort((a: any, b: any) => {
        return b.id - a.id;
      });
       driver.forEach((element:any, index) => {
        element.index = index       +1  
        
      });
  
  
  
      this.drivers = driver
      //  console.log(data)
      
      }
    })
  }


  getDriverSummaryAdminList(date){
    let param ={date:new Date(date)}
    this._api.getDriverSummaryAdminList(param).subscribe(res => {
      console.log(res)
      if(res.status == 200){
   
      console.log(res.data)
      
      }
    })
  }

  val(data){
    console.log(data.id)
    this.driverName = data.userName
    let result;
    if(this.selectedDateRange.length != 0){
      result=   this.selectedDateRange.endDate['$d']
    }else{
      
      result =  moment()['_d']
    }
    this. driverId = data.id
   
    
  }


  returnCount(data){
   let result =  this.returnSummary.filter(arr=>{return arr.orderId == data}) 
console.log(result)
   if(result.length>0){

    return result[0].total_amount
   }else{
    return '-'
   }

  }

  // view(data,name){
  //   localStorage.setItem('cusName',name)
  //   this.router.navigate(['/pages/summary/'+data]) 
  // }


  onStartDateChanged(data){
    this.DateDisplay = data
    this.selectDate =[];
    this.selectDate.push(data)
    //this.selectDate = data
    console.log(data)

  
  }
  generate(){

    const utcDate = new Date(this.selectDate[0]);

    // Add one day to the UTC date
    utcDate.setDate(utcDate.getDate() + 1);
    
    // Convert the updated date to a UTC string
    const updatedUtcDate = utcDate.toISOString();
    console.log(updatedUtcDate)
    localStorage.setItem('dDate' , updatedUtcDate);
    localStorage.setItem('dId' , this.driverId);
    let param ={date:new Date( updatedUtcDate),id:this.driverId}
    this._api.getDriverSummaryAdminList(param).subscribe(res => {
      console.log(res)
      if(res.status == 200){
   
      console.log(res.data)

      this.summaryaData = res.data
      if(  this.summaryaData.length>0){
        this.summaryaData.forEach(element => {
          element.name = element['UserDetails.userName']
          
        });
      }
    

     this.mergeOrders(  this.summaryaData)
      
      }else{
        this.summaryaData =[];
      }
    })

    this._api.getReturnDriverSummaryListadmin(param).subscribe(res => {
      console.log(res)
      if(res.status == 200){
   
      console.log(res.data)

      this.returnSummary = res.data

    

     // this.mergeOrders(  this.summaryaData)
      
      }else{
        this.returnSummary =[];
      }
    })


  }

  

   view(param,name){

    const buttonsConfig: NbWindowControlButtonsConfig = {
      minimize: this.minimize,
      maximize: this.maximize,
      fullScreen: this.fullScreen,
      close: this.close,
    };
    let config= {
      hasBackdrop: true,
      width: '500px',
      height: '300px',
    }

    console.log(param,name)
     localStorage.setItem('cusName',name)
    let data:any = {orderID:param,title:'Summary Product List'}
    // let passData = {name:this.selectCustomer,product:results,customerData:this.selectCustomerData}

    const windowRef: NbWindowRef =  this.windowService.open(SummaryDetailsComponent, 
      {
      title: `Summary Product List`,  
      context:data,buttons: buttonsConfig , 
    });
   


      // Subscribe to the afterClosed event
      windowRef.onClose.subscribe((data) => {
      })
    // const dialogRef = this.dialogService.open(SummaryDetailsComponent, {
    //   hasBackdrop: true,
    //   dialogClass: 'custom-dialog-class', // Add your custom CSS class here
    //   context: data
    // });

    // dialogRef.onClose.subscribe((result) => {
    //   // Execute custom logic when the dialog is closed
    //  console.log(result);       
    // //  if(result == 1){
    // //    this.getBranchDetails()
    // //    this.toastrService.success('Branch Added Successfully','Branch');
    // //     console.log('Window closed 123');
    // //  }else if(result == 0){
    // //    this.toastrService.success('Somthing is Wrong...!', 'Add Branch Failed..!');
    // //  }
    // });
     
  }

  download(){
   console.log(this.driverName,this.selectDate[0]) 
    // Create a new date object using the selectDate value
    const selectedDate = new Date(this.selectDate[0]);

    // Get the year, month, and day components
    const year = selectedDate.getFullYear();
    const month = String(selectedDate.getMonth() + 1).padStart(2, '0'); // Add leading zero if needed
    const day = String(selectedDate.getDate()).padStart(2, '0'); // Add leading zero if needed

    // Format the components as "yyyy-mm-dd"
    const formattedDate = `${day}-${month}-${year}`;
    console.log(formattedDate);
     var element = document.getElementById('table');
    var opt = {
      margin:       1,
      filename:     'Delivery_Summary_'+formattedDate+'_'+this.driverName,
      image:        { type: 'jpg', quality: 0.98 },
      html2canvas:  { scale: 2 },
      jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
    };
    
// New Promise-based usage:
html2pdf().from(element).set(opt).save();
  }

}
