import { Component, OnInit } from '@angular/core';
import { MyaccountComponent } from '../../../myaccount/myaccount.component';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { ContactService } from '../../../contact.service';
import { AcreportInfoComponent } from './acreport-info/acreport-info.component';
import { ReportService } from '../../report.service';
import { environment } from '../../../../environments/environment';

declare var jsPDF : any;
declare var $: any;
const PDF_EXTENSION = ".pdf"
import * as moment from 'moment';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
  selector: 'app-ac-report',
  templateUrl: './ac-report.component.html',
  styleUrls: ['./ac-report.component.scss']
})
export class AcReportsComponent implements OnInit {
ignition_data: any =[];
  fs : any;
  ls : any;
  emailid : any;
  date1 = new Date();
totalWorkingHours=[]
  before:any;
  or : any;
  useridd :any;
  time :any;
  device_data:any;
  devicess:any;
  final:any;
  custtype:any;
  cust:boolean=false;
  Load : Boolean = false;
  date : any;
  devicesss:any;
  mb:any;
  logoutbut:boolean;
  dealer:boolean;
  text:any;
  option:any; 
  finall:any;
  Fromdate:any;
  todate:any;
  options=[];
  logo:any;
  dataForDigital1
  dataForDigital2
  superAdmin:Boolean = false;
  dev_url = environment.hostUrl;
  t:any;
  dataSelect:any;
  errorMsg: any;
  errorDialog: boolean=false;
  searchText:any;
  tabelObj:any; 
  tabelObj1:any; 
  tableFlag: boolean=true;
  identifier : String = "working_report";
  stoppage_data:any;
  arrival_time:any;
  departure_time:any;
  report_to_show =[];
  Durations:any;
  address_show:any;
  start_add_lat:any;
  start_add_long:any;
  uId:any;
  vName:any;
  deviceArr = [];
  data_descip: string;
  digital_input: any;
  private finalise = new Subject<void>();
  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog,private _service:ReportService) {
   this._service.invokeEventForAcReport.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
       
        if(value){
         this.getReport(value); 
       }
       
      
      }); 
   }
   ngOnInit() {
 
    this.t = document.getElementById("download");
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
    this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;

      if(this.custtype == true){
        this.cust = true;
      }  
      if(this.mb.charAt(0)=="n"){
        this.mb = ' '
      }

      if( window.localStorage['Custumer'] == 'ON'){
        this.logoutbut = false
        this.dealer = true
     }
     else{
         this.logoutbut = true
     }
          
     this.logo=window.localStorage['logo'];
     this.text=window.localStorage['text'];
      this.testTable2();
    
     
  }

   testTable2(){
   
  const that = this;
  console.log("inside digital 2");
  $(document).ready(function() {
     that.tabelObj1 = $('#deviceTable').DataTable({
          "processing": true,
          "searching": true, 
          pagingType: 'full_numbers', 
          pageLength: 25,
          serverSide: false,
          "scrollY":'65vh',  
          "scrollCollapse": true,     
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
          ajax: (dataTablesParameters,callback) => {
              var deviceID;
              that.Load = true;
              var from_date = that.Fromdate;
              var to_date =that.todate;
              var user = that.useridd;
              var temp = {
              from_date : from_date,
              to_date : to_date,
              user : user
              }
              console.log(temp);
              
              // https://socket.oneqlik.in/notifs/ACSwitchReport
              
              if((temp.from_date != undefined)&&(temp.to_date != undefined) && that.deviceArr.length!=0){
                var suburl = "";
                suburl += "/notifs/acReport?from_date=" + (temp.from_date).toISOString() +'&to_date=' + (temp.to_date).toISOString() + '&_u=' + temp.user;
                if(that.deviceArr.length != 0){  
                  suburl +='&vname='+that.deviceArr;
                }
                that.contactService.get(suburl).subscribe((resp:any) => {   
                  // console.log(ignReport.length);  
                //  that.rowData=resp
                if(resp.length>0)
                {
                  var j=0
                  for(var i=0;i<resp.length;i++){

                    // that.dataForDigital2=resp[0].s
                      that.calculateACHours(resp[i].s,function(err,succ){
                        if(err){
                          j++;
                          console.log(err);
                        }else{
                          console.log(succ);
                          
                          j++;
                          console.log(j,"==",resp.length);
                          
                          if(j==resp.length){
                            that.Load = false;
                             callback({data : that.reportArray });
                          }
                        }
                      })
                  }

                }else{
                   that.Load = false;
                }
                 
                  
              }, err => {   
                that.Load= false;    
                console.log("error",err) ; 
                var tt = [];  
                callback({data : tt });  
              });
  
              }else{
                 this.Load = false;
               this.data_descip = "Select vehicle" ;  
                 var x = document.getElementById("toast")
                 x.className = "show";
                 setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1500);
                let ta = [];
                that.Load = false;
                callback({data : ta });
              }
                      
        },  
        "rowCallback": function(row: Node, data: any | Object, index: number){  
          $('#getDetail', row).bind('click', () => {         
            console.log("Row Data",data);
                data['fromDate'] = that.Fromdate;
                data['toDate'] = that.todate


            // let dialogRef = that.dialog.open(WorkingHourDetailComponent, {    
            //   width: '548px',
            //   data: { device :data}
            // });
            let dialogRef = that.dialog.open(AcreportInfoComponent, {
                width: '800px',  
                data: {"deviceInfo":data.ign,"digitalInput":that.digital_input}   

               });
          
            dialogRef.afterClosed().subscribe(result => {
              console.log(result);
              if(result == 'close'){
                    console.log(close);
              }
            })  
               
            });
          }, 
      
          "columns": [
              {
                  "data": "deviceName",
                  "visible": true,
                  "render": function(data, type, row) {
                      
                    return data?data : '';                  
                  }
              },
              {
                "data": "Device_ID",
                "visible": true,
                "render": function(data, type, row) {
                    
                  return data?data : '';                  
                }
            },
     
              {
                  "data": "workingHours",
                  "visible": true,
                  render: function(data, type, row) {
                    // var engine_on_time = parseFloat(data) + parseFloat(row['Idle Time']) ;          
                    return data ?data: 0.0; 
                  }
              },
              { 
                "data": "stopHours",
                "visible": true,
                render: function(data, type, row) {
                  return data ? data : 0.0; 
                }
            },
            {
              "data": "_id",
              "visible": true,
              render: function(data, type, row) {
                return '<i id="getDetail" title="Get Detail" style="cursor:pointer;font-size:24px" class="fas fa-info-circle"></i>';        
              }
          }
          ],  

      });
      

  });
}

timeconversion(total_min){
 
  var hours = parseInt(total_min) / 60
  var rhours = Math.floor(hours);
  var minutes = (hours - rhours) * 60;
  var rminutes = Math.round(minutes);

  var Durations = rhours + " " + 'hrs' + " " + rminutes + " " + 'min';
  return Durations ;
}

  

tab:any;
exportExcel()
{

    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    var table = $('#deviceTable').clone();
    table[0].querySelector("thead").remove();
    table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];//document.getElementById('deviceTable'); // id of table

    for(j = 0 ; j < this.tab.rows.length ; j++) 
    {     
        tab_text=tab_text+this.tab.rows[j].innerHTML+"</tr>";
      
    }

    tab_text=tab_text+"</table>";
   
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}
optionVal:any;

getAdd(latitude,longitude){
  var latti =0;
  var longi = 0
  if(latitude != undefined){
    latti = latitude;

  }
  if(longitude != undefined){
    longi = longitude

  }
    return 'https://maps.google.com/?q='+ latti + ',' + longi ; 
}

// callfunction(): void {
//   // this.Load = true;
//   this.tabelObj.draw();
// }

getReport(event){
  console.log("inside function",event);
   if (event == 'getExcel') {
      this.exportExcel();
    } else if(event=='getPdf')
  {
    this.downloadPdf();
  }else{
    this.totalWorkingHours=[]
    this.workingHoursArray=[]
     this.workingHoursArray1=[];
     this.reportArray=[]
    var deviceId: any;
    var tpdata = event ; 
    var that = this;
    var fd = tpdata.fromDate;
    var td  = tpdata.toDate;
    if(event.deviceArr.length==0){
      deviceId=[];
    }else{
      deviceId= event.deviceArr;
    }
    this.deviceArr = deviceId; 
    this.Fromdate = fd
    this.todate = td
    this.tabelObj1.ajax.reload(); 
  }
 
}

workingHoursArray=[]
async newMethod(data){
  console.log("hhhh",data);
  var tempArry=[]
  var stopHr=0;
  var workinHr=0
  var result = await data.reduce(function (r, a) {
        r[a.device.Device_ID] = r[a.device.Device_ID] || [];
        r[a.device.Device_ID].push(a);
        return r;
    }, Object.create(null));
  console.log(result);

  for(var i=0;i<this.deviceArr.length;i++){
    for(var j=0;j<result[this.deviceArr[i]].length;j++){
      console.log("1");
      
      // if(j!==result[this.deviceArr[i]].length){
         console.log("11",result[this.deviceArr[i]][j]);
      if(result[this.deviceArr[i]][j].switch=="OFF"){
         console.log("111",(result[this.deviceArr[i]][j].timestamp).replace('Z', '').replace('T', ''));
         if(result[this.deviceArr[i]][j+1]){
        if((new Date(result[this.deviceArr[i]][j].timestamp).getTime())>(new Date(result[this.deviceArr[i]][j+1].timestamp).getTime())){
          workinHr=(new Date(result[this.deviceArr[i]][j].timestamp).getTime()-new Date(result[this.deviceArr[i]][j+1].timestamp).getTime())/1000;
          stopHr=(new Date(this.todate).getTime()-new Date(this.Fromdate).getTime())/1000;
          
        }
      }
      }
    // }
    }
    tempArry.push({deviceName:result[this.deviceArr[i]][j-1].vehicleName,Device_ID:this.deviceArr[i],stopHours:this.secondsToHms(stopHr),workingHours:this.secondsToHms(workinHr)})
    stopHr=0;
    workinHr=0;
  }
  this.totalWorkingHours=tempArry
  console.log("TEMP==>",tempArry);
  

}
workingHoursArray1=[]
reportArray=[]
// --------------------------------Method For working Hours Calculation-----------------------------
calculateACHours(data,cb){
  console.log("INCOMMING DATA__",data);
  
  var total=0
  console.log(data);
  for(let i=0;i<data.length;i++){
    if(i!==(data.length-1)){
    if(data[0].switch=="OFF"){
    if(data[i].switch=="OFF" && data[i+1].switch=="ON"){
      // console.log("DATE---------->",data[i].timestamp,"==",new Date((data[i].timestamp).replace('Z', '').replace('T', ':')));
      var date=new Date((data[i].timestamp).replace('Z', '').replace('T', ':'));
      var date1=new Date((data[i+1].timestamp).replace('Z', '').replace('T', ':'))
      this.workingHoursArray1.push({deviceName:data[i].vehicleName,timestamp:this.timeDifference(date,date1),Device_ID:this.deviceArr[0]})
      // this.workingHoursArray.push({deviceName:data[i].vehicleName,timestamp:this.timeDifference(new Date(data[i].timestamp),new Date(data[i+1].timestamp)),Device_ID:this.deviceArr[0]})
    }
  }
  else{
    if(data[i].switch=="ON" && data[i+1].switch=="OFF"){
      // console.log("DATE----------1>",data[i].timestamp,"==",new Date((data[i].timestamp).replace('Z', '').replace('T', ':')));
       var date=new Date((data[i].timestamp).replace('Z', '').replace('T', ':'));
      var date1=new Date((data[i+1].timestamp).replace('Z', '').replace('T', ':'))
      this.workingHoursArray1.push({deviceName:data[i].vehicleName,timestamp:this.timeDifference(date,date1),Device_ID:this.deviceArr[0]})
    }
  }
}else{
  for(var j=0;j<this.workingHoursArray1.length;j++){
    total=total+this.workingHoursArray1[j].timestamp;
  }
 var time= Math.abs(this.timeDifference(this.Fromdate,this.todate));
        var stopHrs=this.secondsToHms((time-total))
  this.reportArray.push({Device_ID:data[i].imei,deviceName:data[i].vehicleName,workingHours:this.secondsToHms(total),stopHours:stopHrs,ign:data});
  }
  if(i==data.length-1){
      cb(null,'')
  }

  }
  console.log("JEDHJDH",this.workingHoursArray1,this.reportArray);
  
  

}

// calculateWorkingHours(data){
// console.log(data);
// for(let i=0;i<data.length;i++){
//   if(i!==(data.length-1)){
//   if(data[i].vehicleName==data[i+1].vehicleName){
//     if(data[0].switch=="OFF"){
//     if(data[i].switch=="OFF" && data[i+1].switch=="ON"){
//       // console.log("DATE---------->",data[i].timestamp,"==",new Date((data[i].timestamp).replace('Z', '').replace('T', ':')));
//       var date=new Date((data[i].timestamp).replace('Z', '').replace('T', ':'));
//       var date1=new Date((data[i+1].timestamp).replace('Z', '').replace('T', ':'))
//       this.workingHoursArray.push({deviceName:data[i].vehicleName,timestamp:this.timeDifference(date,date1),Device_ID:data[i].device.Device_ID})
//       // this.workingHoursArray.push({deviceName:data[i].vehicleName,timestamp:this.timeDifference(new Date(data[i].timestamp),new Date(data[i+1].timestamp)),Device_ID:data[i].device.Device_ID})
//     }
//   }
//   else{
//     if(data[i].switch=="ON" && data[i+1].switch=="OFF"){
//       // console.log("DATE----------1>",data[i].timestamp,"==",new Date((data[i].timestamp).replace('Z', '').replace('T', ':')));
//        var date=new Date((data[i].timestamp).replace('Z', '').replace('T', ':'));
//       var date1=new Date((data[i+1].timestamp).replace('Z', '').replace('T', ':'))
//       this.workingHoursArray.push({deviceName:data[i].vehicleName,timestamp:this.timeDifference(date,date1),Device_ID:data[i].device.Device_ID})
//     }
//   }
//   }
// }else{
//   this.finalArrayBuild()
// }
// }
// }

timeDifference(date1,date2) {

  var seconds = (date1.getTime() - date2.getTime()) / 1000;
  return seconds
}

// finalArrayBuild(){
//  var tempSec=0;
//   var result = this.workingHoursArray.reduce(function (r, a) {
//         r[a.Device_ID] = r[a.Device_ID] || [];
//         r[a.Device_ID].push(a);
//         return r;
//     }, Object.create(null));
//     for(var i=0;i<this.deviceArr.length;i++){
//       if(result[this.deviceArr[i]]){
//       for(var j=0;j<result[this.deviceArr[i]].length;j++){
//         tempSec=tempSec+result[this.deviceArr[i]][j].timestamp;
//       }
//     }
//         var time= Math.abs(this.timeDifference(this.Fromdate,this.todate));
//         var stopHrs=this.secondsToHms((time-tempSec))
//         console.log("++++11",stopHrs);
//         if(result[this.deviceArr[i]])
//         this.totalWorkingHours.push({Device_ID:result[this.deviceArr[i]][j-1].Device_ID,deviceName:result[this.deviceArr[i]][j-1].deviceName,workingHours:this.secondsToHms(tempSec),stopHours:stopHrs});
//       // }
      
//       tempSec=0
//     }
//   console.log("sec==>",this.secondsToHms(tempSec),"TOTAL=-",this.totalWorkingHours);

// }

secondsToHms(d) {
    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
    var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
    var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
    return hDisplay + mDisplay + sDisplay; 

}

// downloadPdf(){
//    var doc = new jsPDF("p", "pt", "a2");
//    var header = function(data) {
//                       doc.setFontSize(15);
//                       doc.setTextColor(40);
//                       doc.setFontStyle('normal');
//                       // doc.addImage(dataUrl, 'JPEG', data.settings.margin.left, 20, 30, 30);
//                       doc.text("Ac Report", data.settings.margin.left, 50);
//                     };

//     doc.autoTable({html:"#deviceTable",margin:{bottom:140,left:30,right:8,top:80},theme:'grid',beforePageContent: header},);
//     doc.save("Ac Report");
// }

startAddress;

endAddress;
f_date
t_date
downloadPdf() {
  var outerThis=this
    let fileName =
      "AC Report" +
      new Date()+
      PDF_EXTENSION;
    var pdfsize = "a2";
    var totalPagesExp = "{total_pages_count_string}";
    var doc = new jsPDF("p", "pt", pdfsize);
    outerThis.f_date = moment(this.Fromdate).format('lll'); 
  outerThis.t_date =moment(this.todate).format('lll');

   var pageHeight = doc.internal.pageSize.height || doc.internal.pageSize.getHeight();
var pageWidth = doc.internal.pageSize.width || doc.internal.pageSize.getWidth();
  doc.setFontSize(15);
  doc.text("AC Report", 500, 30);
    doc.setFontStyle("arial");

      var header = function(data) {
    doc.setFontSize(30);
    doc.setTextColor(40);
    doc.setFontStyle('arial');
  
  };

  var options = {
    beforePageContent: header,
    margin: {
      top: 120
    },
    
    startY: doc.autoTableEndPosY() + 20
  };
 var logo=localStorage.getItem('logo1');
 outerThis.toDataURL(logo, function (dataUrl) {
                
    doc.autoTable({
      html:"#deviceTable",
      options,
      styles: {overflow: 'linebreak'},
      theme:'grid',
      didDrawPage: function (data) {
        // Header
        doc.setFontSize(20);
        doc.setTextColor(40);
        doc.setFontStyle('arial');
        // logo=localStorage.getItem('logo1');
          if(logo)
              doc.addImage(dataUrl, 'JPEG', pageWidth-100, 6, 75, 75);
              doc.autoTable({html:"#headerTable",margin:{bottom:140,left:20,right:8,top:40},theme:'plain'});

        // Footer
        var str = "Page " + doc.internal.getNumberOfPages()
        // Total page number plugin only available in jspdf v1.0+
        if (typeof doc.putTotalPages === 'function') {
            str = str + " of " + totalPagesExp;
        }
        doc.setFontSize(10);

        // jsPDF 1.4+ uses getWidth, <1.4 uses .width
        var pageSize = doc.internal.pageSize;
        var pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();
        doc.text(str, data.settings.margin.left, pageHeight - 10);
    },
    
      margin: {top: 85},
     
    });
    if (typeof doc.putTotalPages === 'function') {
      doc.putTotalPages(totalPagesExp);
    }
    doc.save(fileName);
  })
  }

   toDataURL(url, callback) {
   
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            var reader = new FileReader();
            reader.onloadend = function () {
                callback(reader.result);
            }
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.send();
    }
ngOnDestroy(){
   
    this.finalise.next(void 0);
  }

}
