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

@Component({
  selector: 'app-drivers-performance-report',
  templateUrl: './drivers-performance-report.component.html',
  styleUrls: ['./drivers-performance-report.component.scss']
})
export class DriversPerformanceReportComponent 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=new Date();
  todate= new Date();
  options=[];
  logo:any;
  before:any;
  date1:any;
  daily_report_data:any;
  superAdmin:Boolean = false;

  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog) { }

  ngOnInit() {
    var fTime = new Date();
    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.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);
    });

    this.getDriverList();
  }



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

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


  }


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

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

}

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

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

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

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


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

}

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

}

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

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

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

}


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



// component code starts here 

groupVal:any;
driverVal:any;
getDrivers:any;
reportArr=[]
driverReport(){
  // console.log(this.driverVal._id);
  var driverId = this.driverVal._id;
  // console.log(this.Fromdate);
  // console.log(this.todate);
  this.reportArr = [];
  this.contactService.driverReport_data(this.Fromdate,this.todate,driverId)
    .subscribe(res=>{
      // console.log(res);
      for(var i=0;i<res.length;i++){
        this.reportArr[i] = {};
        this.reportArr[i].name = res[i]._id.Driver_Name;
        this.reportArr[i].tripCount = res[i].total_trips;
        this.reportArr[i].Delay = "",  this.reportArr[i].Ontime = "";
        for(var j=0;j<res[i].Overall_Details.length;j++){
          
          if(res[i].Overall_Details[j].status=="Ontime")
          {
            for(var k=0;k<res[i].Overall_Details[j].route_names.length;k++){
              this.reportArr[i].Ontime+=(res[i].Overall_Details[j].route_names[k].names)+" | ";
            }
            this.reportArr[i].onTimeCount = res[i].Overall_Details[j].status_count;
          }
          if(res[i].Overall_Details[j].status=="Delay"){ 
            for(var k=0;k<res[i].Overall_Details[j].route_names.length;k++){
              this.reportArr[i].Delay+=(res[i].Overall_Details[j].route_names[k].names)+" | ";
            }
            this.reportArr[i].delayCount = res[i].Overall_Details[j].status_count;            
          }
         
        }
      }
      // console.log(this.reportArr);
    })
  }

getDriverList(){
  let id= this.useridd;
  this.contactService.getDrivers(id)
    .subscribe(res =>{
      // console.log(res)
      this.getDrivers= res;
    })
}

grpName:any;
getGrp(){
  this.contactService.getGroup(this.useridd).subscribe(      
    res => {
      // console.log(res);     
      this.grpName = res["group_details"];
      // console.log(this.grpName);  
    })
}

tab:any;
exportExcel()
	{
   

	    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
	    var textRange; var j=0;
	    this.tab = document.getElementById('test'); // 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);
	}

}
