import { Component, OnInit } from '@angular/core';
import { MyaccountComponent } from '../../myaccount/myaccount.component';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { ContactService } from '../../contact.service';
import * as moment from 'moment-timezone';
import { BsDatepickerConfig } from 'ngx-bootstrap';
declare var $:any;
@Component({
  selector: 'app-fuel-report',
  templateUrl: './fuel-report.component.html',
  styleUrls: ['./fuel-report.component.scss']
})
export class FuelReportComponent implements OnInit {
 token_identifier: string;
  dataSelect: any[];
  emailid: any;
  useridd: any;
  custtype: any;
  options: any;
   show:boolean=false
  showLine:boolean=false;
  ignition_data
  from_date =new Date();
  to_date = new Date();
  showLoader: boolean;
  event=true;
bsConfig: Partial<BsDatepickerConfig>;
  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog) { }

  ngOnInit() {
     this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' }, { containerClass: 'theme-dark-blue'});
   this.token_identifier = localStorage.getItem('referrer_token=');
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
  
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
 
    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
     this.loadropdown()
    this.getDevices()
    this.testTable()

  }
  Load:boolean=false
  tabelObj:any
  finalArr=[]
  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) => {
         
         that.Load = true;
          console.log("INNNNNS");
           
            if(that.deviceArr.length>0){
            var data={
      start_time:new Date(that.from_date).toISOString(),
end_time: new Date(that.to_date).toISOString(),
event: that.event==true?"IN":"OUT",
imei: that.deviceArr[0]

    }
    that.contactService.post('/gps/getFuelNotifs',data).subscribe((res:any)=>{
               that.Load= false;  
              callback({ data: res });
            }, err => {   
              that.Load= false;    
              callback({ data: [] });
              console.log("error",err) ;     
            });
          }else{
            that.Load= false; 
              console.log("INNNNNS");   
              callback({ data: [] });
          }
   
           
           
        },  
          "columns": [
              {
                  "data": "vehicleName",
                  "render": function(data, type, row) {                   
                    return data?data : '';                  
                  }
              },
               {
                  "data": "pour",
                  "render": function(data, type, row) {                   
                    return data?data : '';                  
                  }
              },
              {
                  "data": "litres",
                  "render": function(data, type, row) {                   
                    return data?data : '';                  
                  }
              },
              {
                  "data": "timestamp",
                  "render": function(data, type, row) {                   
                   return data ? (moment(data).format('llll')) : "";                  
                  }
              },
              {
                  "data": "address",
                  "render": function(data, type, row) {                   
                   return data?data : '';                   
                  }
              },
               

          ],  
          "columnDefs": [
            { className: "dt-body-left", "targets": [ 0,1,2,3] },  
          
          ] 
      });

  });
  }
 

devicesss;
finall
 getDevices(){
    
     this.contactService.getDevice(this.emailid,this.useridd).subscribe(

        data => {
          this.devicesss = data
          this.show=true
          this.finall = (this.devicesss.devices);
          this.options = [];
        
          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,    
              }
               a['selectedValue'] = this.devicesss.devices[i].Device_ID ;
            //  if ((this.componentIdentifier === 'trip_report')||(this.componentIdentifier === 'distance_report')||(this.componentIdentifier === 'idle_report')||(this.componentIdentifier == 'fuel_consumption_report')||(this.componentIdentifier === 'poi_report')||(this.componentIdentifier === 'stoppage_report')||(this.componentIdentifier === 'vehicle_expenses')||(this.componentIdentifier === 'loadunloadTrip')||(this.componentIdentifier === 'maintanance_report')){
            //     a['selectedValue'] = this.devicesss.devices[i]._id ; 
            //   }else if ((this.componentIdentifier === 'fuel_report_graph')||(this.componentIdentifier === 'temp_report_graph')||(this.componentIdentifier === 'summary_report')||(this.componentIdentifier === 'over_speed')||(this.componentIdentifier === 'daily_report')||(this.componentIdentifier === 'device_sos_report')||(this.componentIdentifier === 'ignition_report') ||(this.componentIdentifier === 'working_report')|| (this.componentIdentifier === 'dayWiseReport')||(this.componentIdentifier === 'censor_detail')||(this.componentIdentifier === 'notification_master')){
            //     a['selectedValue'] = this.devicesss.devices[i].Device_ID ; 
            //   }
              this.options.push(a);
            // }
          }
          this.loadropdown()
        })
}

openNav() {
  if(this.showLine){
    document.getElementById("mySidebar").style.width = "295px";
    // document.getElementById("main").style.marginLeft = "295px";
      document.getElementById("line").style.marginLeft = "295px";
      document.getElementById("line1").style.marginLeft = "295px";
      document.getElementById("line").style.background="none"
      

      this.showLine=false;
  }else{
    this.closeNav()
  }


}

closeNav() {
  document.getElementById("mySidebar").style.width = "0";
  document.getElementById("main").style.marginLeft= "0";
  document.getElementById("line").style.marginLeft= "0";
  document.getElementById("line").style.background="#426E86"
  document.getElementById("line").style.width="20px"
  document.getElementById("line1").style.marginLeft= "0";

    this.showLine=true
}


  
changeDate(dateid) {

  if (dateid == 'today') {
    var td = new Date();
    this.from_date = new Date(td.setHours(0, 0, 0));
    this.to_date = new Date();
    console.log('this.from_date', this.from_date);
  }
  if (dateid == 'yesterday') {
    var yt = moment().subtract(1, 'days');
    var ptt = new Date(yt).setHours(0, 0, 0);
    var ttt = new Date(yt).setHours(23,59,59);
    this.from_date = new Date(ptt);
    this.to_date = new Date(ttt);
    console.log('this.from_date', this.from_date);
    console.log('this.to_date', this.to_date);
  }
  if (dateid == 'week') {
    var wd = moment().startOf('week')
    this.from_date = new Date(wd);
    console.log('this.from_date', this.from_date);
    this.to_date = new Date();
  }
  if (dateid == 'month') {
    var md = moment().startOf('month').format();
    this.from_date = new Date(md);
    console.log('this.from_date', this.from_date);
    this.to_date = new Date();
  }
}
data_descip:any;
getReport(event){
  console.log(event);
  
  if(event == 'getExcel'){
    // this.exportExcel();
  }else{

  }
}

 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(() => {
        $('#dbselect').multipleSelect({
          width: 210,
          placeholder: 'Select Vehicles .....',
          filter: true,
          single: true,
          selectAll: false
   
        })
    
       that.showLoader = false;
      }, 100);
      

      
   
    
  }
  deviceArr=[]
  reportFilter(){
    this.deviceArr =  $('#dbselect').multipleSelect('getSelects','value'); 
    console.log(this.deviceArr,this.from_date,this.to_date);
    var data={
      start_time:new Date(this.from_date).toISOString(),
end_time: new Date(this.to_date).toISOString(),
event: this.event==true?"IN":"OUT",
imei: this.deviceArr[0]

    }
     this.tabelObj.ajax.reload(); 
    // this.contactService.post('/gps/getFuelNotifs',data).subscribe((res:any)=>{
    //   console.log(res);
    //   this.finalArr=res;
    //   this.tabelObj.ajax.reload();  

    // })
  }
  exportExel(){

  }
  exportPDF(){

  }
}
// http://localhost:3000/gps/getFuelNotifs
// {start_time: "2022-02-05T18:30:00.000Z", end_time: "2022-02-10T09:07:19.622Z", imei: "354018113208049",…}
// end_time: "2022-02-10T09:07:19.622Z"
// event: "IN"
// imei: "354018113208049"
// start_time: "2022-02-05T18:30:00.000Z"