import { Component, OnInit } from '@angular/core';
import { MdDialog } from '@angular/material';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { ContactService } from '../../../contact.service';
import { ReportService } from '../../report.service';
// declare function show
declare var google: any;
declare var jsPDF : any;
declare var $: any;
const PDF_EXTENSION = ".pdf";
declare var moment:any;
declare var html2canvas:any
declare var Chart :any;
@Component({
  selector: 'app-performance-report',
  templateUrl: './performance-report.component.html',
  styleUrls: ['./performance-report.component.scss']
})
export class PerformanceReportComponent implements OnInit {
identifier : any = 'stoppage_report';
  address: any;
  // overSpeedobject:any;
  fs : any;
  ls : any;
  emailid : 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;
  before:any;
  superAdmin:Boolean = false;
  dataStoppage: any[];
  stoppage_obj: any;
  duration:any;
  
  stoppage_duration: any;
  finalArr: any;
  supAdmin: any;
  logo1: string;
  private finalise = new Subject<void>();
  constructor(private contactService: ContactService,private _service:ReportService,private router: Router,public dialog: MdDialog) {
 this._service.invokeEventForPerformanceReport.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
        if(value){
         this.getReport(value); 
       }
      });
   }
ngOnDestroy(){
   
    this.finalise.next(void 0);
  }
  ngOnInit() {

    // var fTime = new Date().setHours(0,0,0);
    // this.Fromdate = new Date(fTime);
    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;
    this.supAdmin=JSON.parse(window.atob(window.localStorage.token.split('.')[1])).supAdmin;
    console.log("TOKEN=>",JSON.parse(window.atob(window.localStorage.token.split('.')[1])));
    

    this.contactService.get('/users/shareProfileImage?uid='+this.supAdmin).subscribe((res:any)=>{
      console.log(res);
      
    if(res.imageDoc.length != 0){
        var str =  res.imageDoc[0]
        var splitStr = str.split('/');
        var concatStr ='';
       for(var i=1 ; i< splitStr.length ; i++){      
         if(i > 0){ 
          var tt = splitStr[i];   
          concatStr += '/'+tt ; 
         }
       }
       this.logo1='https://www.oneqlik.in' + concatStr
       console.log("IMAGE==>",this.logo1);
      
      }
      
    })
      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.testTable()
    // this.tabelObj;
       
  }

 


  stoppage_data=[];
  arrival_time:any;
  departure_time:any;
  report_to_show =[];
  Durations:any;
  address_show:any;

addressLink = "";

  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>";
          // console.log('tab_text',JSON.parse(tab_text));
          //tab_text=tab_text+"</tr>";
      }
  
      tab_text=tab_text+"</table>";
      // tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
      // tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your 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);
  }
  
  tabelObj :  any;

testTable() {
  const that = this;
 
  console.log("inside function");
  $(document).ready(function() {
     that.tabelObj = $('#deviceTable').DataTable({
      // dom: 'Bfrtip',
      // buttons: [
      //     'copy', 'csv', 'excel', 'pdf', 'print'
      // ]  ,
          "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) => {
            console.log('temptemptemptemptemp',dataTablesParameters);
              var deviceID;
              that.Load= true;    
             

          var tempfd = new Date().setHours(0,0,0,0);
          var tf =moment(tempfd).subtract(1, "days") ;
          var temptd = new Date();
          
         
            var from_date = that.Fromdate?that.Fromdate:tf.toISOString();
            var to_date = that.todate?that.todate:temptd.toISOString();
            var user = that.useridd;
            var temp = {
            from_date : from_date,
            to_date : to_date,
            user : user
            }
            var suburl = "";
            suburl += "/summary/summary?from=" + temp.from_date +'&to=' + temp.to_date + '&user=' + temp.user;
            // that.finalArr=[]
            console.log(this.deviceArr);
            if(that.deviceArr.length != 0){  
              suburl +='&device='+that.deviceArr;
            }else{
            
              let resp =[];
             

              callback({data : resp });
            }
            if(temp.from_date && temp.to_date){
              that.dataForKMDriven=[]
              that.vehicleName=[];
               that.maxSpeedData=[]
               that.dataForHourDriven=[];
               that.clourArray=[]
            that.contactService.get(suburl).subscribe((resp:any) => {   
                // console.log(ignReport.length);   
                that.Load= false;   
                 for(var i=0;i<resp.length;i++){
                that.dataForKMDriven.push(resp[i].total_odo?(Number(resp[i].total_odo)/1000).toFixed(2):'')
                that.vehicleName.push(resp[i].devObj[0].Device_Name?resp[i].devObj[0].Device_Name:'')
                that.maxSpeedData.push((resp[i].today_maxSpeed?Number(resp[i].today_maxSpeed):0))
                  that.dataForHourDriven.push(Number(that.millisecondConversion1(parseInt(resp[i].today_running))))
                that.clourArray.push(that.getRandomColor())
              if(i==(resp.length-1)){
                 that.dataToPlot()
                console.log(that.dataForHourDriven);
                
                }
              }

                that.finalArr=resp 
                console.log('respresp=>',resp);      
                callback({data : resp });
            }, err => {   
              that.Load= false;    
              console.log("error",err) ;     
            });
          }else{
            that.Load= false;       
                callback({data : [] });
          }
        },  
      
          "columns": [
              {
                  "data": "devObj",
                  "render": function(data, type, row) {
                      
                    return data[0].Device_Name?data[0].Device_Name:'';                     
                  }
              },
              {
                  "data": "total_odo",
                  render: function(data, type, row) {
                    return data?(Number(data)/1000).toFixed(2):'';        
                  }
              },
              {
                  "data": "total_odo",
                  render: function(data, type, row) {
                    if(that.days>0){
                      return row.total_odo?(Number(row.total_odo)/(1000*that.days)).toFixed(2):'';           

                    }else{
                      return row.total_odo?(Number(row.total_odo)/(1000)).toFixed(2):''; 
                    }
                  }
              },   
            
          {
            "data": "today_running",
            render: function(data, type, row) { 
            
             var ign_on:any;
                  if(data != undefined){
                   ign_on =  that.millisecondConversion(parseInt(data));
                  }else{
                    ign_on = '0:0'
                  }
                    return ign_on;  
            }
          },
          {
            "data": "today_stopped",
            render: function(data, type, row) { 
            
             var ign_on:any;
                  if(data != undefined){
                   ign_on =  that.millisecondConversion(parseInt(data));
                  }else{
                    ign_on = '0:0'
                  }
                    return ign_on;  
            }
          },
          
          {
            "data": "t_idling",
            render: function(data, type, row) { 
              var ign_on:any;
                  if(data != undefined){
                   ign_on =  that.millisecondConversion(parseInt(data));
                  }else{
                    ign_on = '0:0'
                  }
                    return ign_on; 
            }
          },
            {
            "data": "today_maxSpeed",
            render: function(data, type, row) { 
            
                    return data?data:'';  
            }
          }, 
          {
            "data": "today_routeViolations",
            render: function(data, type, row) { 
            
                    return data?data:0;  
            }
          },                       
          ],  
          "columnDefs": [
            { className: "dt-body-left", "targets": [ 0,1,2,3,4,5,6,7 ] },
            {
              "targets": '_all',
              "createdCell": function (td, cellData, rowData, row, col) {
                  $(td).css('padding', '18px')
              }
          },
          // { "width": "20%", "targets": 0 },
          // { "width": "10%", "targets": 1 },
          // { "width": "20%", "targets": 2 },
          // { "width": "30%", "targets": 3 },  
          // { "width": "20%", "targets": 4 },      
         
          ] 
      });

  });

}
clourArray=[]
  getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
  millisecondConversion(duration){
 
var x = duration;
var d = moment.duration(x, 'milliseconds');
var hours = Math.floor(d.asHours());
var mins = Math.floor(d.asMinutes()) - hours * 60;
return  hours + ":" + mins;
  
}
  millisecondConversion1(duration){
 
var x = duration;
var d = moment.duration(x, 'milliseconds');
var hours = Math.floor(d.asHours());
var mins = Math.floor(d.asMinutes()) - hours * 60;
return  hours+'.'+mins;
  
}
  deviceArr=[];
  data_descip = '';
  days=1
  getReport(event){
    console.log(event);
    if (event == 'getExcel') {
      this.exportExcel();
    } else if(event=='getPdf')
  {
    this.expotToPdf();
  }else{
      var deviceId: any;
      var tpdata = event ; 
      var that = this;
      var fd = new Date(tpdata.fromDate);
      var td  = new Date(tpdata.toDate);
      var a = moment(fd);
var b = moment(td);
this.days=b.diff(a, 'days');
console.log(this.days);
if(this.days<0){
  this.days=1;
} // 1
console.log(this.days);

        deviceId= event.deviceArr;
      
      this.deviceArr = deviceId; 
    
      this.Fromdate = fd.toISOString();
      this.todate = td.toISOString();
     
        this.tabelObj.ajax.reload(); 
        
    
    }


    function launch_toast() {
      // console.log(divid);
       var x = document.getElementById("toast")
       //console.log(x);
       x.className = "show";
       setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1500);
   }    
   
  }

  durationFilter(data){
    var temp=[];
    var diff
    console.log(data,this.stoppage_duration[0]);
     if(this.stoppage_duration[0]==0){
        temp=data
       }else{
    if(data.length!=0){
    for(var i=0;i<data.length;i++){
      diff=this.dateDiffrence(data[i].arrival_time,data[i].departure_time);
     if((this.stoppage_duration != undefined )&&(this.stoppage_duration.length != 0 )){
      
       if(this.stoppage_duration[0]==1){
            if(diff.hrs<=2){
              if(diff.hrs==2){
                if(diff.min>0){

                }else{
                  temp.push(data[i]);
                }
              }else
                temp.push(data[i]);
            }
       }else{
          if(diff.hrs>=this.stoppage_duration[0]){
         temp.push(data[i]);
       }

       }
      
      }
    }
  }
}
      return temp;
  }
  dateDiffrence(date1,date2){
                  let arrival_time = new Date(date1).toLocaleString();                 
                  let departure_time = new Date(date2).toLocaleString();
                  var fd = new Date(arrival_time ).getTime();
                  var td = new Date(departure_time).getTime();
                  var time_difference = td-fd;
                  var total_min = time_difference/60000;
                  var hours = total_min/60
                  var rhours = Math.floor(hours);
                  var minutes = (hours - rhours) * 60;
                  var rminutes = Math.round(minutes);
                  let Durations = rhours;
                  return {hrs:Durations,min:rminutes};
  }

  reportPeriod;
  totalHours
  avgDistTraveled
  reportDate=moment(new Date()).format('lll');
  totalDistanceTraveled=0
 expotToPdf(){
    console.log(this.stoppage_data);

    this.downloadPdf()
    
  }
  downloadPdf(){
    var totalHours=0
    this.totalHours;
    this.totalDistanceTraveled=0
    for(var i=0;i<this.finalArr.length;i++){
      this.totalDistanceTraveled=this.totalDistanceTraveled+this.finalArr[i].total_odo
      totalHours=this.totalDistanceTraveled+this.finalArr[i].today_running
    if(i==this.finalArr.length-1){
      this.totalDistanceTraveled=this.totalDistanceTraveled/1000;
      this.totalHours=this.millisecondConversion(totalHours)
      if(this.days>0){
        this.avgDistTraveled=this.totalDistanceTraveled/this.days
      }else{
         this.avgDistTraveled=this.totalDistanceTraveled
      }
    }
    }

 var image=localStorage.getItem('profilePic')
 this.reportPeriod= moment(this.Fromdate).format('lll')+' to '+  moment(this.todate).format('lll')    
console.log(image);

  var outerThis=this;

 var element = $('#cartForKMDriven');
        var pdfOptions = {
            orientation: "landscape", // One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
            unit: "mm",              //Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"
            format: "legal"            //One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'
        };

        var doc = new jsPDF(pdfOptions);

        var pageWidth = doc.internal.pageSize.width-20;
        var width  =  pageWidth;

        html2canvas(element, {
            useCORS: true, // MUST
            onrendered: function(canvas) {
                var imgWidth = element.width();
                var imgHeight = element.height();

                var height =  (pageWidth * imgHeight)/ imgWidth
                var imgData = canvas.toDataURL('image/png');

                 var element1 = $('#cartForHoursDriven');
                  var pdfOptions = {
                      orientation: "landscape", // One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
                      unit: "mm",              //Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"
                      format: "legal"            //One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'
                  };
                  html2canvas(element1, {
            useCORS: true, // MUST
            onrendered: function(canvas) {
              
               var element2 = $('#cartForMaxSpeed');
                  var pdfOptions = {
                      orientation: "landscape", // One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
                      unit: "mm",              //Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"
                      format: "legal"            //One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'
                  };
                  html2canvas(element2, {
            useCORS: true, // MUST
            onrendered: function(canvas1) {
              doc.setFontSize(22);
              doc.text(151, 9, "Performance Report");
              doc.autoTable({html:"#headerTable",margin:{bottom:140,left:35,right:8,top:9},theme:'plain'});
                var imgWidth2 = element2.width();
                var imgHeight2 = element2.height();

                var imgWidth1 = element1.width();
                var imgHeight1 = element1.height();

                var height1 =  (pageWidth * imgHeight1)/ imgWidth1
                var imgData1 = canvas.toDataURL('image/png');

                 var height2 =  (pageWidth * imgHeight1)/ imgWidth1
                var imgData2 = canvas1.toDataURL('image/png');
                outerThis.toDataURL(outerThis.logo1, function (dataUrl) {
                  if(outerThis.logo1)
                  doc.addImage(dataUrl, 'JPEG', 2, 2, 27, 27);
                  doc.addImage(imgData, 'PNG', 5, 30 , width, height-30);
                  doc.addPage();
                  doc.addImage(imgData1, 'PNG', 5, 30 , width, height1-30);
                  doc.addPage();
                  doc.addImage(imgData2, 'PNG', 5, 30 , width, height2-30);
                   
                 doc.autoTable({
                     head: outerThis.headRows(),
                     // margin: { top: 80 },
                     startY: doc.autoTable.previous.finalY + 200,
                     body: outerThis.bodyRows(outerThis.finalArr.length, outerThis.finalArr),
                     // beforePageContent: header,
                 });
                  
                 
                doc.save(name);
              
              })
              }
            })
            }
          })

              
            }
        });


                }
              

   toDataURL(url, callback) {
     console.log(url);
     
        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();
    }


    headRows() {

    return [
 

      {
        deviceName:'device Name',
        total_odo:'Total Dist.',
        avg_odo:'Avg Dist.',
        today_running:'Driven Hours',
        today_stopped:'Stationary Hours',
        t_idling:'Excess Idle',
        today_maxSpeed:'Max Speed',
        today_routeViolations:'Speed Violation',
      
      }
    ];
  }

  bodyRows(rowCount, pdfBody) {
    rowCount = rowCount || 10;
    let body = [];
 
    for (var j = 0; j < rowCount; j++) {
      var avg
      if(this.days>0){
                      avg= pdfBody[j].total_odo?(Number(pdfBody[j].total_odo)/(1000*this.days)).toFixed(2):'';           

                    }else{
                      avg= pdfBody[j].total_odo?(Number(pdfBody[j].total_odo)/(1000)).toFixed(2):''; 
                    }
      body.push({
        deviceName:pdfBody[j].devObj[0].Device_Name,
        total_odo:pdfBody[j].total_odo/1000,
        avg_odo:avg,
       today_running:this.millisecondConversion(pdfBody[j].today_running),
       today_stopped:this.millisecondConversion(pdfBody[j].today_stopped),
        t_idling:this.millisecondConversion(pdfBody[j].t_idling),
        today_maxSpeed:pdfBody[j].today_maxSpeed,
         today_routeViolations:pdfBody[j].today_routeViolations?pdfBody[j].today_routeViolations:0,
      });
    }
    return body;
  }
   durationFun(row) {    
                  let arrival_time = new Date(row.arrival_time).toLocaleString();                 
                  let departure_time = new Date(row.departure_time).toLocaleString();
                  var fd = new Date(arrival_time ).getTime();
                  var td = new Date(departure_time).getTime();
                  var time_difference = td-fd;
                  var total_min = time_difference/60000;
                  var hours = total_min/60
                  var rhours = Math.floor(hours);
                  var minutes = (hours - rhours) * 60;
                  var rminutes = Math.round(minutes);
                
                  let Durations = rhours +" "+'hrs'+  " "+ rminutes + 'min'; 
                  
                  return Durations;
                 
                }


    cartForKMDriven:any;
     cartForMaxSpeed:any;
    cartForHoursDriven:any;
    vehicleName=[]
    dataForKMDriven=[];
    dataForHourDriven=[];
    maxSpeedData=[]
    InsertionTime
  dataToPlot(){
  console.log("IN CHART");
  
    if(this.cartForKMDriven != undefined){
      this.cartForKMDriven.destroy();
    }
     if(this.cartForHoursDriven != undefined){
      this.cartForHoursDriven.destroy();
    }
     if(this.cartForMaxSpeed != undefined){
      this.cartForMaxSpeed.destroy();
    }
    this.vehicleName
    this.dataForKMDriven
    this.InsertionTime
  
    var that = this;
    var canvas = <HTMLCanvasElement> document.getElementById("cartForKMDriven");
    var ctx = canvas.getContext("2d");

     this.cartForKMDriven = new Chart(ctx, {
      type: 'bar',
      data: {
         labels: this.vehicleName,
  datasets: [{
    label: 'Kilometer Driven Comparison',
    data: this.dataForKMDriven,
   backgroundColor:this.clourArray,
    borderWidth: 1
  }]
      },
      options: {
         scaleShowValues: true,
        responsive: true,
        maintainAspectRatio: false,
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero: true
                  }
              }],
              xAxes: [{
      ticks: {
        autoSkip: false
      }
    }]
          }
      }
  });


  var canvas1 = <HTMLCanvasElement> document.getElementById("cartForHoursDriven");
    var ctx = canvas1.getContext("2d");

     this.cartForKMDriven = new Chart(ctx, {
      type: 'bar',
      data: {
         labels: this.vehicleName,
  datasets: [{
    label: 'Graphical View of Driven Hours',
    data: this.dataForHourDriven,
     backgroundColor:this.clourArray,
    borderWidth: 1
  }]
      },
      options: {
          scaleShowValues: true,
        responsive: true,
        maintainAspectRatio: false,
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero: true
                  }
              }],
              xAxes: [{
      ticks: {
        autoSkip: false
      }
    }]
          }
      }
  });


  var canvas2 = <HTMLCanvasElement> document.getElementById("cartForMaxSpeed");
    var ctx = canvas2.getContext("2d");

     this.cartForMaxSpeed = new Chart(ctx, {
      type: 'line',
      data: {
         labels: this.vehicleName,
  datasets: [{
    label: 'Max Speed',
    data: this.maxSpeedData,
    fill: false,
    borderColor: 'rgb(75, 192, 192)',
    tension: 0.1
  }]
      },
      options: {
          scaleShowValues: true,
        responsive: true,
        maintainAspectRatio: false,
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero: true
                  }
              }],
              xAxes: [{
      ticks: {
        autoSkip: false
      }
    }]
          }
      }
  });


  }

}


