import { Component, OnInit } from '@angular/core';
 
import * as html2pdf from 'html2pdf.js'
import * as moment from 'moment';
import { PageapiService } from '../pageapi.service';
import { Router } from '@angular/router';
@Component({
  selector: 'ngx-return-sheet',
  templateUrl: './return-sheet.component.html',
  styleUrls: ['./return-sheet.component.scss']
})
export class ReturnSheetComponent implements OnInit {

  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')
    // ]

  };productDeatils:any =[];    DateDisplay:any =[];driverName:any =[];  selectDate:any =[]; driverId:any =[];
  selectedDateRange:any =[];drivers:any =[];summaryaData:any=[];driverval:any=[];returnSummary:any =[];
  constructor(public _api:PageapiService, private router:Router) { }

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

  }


  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)
    this.driverName = data.userName

  let result;
    // if(this.selectedDateRange.length != 0){
    //   result=   this.selectedDateRange.endDate['$d']
    // }else{
      
      result =    this.selectDate
   // }
    this.DateDisplay = result
    this.driverId = data.id
    console.log(result)
    // let param ={date:new Date(result),id:data.id}
    // this._api.getDriverSheet(param).subscribe(res => {
    //   console.log(res)
    //   if(res.status == 200){
   
    //   console.log(res.data)

    //   this.summaryaData = res.data
    //   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)
      
    //   }
    // })

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

    //   this.productDeatils = res.data

    

    //  // this.mergeOrders(  this.summaryaData)
      
    //   }
    // })


    
    
  }


  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){
    this.router.navigate(['/pages/summary/'+data]) 
  }


  filterData(param){

    let tmp=[];
  let order =   this.productDeatils.filter(arr=>{return arr.orderId == param}) 
if(order.length>0){

  //console.log(param)


  order.forEach(element => {

    if(element.ProductDetails.length>0){

      tmp.push(element.ProductDetails[0].productName)
    } 

      
    
  });
  //console.log(tmp)
  return tmp
}else{
  return tmp
}


  }


  customer(param){

    let tmp=[];
  let order =   this.productDeatils.filter(arr=>{return arr.orderId == param}) 
if(order.length>0){

  //console.log(param)


  order.forEach(element => {

    if(element.CusDetails.length>0){

      tmp.push(element.CusDetails[0].cusName)
    } 

      
    
  });
  //console.log(tmp)
  return tmp[0]
}else{
  return tmp
}


  }

  filterDataqty(param){

    let tmp=[];
  let order =   this.productDeatils.filter(arr=>{return arr.orderId == param}) 
if(order.length>0){

  console.log(param)


  order.forEach(element => {

    if(element.ProductDetails.length>0){

      tmp.push(element.qty)
    } 

      
    
  });
  //console.log(tmp)
  return tmp
}else{
  return tmp
}


  }

  filterDataNo(param){

    let tmp=[];
  let order =   this.productDeatils.filter(arr=>{return arr.orderId == param}) 
if(order.length>0){

  console.log(param)


  order.forEach(element => {

    if(element.ProductDetails.length>0){

      tmp.push(element.cylinderNo)
    } 

      
    
  });
  //console.log(tmp)
  return tmp
}else{
  return tmp
}


  }
  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:     'Return_Sheet_'+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();
  }

  generate(){

    console.log(this.selectDate)
    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)

    let param ={date: updatedUtcDate,id:this.driverId}
    this._api.getDriverSheet(param).subscribe(res => {
      console.log(res)
      if(res.status == 200){
   
      console.log(res.data)

      this.summaryaData = res.data
      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)
      
      }
    })

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

      this.productDeatils = res.data

    

     // this.mergeOrders(  this.summaryaData)
      
      }
    })

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

  
  }
}
