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-route-violation',
  templateUrl: './route-violation.component.html',
  styleUrls: ['./route-violation.component.scss']
})
export class RouteViolationComponent implements OnInit {
  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;
  tabelObj:any;
  superAdmin:Boolean = false;
  date1:any;
  user_against_route: 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;

   

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

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

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


//   }


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



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

// 	Ddetail(){
//     this.router.navigateByUrl("driverdetail");
//   }
//   DModel(){
//     this.router.navigateByUrl("deviceModel");
//   }
//   VType(){
//     this.router.navigateByUrl("VehicleType");
//   }
  
//   route_map(){
//     this.router.navigateByUrl("routeMapping");

//   }

//   notification(){
//     this.cond = false
//     this.router.navigateByUrl("notifications");
//   }
  
//   driverPerformance(){
//     this.cond = false
//     this.router.navigateByUrl("device-report/Driver-performance");
//   }
  
//   ideal(){
//     this.router.navigateByUrl("device-report/ideal-report");
//   }
//   geo(){
//     this.router.navigateByUrl("geofencing");
    
//   }
//   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");
// }

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

// }

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

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

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

// }

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

// }

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

// }

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

// distance_report(){
//   this.cond = false
//   this.router.navigateByUrl("device-report/distance_report");
// }
  routeViolation_data=[];
  route:any;
  show_time:any;;
  vehicle_name:any;
  address_show:any;
  start_add:any;
  lattitude:any;
  longitude:any;
  route_name:any;

  route_vioation(Fromdate,todate,option){
    let f_date = Fromdate.toISOString();
    let t_date =  todate.toISOString();
    this.routeViolation_data=[];
    let uId = option.user;
    var outerThis = this;

    this.contactService.route_violation(f_date, t_date, uId) 
    .subscribe(res=>{
        // console.log(res);
        this.route = res;
      })
  }



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

  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;
               
                // dataTablesParameters.find._u = that.useridd;
              
                // dataTablesParameters.find._u = user;
  
                // if(that.deviceArr.length != 0){
           
                  // dataTablesParameters.find.vname = deviceId;
                // }
              // if (that.Fromdate) {
                  // var fdate = new Date(that.Fromdate).toISOString()      
                  // dataTablesParameters.find.f_date = fdate    
                  // dataTablesParameters.find.f_date =  from_date;    
              // };
  
              // if (that.todate) {
                // var fdate = new Date(that.todate).toISOString()      
                // dataTablesParameters.find.t_date = fdate     
                  // dataTablesParameters.find.t_date = to_date  ;
            // };
            // this.deviceArr = deviceId; 
           
              var from_date = that.Fromdate;
              var to_date = that.todate;
              let user; 
          if(that.user_against_route.length != 0){
             user = that.user_against_route[0].user
          }else{
            console.log("Please Select Route");
          }
          console.log(user);
            if((from_date != undefined)&&(to_date != undefined)){
              that.contactService.route_violation(from_date, to_date, user).subscribe(res=>{
                // console.log(res);
                that.Load = false;
                that.route = res;
                callback({data : that.route})
              },err=>{
                that.Load = false;
              })

            }else{
              let ta =[];
              that.Load = false;
              callback({data : ta})
            }
      
             
            
          },  
        
            "columns": [
                {
                    "data": "vehicleName",
                    "render": function(data, type, row) {
                        
                      return data?data : '';                  
                    }
                },
                {
                    "data": "track",
                    render: function(data, type, row) {
                      return data?data.name:'';        
                    }
                },
                {
                    "data": "address",
                    "defaultContent": "_id",
                    render: function(data, type, row) {
                      return data?data:"";  
                    }
                },            
              {
                "data": "timestamp",
                render: function(data, type, row) {        
                  var rt = new Date(data);
                  return data ? (moment(rt).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 },
         
            ] 
        });
  
    });
  
  }




  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];
  
      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);
  }
  
  deviceArr =[];
  identifier  ="route_violation_report";

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


}
