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';


declare var google: any;
declare var $:any;
import * as moment from 'moment';

@Component({
  selector: 'app-stoppage-report',
  templateUrl: './stoppage-report.component.html',
  styleUrls: ['./stoppage-report.component.scss']
})
export class StoppageReportComponent 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;
  // filterDurations=[{
  //   value:2,
  //   viewvalue:"More than 2 Hours"
  // },
  // {
  //   value:6,
  //   viewvalue:"More than 6 Hours"
  // },
  // {
  //   value:12,
  //   viewvalue:"More than 12 Hours"
  // },{
  //   value:24,
  //   viewvalue:" More than 24 Hours"
  // }]
  stoppage_duration: any;
  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog) { }

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

    //   });

      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;
  // stoppageReport(Fromdate,todate){
 
  //   let f_date = Fromdate.toISOString();
  //   let t_date =  todate.toISOString();
  
  //   var uId= this.useridd
   

  //   var vName="";
  // if((this.dataStoppage==undefined)||(this.dataStoppage.length==0)){
  //   vName="";
  // }else{
  //   vName= this.dataStoppage?this.dataStoppage[0].id:"";
  // }

  //   // console.log(vName)
  //   this.report_to_show=[];
  //   var outerThis = this;
   
  //   // console.log('completeObj',uId,vName);
  //   this.Load =true;
  //   this.contactService.stoppage_report(f_date,t_date,uId,vName)
  //   .subscribe(res=>{
  //     console.log(res)
  //    this.Load = false;
  //     this.stoppage_data = res;
  //     // console.log(this.stoppage_data)

  //     // for(var i=0;i<this.stoppage_data.length;i++){
  //      for(var i=0;i<this.stoppage_data.length;i++){
  //       this.arrival_time = new Date(this.stoppage_data[i].arrival_time).toLocaleString();
       
  //       this.departure_time = new Date(this.stoppage_data[i].departure_time).toLocaleString();
  //       var fd = new Date(this.arrival_time ).getTime();
  //       var td = new Date(this.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);
      
  //       this.Durations = rhours +'hrs'+ rminutes + 'min';
  //       this.address = this.stoppage_data[i].address
        
  //       this.overSpeedobject = {
  //         deviceName : this.stoppage_data[i].device?this.stoppage_data[i].device.Device_Name:"NA",
  //         arrivalTime:this.arrival_time,
  //         departureTime: this.departure_time,
  //         duration:this.Durations,
  //         location: this.address,
  //         lattitude   : this.stoppage_data[i].lat?this.stoppage_data[i].lat : 0,
  //         longitude : this.stoppage_data[i].long?this.stoppage_data[i].long : 0,
  //       }
   
  //     this.report_to_show.push(this.overSpeedobject)

  //      }
  //   },err=>{
  //     this.Load = false;
  //     console.log("error while fetching data",err);
  //   })    
  // }

  // xlStoppageReport(Fdate,tdate,option){
  //   let uId = option.user;
  //   let vName= option._id;
  //   this.contactService.xlStoppageReport(Fdate.toISOString(),tdate.toISOString(),this.useridd,vName)
  //     .subscribe(res=>{
  //       // console.log('xcelreport',res);
  //     })
  // }


addressLink = "";
// getlink(report){
 
//   var lat = report.lattitude?report.lattitude:0;
//   var lng = report.longitude?report.longitude:0;
//   this.addressLink =  'https://maps.google.com/?q=' + lat + ',' + lng;
//   return this.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);
  }
  


  // filterStoppageStates(val) {

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

  // getStoppageObj(valS){
  //   this.stoppage_obj = valS;
  // }


  // filterReport(){
  //   var tableFilteredData = [];
  //   // console.log('Inside function')
  //   // console.log(this.duration.value);
  //   for(var i=0;i<this.report_to_show.length;i++){
  //     if(Number(this.report_to_show[i].duration.split("h")[0])>this.duration.value){
  //       tableFilteredData.push(this.report_to_show[i]);
  //     }
  //   }
  //   this.report_to_show = tableFilteredData;
  // }

  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) => {
            
                var deviceID;
             
                var vName; 
                var dr ; 
              var from_date = that.Fromdate;
              var to_date = that.todate;
              var user = that.useridd;
              if(that.deviceArr.length != 0){
                vName = that.deviceArr[0];
              }
              if((that.stoppage_duration != undefined )&&(that.stoppage_duration.length != 0 )){
              
                  dr = that.stoppage_duration[0];
                  console.log("DR-",dr);
                  
              }
                  that.Load = true ; 
                if((from_date != undefined)&&(to_date != undefined)){
                  that.contactService.stoppage_report(from_date,to_date,user,vName)
                  .subscribe(res=>{ 
                    that.stoppage_data =[];     
                    that.Load = false ; 
                    that.stoppage_data = that.durationFilter(res);  
                     callback({data : that.stoppage_data});
                  },err=>{
                    that.Load = false ; 
                    console.log("error while fetching data",err);
                  }) 

                }else{
                  that.Load = false; 
                      let ta = [];
                     callback({data : ta});
                }
         
          }, 
        
            "columns": [
                {
                    "data": "device",   
                    "render": function(data, type, row) {
                        
                      return data?data.Device_Name : '';                  
                    }
                },
                {
                    "data": "arrival_time",
                    render: function(data, type, row) {
                      var atime = new Date(data);
                      return data ? (moment(atime).format('llll')) : "";    
                    }
                },
                {
                    "data": "departure_time",
                
                    render: function(data, type, row) {
                      var dtime = new Date(data);
                      return data ? (moment(dtime).format('llll')) : "";  
                  
                    }
                }, 
          
                
              {
                "data": "_id",
                "defaultContent": null,
                render: function(data, type, 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;
                 
                }
            } ,
            {
              "data": "address",
              render: function(data, type, row) {            
                var lat = row.lat?row.lat:0;
                var lng = row.long?row.long:0;    
                  var addressLink = '<a href="https://maps.google.com/?q='+ lat +','+lng +' "  target="_blank" title="Click to get vehicle last location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>';            
                  if(data){
                    return data ;
                  }else{
                    return addressLink;     
                  }
              }
          }                       
            ],  
            "columnDefs": [
              { className: "dt-body-left", "targets": [ 0,1,2,3,4 ] },
              {
                "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 },
         
            ] 
        });
  
    });
  
  }

  deviceArr=[];
  data_descip = '';
  getReport(event){
    console.log(event);
    if(event == 'getExcel'){
      this.exportExcel();
    }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=[];
        this.data_descip = 'Please Select Device';
        launch_toast(); 
        return
      }else{
        deviceId= event.deviceArr;
      }
      this.deviceArr = deviceId; 
    
      this.stoppage_duration = event.duration ; 
      if(this.stoppage_duration.length == 0){
        // this.data_descip = 'Please Select Duration';
        // launch_toast(); 
        // return
        this.stoppage_duration.push(0)
        
      }
      
      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};
  }
  
}


