import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../../contact.service';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { MyaccountComponent } from '../../../myaccount/myaccount.component';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { environment } from '../../../../environments/environment';
declare var google: any;
import * as moment from 'moment';
declare var jsPDF : any;
declare var $: any;
const PDF_EXTENSION = ".pdf"
import { ReportService } from '../../report.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-over-speed',
  templateUrl: './over-speed.component.html',
  styleUrls: ['./over-speed.component.scss']
})
export class OverSpeedComponent implements OnInit {
  fs : any;
  ls : any;
  emailid : any;
  identifier:String = "over_speed";
  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;
  dev_url = environment.hostUrl;
  date1:any;

  dataSelect:any;

  superAdmin:Boolean = false;
  deviceId: any;
  tabelObj: any;
  private finalise = new Subject<void>();
  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog,private _service:ReportService) {
    this._service.invokeEventForoverspeedReport.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.contactService.getDevice(this.emailid,this.useridd).subscribe(

    //   data => {
    //     this.devicesss = data
     
    //     this.finall = (this.devicesss.devices);

    //     for(let i=0;i<this.devicesss.devices.length;i++){

    //       if(this.devicesss.devices[i].type_of_device =="Tracker"){

    //         let a ={
    //           value : this.devicesss.devices[i].Device_Name,
    //           viewValue:this.devicesss.devices[i].Device_Name,
    //           did:this.devicesss.devices[i].Device_ID,
    //           id:this.devicesss.devices[i]._id,
    //           user:this.devicesss.devices[i].user,
    //           email: this.devicesss.devices[i].Email_ID,
    //           deviceType: this.devicesss.devices[i].type_of_device
    //         }
    //         this.options.push(a);
    //       }

    //     }
    //       // console.log(this.options);
    //       let that = this;
    //       setTimeout(()=>{
    //         that.loadropdown();
    //       },100)  
      

    //   });

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


  // loadropdown() {
  //   let that = this;
  //   var script = document.createElement("script");
  //   script.setAttribute("type", "text/javascript");
  //   script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
  //   document.getElementsByTagName("head")[0].appendChild(script);
  //   setTimeout(() => {

  //     $('#select').multipleSelect({
  //       width: 200,
  //       placeholder: 'Select device.....',
  //       filter: true,
  //     })
  //    // $('#select').show();
  //   }, 100);


  // }

//   ign(){
//     this.router.navigateByUrl("device-report/ign-report");
  
//   }

//   ignition_report(){
//     this.cond = false
//     this.router.navigateByUrl("device-report/ignition_report");


//   }

//   notification(){
//     this.cond = false
//     this.router.navigateByUrl("notifications");
//   }


//   ideal(){
//     this.router.navigateByUrl("device-report/ideal-report");
//   }
//   geo(){
//     this.router.navigateByUrl("geofencing");
    
//   }


//   Ddetail(){
//     this.router.navigateByUrl("driverdetail");
//   }
//   DModel(){
//     this.router.navigateByUrl("deviceModel");
//   }
//   VType(){
//     this.router.navigateByUrl("VehicleType");
//   }
//   myaccount(){
   
//     let dialogRef = this.dialog.open(MyaccountComponent, {
//       width: '903px',
//       data: {}
//     });
  
//     dialogRef.afterClosed().subscribe(result => {
  
//       if(result == "succ"){
//         // console.log("Updated")
//       }
  
//     });
//   }
// openNav() {
//   /*  document.getElementById("myNav").style.width = "100%";
// */
//    this.router.navigateByUrl("location");

// }
// logout(){
//   window.localStorage.clear();
//   this.router.navigateByUrl("login");
// }
// devi(){
//   this.router.navigateByUrl("dashboard");

// }
// soon(){
//   this.router.navigateByUrl("const?_i="+window.localStorage.token);
  
// }
// new(){
//   this.router.navigateByUrl("new");
  
// }
// cond:Boolean = false;
// point : any = 0;
//  a(){
//   // console.log(this.point);
//    if(this.point == 0){
//     this.cond = true;
//     this.point ++;
//    }
//  else if(this.point % 2 == 0){
//   this.cond = true;
//   this.point ++;
//  }
//  else{
//    this.cond = false
//    this.point ++;
//  }

  
// }
// addcus(){
//   this.router.navigateByUrl("add");
// }
// report(){
//   this.cond = false
//   this.router.navigateByUrl("device-report");

// }
// report_speed(){
//   // console.log("report speed call")
//   this.cond = false
//   this.router.navigateByUrl("device-report/device-speed-report");
// }
// mydealer(){
//   window.localStorage['token'] =  window.localStorage['Dealer_token'];
//   localStorage.removeItem('devices');
//   window.localStorage['DataUpdate'] = 'True';
//   if(window.localStorage['DataLoaded'] = 'True'){
//     window.localStorage['Custumer'] = 'OFF'
//     this.router.navigateByUrl("add")
//    // this.router.navigateByUrl("const?_status="+"OK");
//   }
// }

// summaryReport(){

//   this.cond = false
//   this.router.navigateByUrl("device-report/summary-report");
// }

// alert_report(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/alert_report");
// }

// geofancingReport(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/geofancing");
// }

// overspeed(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/overspeed");

// }

// driverPerformance(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/Driver-performance");
// }

// routeViolation(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/routeViolation");

// }

// stoppage_report(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/stoppage_report");

// }



// route_map(){
//   this.router.navigateByUrl("routeMapping");

// }

// distance_report(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/distance_report");
// }

// trip_report(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/trip_report");

// }
// group(){
//   this.cond = false
//   this.router.navigateByUrl("group_view");
// }


// vehicleRoute(){
//   this.router.navigateByUrl("vehicleRoute");

// }

// dealerInfo(){
//   this.cond = false
//   this.router.navigateByUrl("dealerInfo");
// }


getReport(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);
    if(event.deviceArr.length==0){
      deviceId=[];
    }else{
      deviceId= event.deviceArr;
    }
    this.deviceArr = deviceId; 
    this.Fromdate = fd.toISOString();
    this.todate = td.toISOString();
    console.log("b4");
    // this.tabelObj.clear();
    // var aa = [];
    // this.tabelObj.rows.add(aa); 
  
    console.log(this.tabelObj);
    this.tabelObj.ajax.reload();      

  }
 
    


}

   


  overSpeed_data=[];
  overSpeed:any;
  address_show:any;
  vehicle_name:any;
  show_time:any;
  speed_ex:any;
 
  start_add:any;
  uId:any;
  data_descip:any;
  tost1(errcode){
    if(errcode=="error_message"){
      this.data_descip = "No Data Available";
      launch_toast();

    }

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

  }
  start_add_long:any;
  start_add_lat:any;
  deviceArr = [];
  overSpeeding_report(Fromdate,todate){
    //  console.log(this.dataSelect);
      var deviceId;

      this.deviceArr =  $('#select').multipleSelect('getSelects','value');
      if(this.deviceArr.length==0){
        deviceId=[];
      }else{
        deviceId= this.deviceArr;
      }
  
     
      let did =this.useridd;
     
    let f_date = Fromdate.toISOString();
    let t_date =  todate.toISOString();
    // console.log(f_date);
    // console.log(t_date);
    this.overSpeed_data=[];  
    var outerThis = this;
    this.Load = true; 
    this.contactService.overSpeed(f_date, t_date, did,deviceId)
     .subscribe(res => {
        this.overSpeed= res;
        console.log("this.overSpeed=>",this.overSpeed);
        this.Load = false;  
      },err=>{
        this.Load =false;
        console.log("Error while fetching data",err);

      })
  }


  testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function() {
   
       that.tabelObj = $('#deviceTable').DataTable({
          dom: 'lBftip',
          buttons: [
            'copy',
            'print',
            'excel'
          ],       
            "processing": false,
            "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;
                console.log('that.deviceArr',that.deviceArr);    
              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
              }

            
              var suburl = "";
              that.Load= true;    
              suburl += "/notifs/overSpeedReport?from_date=" + temp.from_date +'&to_date=' + temp.to_date + '&_u=' + temp.user;
              if(that.deviceArr.length != 0){  
                suburl +='&device='+that.deviceArr;
              }
              if(temp.from_date && temp.to_date){
              that.contactService.get(suburl).subscribe((resp:any) => {   
                  // console.log(ignReport.length); 
                  that.Load= false;      
                 that.overSpeed=resp;
                  callback({data : resp });
              }, err => {   
                that.Load= false;    
                console.log("error",err) ;     
              });
            }else{
               that.Load= false;   
              callback({data : [] });
            }
          },  
        
            "columns": [
                {
                    "data": "vehicleName",
                    "defaultContent": "",
                    "render": function(data, type, row) {
                        
                      return data?data : '';                  
                    }
                },
                {
                    "data": "overSpeed",
                    "defaultContent": "",
                    render: function(data, type, row) {
                      return data?data:'';        
                    }
                },
                {
                    "data": "address",
                    "defaultContent": "",
                    render: function(data, type, row) {
                      
                      var lat = row.lat?row.lat:0;
                      var long = row.long?row.long:0;
                      var addressLink = '<a href="https://maps.google.com/?q='+ lat +','+long +' "  target="_blank" title="Click to get vehicle End location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>';      
                      return data?data : addressLink; 
                  
                    }
                },        
              {
                "data": "timestamp",
                "defaultContent": "",
                render: function(data, type, row) { 
                  var overspeedDate = new Date(data);
                  return data ? (moment(overspeedDate).format('llll')) : "";              
                 
                }
            }  
            
            ],  
            "columnDefs": [
              { className: "dt-body-left", "targets": [ 0,1,2,3 ] },
              {
                "targets": '_all',
                "createdCell": function (td, cellData, rowData, row, col) {
                    $(td).css('padding', '18px')
                }
            }   ,
            { "width": "10px", "targets": 0 },
            { "width": "40px", "targets": 1 },
            { "width": "100px", "targets": 2 },
            { "width": "70px", "targets": 3 },
           
            ] 
        });
  
    });
  
  }

  addressLink = "";
getlink(report){
  console.log("inside function");
  console.log("report=>",report);
  var lat = report.lat?report.lat:0;
  var lng = report.long?report.long:0;
  this.addressLink =  'https://maps.google.com/?q=' + lat + ',' + lng;
  return this.addressLink ; 
}

  xlUrl:any;
  export_to_XL(Fromdate,todate,option){
    // console.log("Excel report");
    let f_date = Fromdate.toISOString();
    let t_date = todate.toISOString();
    let uId1 = option.user.first_name;
    // console.log(uId1);
    this.contactService.OSXLreport(f_date,t_date,uId1,this.useridd)
      .subscribe(res=>{
      //  console.log(res);
        this.xlUrl= this.dev_url +"/"+res.filename;
        
        // console.log(this.xlUrl);
      })
  
  
  
  }


  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+"</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);
  }
  


filterStates(val) {

  // console.log(val)
  // console.log(this.options)

  if (val==""){

    this.dataSelect = [];
    // console.log("deviceValue",this.dataSelect);
  } else{
  
    const filterValue:any = val;
    
     this.dataSelect = this.options.filter(function(d){
      var t = d.value.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase());
    //  this.option = this.options[i];
  
   
      return t > -1;    
    });
    
      return this.dataSelect;

  }


}

    expotToPdf(){
    console.log(this.overSpeed);

    this.downloadPdf()
    
  }
downloadPdf() {
    let fileName =
      "Overspeeding Report" +
      new Date().getTime() +
      PDF_EXTENSION;
    var pdfsize = "a2";

    var doc = new jsPDF("p", "pt", pdfsize);
  //   var f_date = moment(this.from_date).format('lll'); 
  // var t_date =moment(this.to_date).format('lll');
  // var date_combine = f_date + ' to ' + t_date;
  // doc.setFontSize(30);
  doc.setFontSize(15);
  doc.text('Overspeeding Report ', 20, 30);
  // doc.text(date_combine, 250, 60);
    doc.setFontStyle("arial");

      var header = function(data) {
    doc.setFontSize(15);
    doc.setTextColor(40);
    doc.setFontStyle('normal');
    //doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50);
    // doc.text("Testing Report", data.settings.margin.left, 50);
  };

  var options = {
    beforePageContent: header,
    margin: {
      top: 120
    },
    startY: doc.autoTableEndPosY() + 20
  };

    doc.autoTable({
      head: this.headRows(),
      // margin: { top: 80 },
      body: this.bodyRows(this.overSpeed.length, this.overSpeed),
      options
      
    });
    doc.save(fileName);
  }
  headRows() {

    return [
  // displayedColumns=['vehicleName','IMEI','totalDistance','fuel','ignOn','ignOff','idleTime','outOfReach','noGps','trips','maxSpeed','startLocation','endLocation','details'];

      {
        vehicleName:'Vehicle Name',
        overSpeed:'Overspeed',
        location:'Location',
        timestamp:'Date Time',
        // ac_status:'AC Status',
        
      }
    ];
  }

  bodyRows(rowCount, pdfBody) {
    console.log(rowCount, pdfBody);

    rowCount = rowCount || 10;
    let body = [];
    for (var j = 0; j < rowCount; j++) {
      body.push({

       vehicleName:pdfBody[j].vehicleName,
       overSpeed:pdfBody[j].overSpeed,  
       location:[pdfBody[j].lat,pdfBody[j].long], 
       timestamp:moment(new Date(pdfBody[j].timestamp)).format('llll'),
        // ac_status:pdfBody[j].device.ac_status?pdfBody[j].device.ac_status:'N/A'
      });
    }
    return body;
  }


}
