import { TripHistoryComponent } from './../trip-history/trip-history.component';
import { Component, OnInit } from '@angular/core';
import { ContactService } from '../contact.service';
import { Router } from '@angular/router';
import { MdDialog, MdSnackBar } from '@angular/material';
import { FlashMessagesService } from 'angular2-flash-messages';
import { EditRouteMapComponent } from '../edit-route-map/edit-route-map.component';
import { ExpenseComponentComponent } from '../device-report/trip-by-device/expense-component/expense-component.component';
import { ExpenselistComponent } from '../device-report/trip-by-device/expenselist/expenselist.component';

@Component({
  selector: 'app-route-mapping',
  templateUrl: './route-mapping.component.html',
  styleUrls: ['./route-mapping.component.scss']
})
export class RouteMappingComponent implements OnInit {

  route_detail_show1: any;
  routeObject: any;
  constructor(private router: Router,private contactService: ContactService,public dialog: MdDialog, public snackBar: MdSnackBar,private _flashMessagesService: FlashMessagesService) { }
  before:any;
  logoutbut:boolean;
  cust:boolean=false;
  logo:any;
  text:any;
  fs:any;ls:any;emailid:any;or:any;useridd:any;mb:any;custtype:any;dealer:any;
  showImage:any;
  groups=[];
  group_info:any;
  myInput:any;
  deviceId:any;
  device_update:any;
  superAdmin:Boolean = false;
  ngOnInit() {
    this.logo=window.localStorage['logo'];
    this.text=window.localStorage['text'];  
     window.localStorage['DataUpdate'] = 'Tthis.rue'
     
     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;
    //  console.log('testing',this.useridd);
     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.trackMapRoute();
  this.routeDetails(this.useridd);

  }


  mydealer(){
    // console.log('Dealer')
  }

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

  geo(){
    this.router.navigateByUrl("geofencing");
    
  }

  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");
    
  }
  
  group(){
    this.cond = false
    this.router.navigateByUrl("group_view");
  }

  cond:Boolean = false;
point : any = 0;
 aa(){
  // 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 ++;
 }

  
}


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

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

}
report_speed(){
  // console.log("report speed call")
  this.cond = false
  this.router.navigateByUrl("device-report/device-speed-report");
}



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

}




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

}

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

}

summaryReport(){

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

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

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

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


}

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


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

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

}

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

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

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

saveRoute(){
  this.cond = false
  this.router.navigateByUrl('vehicleRoute');
}



addcus(){
  localStorage.removeItem('mapLoad_ID')
  this.router.navigateByUrl("add");
}
Ddetail(){
  this.router.navigateByUrl("driverdetail");
}
DModel(){
  this.router.navigateByUrl("deviceModel");
}
VType(){
  this.router.navigateByUrl("VehicleType");
}
dealerInfo(){
  this.cond = false
  this.router.navigateByUrl("dealerInfo");
}

route_detail=[];
trackMapRoute(){

  this.contactService.trakcRouteMap(this.useridd)
  .subscribe(res=>{
    // console.log("qwerty",res);
    console.log('res=>',res);
    this.route_detail=res;
    
    // console.log(res.length)
    // for(var k=res.length-1;k>=0;k--){
    //   var newObj = {
    //     'Route_Name':res[k]?res[k].Route_Name:'',
    //     'Device_Name':res[k]?res[k].Device_Name:'',
    //     'Driver':res[k]?res[k].Driver:'',
    //     'Loading_Site':res[k]?res[k].Loading_Site:"",
    //     'Unloading_Site':res[k]?res[k].Unloading_Site:"",
    //     'Planned_Start_Time':res[k]?res[k].Planned_Start_Time:'',
    //     'Planned_End_Time':res[k]?res[k].Planned_End_Time:'',
    //     'Actual_Start_Time':res[k]?res[k].Actual_Start_Time:'',
    //     'Actual_End_Time':res[k]?res[k].Actual_End_Time:'',
    //     'Trip_Status_Reached':res[k]?res[k].Trip_Status_Reached:'',
    //     'End_Duration':res[k]?res[k].End_Duration:'',
    //     'Allow_Reverse':res[k]?.res[k].Allow_Reverse
      
    //   }
    //   this.route_detail.push(newObj);
    // }
    
    // console.log(this.route_detail)
    // console.log(this.route_detail.length)
   
  },err=>{
    // console.log(err.status);
    // console.log("Error occured !!!");
    // this._flashMessagesService.show("Internal server error !!!", { cssClass: 'alert-danger', timeout: 2500 });
  })
}



addMapPOI(poiRoute){ 

  this.cond = false
  localStorage.setItem('POIID', JSON.stringify(poiRoute.routeId));
  localStorage.setItem('startTime', JSON.stringify(poiRoute.Actual_Start_Time));
  localStorage.setItem('endTime', JSON.stringify(poiRoute.Actual_End_Time));
  localStorage.setItem('devId',JSON.stringify(poiRoute.Device_Id))

  var tripShow = {
    routeId:poiRoute.routeId,
    actualStartTime:poiRoute.Actual_Start_Time,
    actualEndTime:poiRoute.Actual_End_Time,
    deviceId:poiRoute.Device_Id
  }

  // console.log("tripObject=>",tripShow);



  localStorage.setItem('poiData', JSON.stringify(tripShow));


  this.router.navigateByUrl("Point_Of_Intrest");
}

routeDetails(uId){
  // console.log(uId);
  this.contactService.getRouteDetail(uId)
    .subscribe(res=>{
      // console.log("routedet",res.status)
      this.route_detail_show1=res;
    },err=>{
      // console.log(err.status);
      // console.log("Error occured !!!");
      // this._flashMessagesService.show("Internal server error !!!", { cssClass: 'alert-danger', timeout: 2500 });
    })
}

route_Id:any;

tripHistory(route){
 

  this.route_Id = route.routeId;
console.log(route);

  let dialogRef_1 = this.dialog.open(TripHistoryComponent, {
    // height:'500px',
    width:'950px',
    data:route
  });

}

// edit routeMap functionality starts here 
editRouteMap(route){

  // console.log("route Object",route);

  this.routeObject= route;

  let dialogRef_edit = this.dialog.open(EditRouteMapComponent, {
    // height:'600px',
    // width:'950px',
    data: {routeId : this.routeObject}
  });


  dialogRef_edit.afterClosed().subscribe(result => {
    
    // console.log(result);
    if(result=="success"){
      this.trackMapRoute()

    }
  })

}


table1ch(){
    
  myFunction();
      function myFunction() {
        var input, filter, table, tr, td, i,td1;
        input = document.getElementById("myInput");  
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        for (i = 0; i < tr.length; i++) {
          td = tr[i].getElementsByTagName("td")[1];
          td1= tr[i].getElementsByTagName("td")[0]
          if (td) {
            if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
              tr[i].style.display = "";
            } 
            else if(td1.innerHTML.toUpperCase().indexOf(filter) > -1){
              tr[i].style.display = "";
            }
            else {
              tr[i].style.display = "none";
            }
          }       
        }
      }
    }



    tab:any;
exportExcel()
{
 
 
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    this.tab = document.getElementById('test_route'); // id of table
    // console.log('tab=>',this.tab)
    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
    tab_text= tab_text.replace(/<md-icon[^>]*>|<\/md-icon>/gi, ""); // reomves input params
   
    // console.log(tab_text)


  //   <td _ngcontent-c11="">
  //   history
  // </td>
  // <td _ngcontent-c11="">
  //   edit
  // </td>

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");
    var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  
    return (sa);
}


addExpense(tripObject){
  console.log('tripObject=>',tripObject);
  let dialogRef = this.dialog.open(ExpenseComponentComponent, {
    width : "700px",
    data: tripObject
  });

  dialogRef.afterClosed().subscribe(result => {
    // console.log(result);
    if(result == "success"){
      let message1="Expense Added";
      let action:any;
      this.snackBar.open(message1, action, {
        duration: 5000,
        
      });  
    
    }
 
  });  
}

expenseList(tripObject)
{
  let dialogRef = this.dialog.open(ExpenselistComponent, {
    width : "700px",
    data: tripObject
  });

}


}
