import { Component, OnInit, Output, EventEmitter, Input, OnChanges } from '@angular/core';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { ContactService } from '../../contact.service';
declare var $:any;
import * as moment from 'moment-timezone';
import { Router } from '@angular/router';
@Component({
  selector: 'app-report-filter',
  templateUrl: './report-filter.component.html',
  styleUrls: ['./report-filter.component.scss']
})
export class ReportFilterComponent implements OnInit {
  from_date =new Date();
  to_date = new Date();
  liecenceStatus="New"
  distributerValue
  type=[{Name:'Renewed',value:'renewed'},{Name:'Renewal Pending',value:'pending'},{Name:'Expired',value:'expired'}]
  renewalType='renewed'
  liecenceTypeArray=[
    {name:"New",value:"new"},
    {name:"Renewal",value:"renewal"}
  ]
  months=[{name:'January',value:0},{name:'February',value:1},{name:'March',value:2},{name:'April',value:3},{name:'May',value:4},{name:'June',value:5},
          {name:'July',value:6},{name:'August',value:7},{name:'September',value:8},{name:'October',value:9},{name:'November',value:10},{name:'December',value:11}]
  bsConfig: Partial<BsDatepickerConfig>;
  @Output() onReportFIlter: EventEmitter<any> = new EventEmitter<any>();
  superAdmin: any;
  disDataFIlter=[]
  fs: any;
  emailid: any;
  ls: any;
  or: any;
  useridd: any;
  bilingMonth = new Date();
  mb: any;
  custtype: any;
  devicesss: any;
  minIdleTime:any=5;
  showXL : Boolean =true; 
  filterRtype = 'Time';
  userFilterType='Name';
  deviceFilterType='IMEI';
  distributers=[]
  reportType = ['Time','Daily','Trip'];
  userRadio= ['Phone', 'Name'];
  deviceRadio= ['IMEI','SIM'];
  deviceRadio1= ['IMEI','NAME'];
  billingType = [{
    selectedValue:'Monthly',
    value: 'Monthly'
  },

  {
    selectedValue:'Yearly',
    value: 'Yearly'
  }]

  billing_status =[
    {
      selectedValue:'Paid',
      value: 'Paid'
    },
    {
      selectedValue:'Pending',
      value: 'Pending'
    }

  ]
  finall: any;
  deleteduser:boolean=false;
  deleteddevice:boolean=false;
  options: any=[{selectedValue : '',value:''}];
  cust: boolean;
  logoutbut: boolean;
  dealer: boolean;
  showLoader:boolean=true;
  colorTheme = 'theme-dark-blue';
  optionLabel:String = 'Vehicle';
  showFromDate : Boolean = true;
  lableVariable = 'To' ; 
  stoppage_duration =[{value: "0",view_value:"All Data"},{value: "1",view_value:"Less Than 2 Hours"},{value: "2",view_value:"More Than 2 Hours"},{value: "6",view_value:"More Than 6 Hours"},{value: "12",view_value:"More Than 12 Hours"},{value: "24",view_value:"More Than 24 Hours"}];
  selectedStopageDuration="0"
  @Input() componentIdentifier: string;
  constructor(private contactService: ContactService,private router:Router) { 
     console.log("UEJJSKHHH",this.router.url);
    
    if(this.router.url=="/NotificationForCC"){
      this.componentIdentifier=="notification_master"
      
    }
    console.log(this.componentIdentifier,this.selectedStopageDuration);
    this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' }, { containerClass: this.colorTheme });
  }

  ngOnInit() {
    this.loadropdown();
    this.getSuperAdminList()
    var fTime = new Date();
    fTime.setHours(0,0,0,0);   
    this.from_date = new Date(fTime);
    console.log('this.componentIdentifier',this.componentIdentifier);

    if(this.componentIdentifier === 'summary_report'){
   
      fTime.setDate(fTime.getDate()-1);
     
      this.from_date = new Date(fTime);
  
      var td  = new Date().setHours(23,59,59,999);
      this.to_date = new Date(td);
      this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYYY' }, { containerClass: this.colorTheme });

    }

    if((this.componentIdentifier === 'dayWiseReport')){
      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(this.componentIdentifier=="deviceList"){
      var today = new Date();
      var startDate = new Date(today.getFullYear(), today.getMonth(), 1);
      this.from_date=startDate
    }

    if(this.componentIdentifier === 'daily_report'){
      this.showFromDate = false;
      this.lableVariable = 'Select Date';
      
    }


    if((this.componentIdentifier === 'fuel_report_graph') || (this.componentIdentifier === 'vehicle_expenses')||(this.componentIdentifier === 'temp_report_graph')){
      this.showXL = false;
    }
   
  
    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.componentIdentifier === 'geofence_report'){
      this.optionLabel = 'geofences'; 
      this.getgeofence();
    }else if(this.componentIdentifier === 'route_violation_report'){
      this.routeViolationArr()
    }else if(this.componentIdentifier === 'billing_detail'){
      this.getUser();

    }else{
      this.contactService.getDevice(this.emailid,this.useridd).subscribe(

        data => {
          this.devicesss = data
       
          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,
                // email: this.devicesss.devices[i].Email_ID,
                // deviceType: this.devicesss.devices[i].type_of_device,      
              }
              
             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);
            // }
          }

          if(this.componentIdentifier == 'poi_report'){
            this.getPOI();
          }else{
            this.loadropdown();
          }
      

        
            // console.log("ignition option",this.options);
            let that = this;
            // setTimeout(()=>{ 
            // },100)  
        
        });

      

    }
  



      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
     } 
     
     if(this.componentIdentifier == 'usersMaster'){  
      this.getAllUser();
     }

     if((this.componentIdentifier == 'deviceRenew')||(this.componentIdentifier == 'deviceMaster')||(this.componentIdentifier == 'gps_master')){  
      this.getAllDevice();
     }
     if(this.componentIdentifier === 'notification_master'){
          this.getDeviceForNotif();
     }
  
     
  }

  loadropdown() {
    let that = this;
    var placeholderval;
    if(this.componentIdentifier === 'geofence_report'){
      placeholderval = 'Select Geofence .....'
    }
    if((this.componentIdentifier === 'distance_report')||(this.componentIdentifier === 'fuel_report_graph')||(this.componentIdentifier === 'temp_report_graph')||(this.componentIdentifier === 'loadunloadTrip')||(this.componentIdentifier === 'censor_detail')){
      placeholderval = 'Select Vehicles .....'
    }
    if(this.componentIdentifier === 'billing_detail'){
      placeholderval = 'Select User .....'

    }
    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);
  
    // ||(this.componentIdentifier === 'notification_master')
    if((this.componentIdentifier === 'geofence_report')||(this.componentIdentifier == 'usersMaster')||(this.componentIdentifier == 'deviceRenew')||(this.componentIdentifier == 'deviceMaster')||(this.componentIdentifier === 'poi_report')||(this.componentIdentifier === 'billing_detail')||(this.componentIdentifier === 'fuel_report_graph')||(this.componentIdentifier === 'temp_report_graph')||(this.componentIdentifier === 'device_sos_report')||(this.componentIdentifier === 'vehicle_expenses')||(this.componentIdentifier === 'censor_detail')||(this.componentIdentifier ==='gps_master')){
      console.log(placeholderval);
      setTimeout(() => {
        $('#dbselect').multipleSelect({
          width: 230,
          placeholder: placeholderval,
          filter: true,
          single: true,
          selectAll: false
   
        })
    
       that.showLoader = false;
      }, 100);
      

      if(this.componentIdentifier === 'billing_detail'){
        setTimeout(() => {

          $('#dbselect_billtype').multipleSelect({
            width: 200,
            placeholder: "Select Type",
            filter: true,
            single: true,
            selectAll: false  
          }) 
       
  
          $('#dbselect_billStatus').multipleSelect({
            width: 200,
            placeholder: "Select Status",
            filter: true,
            single: true,
            selectAll: false  
          }) 
        }, 100);
      }

      if(this.componentIdentifier == 'usersMaster'){
        setTimeout(() => {
          $('#dbselectPhone').multipleSelect({
            width: 250,
            placeholder: "Customer Phone",
            filter: true,
            single: true,
            selectAll: false  ,
         
          }) 

          $("#dbselectPhone").multipleSelect("disable");
    
          $('#dbselectName').multipleSelect({
            width: 250,
            placeholder: "Customer Name",
            filter: true,
            single: true,
            selectAll: false  
          }) 
    
        },100)
       }

       if(this.componentIdentifier == 'deviceMaster'){

        setTimeout(() => {
          $('#dbselectIMEI').multipleSelect({
            width: 250,
            placeholder: "Vehicle IMEI",
            filter: true,
            single: true,
            selectAll: false  
          }) 
    
          $('#dbselectSIM').multipleSelect({
            width: 250,
            placeholder: "Sim Number",
            filter: true,
            single: true,
            selectAll: false  
          }) 

          $("#dbselectSIM").multipleSelect("disable");
    
        },100)

       }
       

       if(this.componentIdentifier == 'gps_master' || this.componentIdentifier=='deviceRenew'){

        setTimeout(() => {
          $('#dbselectIMEI').multipleSelect({
            width: 250,
            placeholder: "Vehicle IMEI",
            filter: true,
            single: true,
            selectAll: false  
          }) 
    
          $('#dbselectVehicleName').multipleSelect({
            width: 250,
            placeholder: "Vehicle Name",
            filter: true,
            single: true,
            selectAll: false  
          }) 

          $("#dbselectVehicleName").multipleSelect("disable");
    
        },100)

       }

     

      
    }else{
      setTimeout(() => {
        $('#dbselect').multipleSelect({
          width: 200,
          placeholder: 'Select Vehicle.....',
          filter: true,
   
        })  
      }, 100);

    }



    if(this.componentIdentifier == 'poi_report'){
      setTimeout(() => {
        $('#dbselect_1').multipleSelect({
          width: 200,
          placeholder: "Select POI",
          filter: true,
          single: true,
          selectAll: false  
        }) 
      }, 100);
    }

  

    if(this.componentIdentifier == 'stoppage_report'){
      setTimeout(() => {
        $('#dbselect_2').multipleSelect({
          width: 200,
          placeholder: "Select Duration",
          filter: true,
          single: true,
          selectAll: false,  
        }) 
      }, 200);
    }

    if(this.componentIdentifier == 'route_violation_report'){
      setTimeout(() => {
        $('#dbselect_3').multipleSelect({
          width: 200,
          placeholder: "Select Route",
          filter: true,
          single: true,
          selectAll: false  
        }) 
      }, 100);
    }

    if(this.componentIdentifier == 'notification_master'){
      setTimeout(() => {
        $('#dbselect_notif').multipleSelect({
          width: 200,
          placeholder: "Select type",
          filter: true,
          // single: true,
          // selectAll: false  
        }) 

        $('#dbselectNotif').multipleSelect({
          width: 200,
          placeholder: "Select Vehicle",
          filter: true,
          // single: true,
          // selectAll: false  
        }) 
      }, 100);

    
    }


    // if(this.componentIdentifier == 'usersMaster'){
      
    //   $('#dbselectPhone').multipleSelect({
    //     width: 200,
    //     placeholder: "Customer Phone",
    //     filter: true,
    //     single: true,
    //     selectAll: false  
    //   }) 

    //   $('#dbselectName').multipleSelect({
    //     width: 200,
    //     placeholder: "Customer Name",
    //     filter: true,
    //     single: true,
    //     selectAll: false  
    //   }) 
    // }
    // var triggerReport = setTimeout(()=>{
    //   clearTimeout(triggerReport);
    //   var data = '';
    //   if(that.componentIdentifier != 'fuel_report_graph'){
    //     that.reportFilter(data);
    //   }
    
    // },200)
   
  }


  deviceArr = [];
  deviceFilterArr :any;
   reportFilter(data): void {
    this.deviceArr =  $('#dbselect').multipleSelect('getSelects','value'); 
    console.log('this.deviceArr',this.deviceArr);
    var that  = this;
     var filter = {
       fromDate : this.from_date,
       toDate : this.to_date,
       deviceArr : this.deviceArr
     }
     if (this.componentIdentifier == 'fuel_consumption_report') {
       filter['filter_type'] = this.filterRtype;
          var tempArr = [];
          // for(var i=0;i<this.options.length;i++){
          //   for(var j=0;j<this.deviceArr.length;j++){
          //     this.options[i].id=
          //   }
          // }
          var dataArr = this.options.filter(function (item) {  
            for(var i=0;i< that.deviceArr.length;i++){
              if(item.id == that.deviceArr[i]){   
                  return item;
                }             
            } 
          });
       
          filter.deviceArr = dataArr ; 
     }

     if(this.componentIdentifier === 'idle_report'){
      filter['minidleT'] = this.minIdleTime ; 
     }

     if(this.componentIdentifier === 'poi_report'){
      let poi_id =  $('#dbselect_1').multipleSelect('getSelects','value');
      filter['poi_id'] = poi_id ; 
     }

     
     if(this.componentIdentifier === 'stoppage_report'){
      let duration = [];
      duration =  $('#dbselect_2').multipleSelect('getSelects','value');
      filter['duration'] = duration ; 
     }

     if(this.componentIdentifier === 'route_violation_report'){
      let vroute = [];
      vroute =  $('#dbselect_3').multipleSelect('getSelects','value');
      var routeArr = this.routeArr.filter(function (item) {  
        if(item._id == vroute[0]){   
          return item;
        }             
    });
      filter['route'] = routeArr ; 
     }

     if(this.componentIdentifier === 'notification_master'){
      let notif_type = [];
      notif_type =  $('#dbselect_notif').multipleSelect('getSelects','value');

      filter.deviceArr =  $('#dbselectNotif').multipleSelect('getSelects','value');

      // var devIwner = this.notifDevArr.filter((u)=>{
      //   filter.deviceArr.
      // })
  
      filter['notitype'] = notif_type ; 
     }

      if(this.componentIdentifier === 'deviceList'){
        filter['liecenceStatus'] = this.liecenceStatus ;
        filter['distributerSelect'] = this.distributerSelect ;
  //       liecenceStatus="new"
  // distributerValue
      }

     if(this.componentIdentifier === 'usersMaster'){
      var userID = $('#dbselectPhone').multipleSelect('getSelects','value'); 
      var userID1 = $('#dbselectName').multipleSelect('getSelects','value'); 
      if((userID != undefined)&&(this.userFilterType == 'Phone')){
        filter['userId'] = userID;
      }
      if((userID1 != undefined)&&(this.userFilterType === 'Name')){
        filter['userId'] = userID1;
      }
        filter['deletedUser']  = this.deleteduser;
     }

     if((this.componentIdentifier === 'deviceMaster')||(this.componentIdentifier === 'gps_master') ||(this.componentIdentifier === 'deviceRenew')){
      var DID = $('#dbselectIMEI').multipleSelect('getSelects','value'); 
      if((this.componentIdentifier === 'deviceMaster')){
        var DID1 = $('#dbselectSIM').multipleSelect('getSelects','value'); 
      }else{
        var DID1 = $('#dbselectVehicleName').multipleSelect('getSelects','value'); 
      }
    
      if(((DID != undefined)&&(this.deviceFilterType == 'IMEI'))|| ((DID != undefined)&&(this.componentIdentifier === 'deviceRenew')) ){
        filter['deviceId'] = DID;
        filter['type'] = 'IMEI';
      }
      if((DID1 != undefined)&&(this.deviceFilterType === 'SIM')){
        filter['deviceId'] = DID1;
        if(this.componentIdentifier === 'deviceMaster'){
          filter['type'] = 'SIM';
        }else{
          filter['type'] = 'VNAME';
        }
    

      }
      console.log('this.deleteddevice',this.deleteddevice);
        filter['deletedDevice']  = this.deleteddevice;
        if(this.componentIdentifier === 'deviceRenew'){
          filter['type']=this.renewalType
        }
       
     }


    this.onReportFIlter.emit(filter);
}

reportFilter_billing(){
  var userObj =  $('#dbselect').multipleSelect('getSelects','value'); 
  var billingType = $('#dbselect_billtype').multipleSelect('getSelects','value'); 
  var billingStatus = $('#dbselect_billStatus').multipleSelect('getSelects','value'); 
  
  var filter = {
    date : this.modelDate,
    type : billingType,
    status : billingStatus,
    user :userObj
  }

  console.log(filter);

  this.onReportFIlter.emit(filter);
}


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

exportExel(){
  this.onReportFIlter.emit('getExcel');
}
geofenceArr = [];
getgeofence(){
  this.geofenceArr=[];
  this.contactService.getallgeofence(this.useridd).subscribe(
    data => {
      this.options = data ;
      for(var i = 0; i<this.options.length;i++){
        this.options[i]['selectedValue'] = this.options[i]._id;
        this.options[i]['value']  = this.options[i].geoname ; 
      }
      let that = this;
      setTimeout(()=>{
        that.loadropdown();
      },100)  
      console.log('this.options',this.options);
    });
}


getUser(){
  this.contactService.getDistributerList(this.useridd).subscribe(
    data => {
      console.log('data',data);
      this.options = data ;
      for(var i = 0; i<this.options.length;i++){
        this.options[i]['selectedValue'] = this.options[i]._id;
        this.options[i]['value']  = this.options[i].first_name + ' '  +  this.options[i].last_name; 
      }
      let that = this;
      setTimeout(()=>{
        that.loadropdown();
      },100)  
      console.log('this.options',this.options);
    });

}

route_detail_show=[];
poiArr=[];
getPOI(){
  // console.log("Mapping history !!!");
  this.contactService.getPOI(this.useridd)
  .subscribe(res=>{
  //   console.log("routedet",res);
    this.route_detail_show=res;

    var poiObj; 

    for(var i=0;i<this.route_detail_show.length;i++){
      poiObj ={
          poiname: this.route_detail_show[i].poi.poiname,
          id : this.route_detail_show[i]._id
        }

        this.poiArr.push(poiObj);
    }

  
    this.loadropdown();
  //   console.log("routeDetails=>",this.poiArr);
  },err=>{
    this.loadropdown();
  })
}

routeArr =[];

routeViolationArr(){
  var that =this;
  this.contactService.routeViolation(this.useridd).subscribe(
    res => {
      
      var route =[];
      this.routeArr =[];
      route = res;       
      for(let i=0;i<route.length;i++){      
          this.routeArr.push(route[i]);   
      }
        console.log(this.routeArr);

        setTimeout(()=>{
          that.loadropdown();
        },100)  
    });
  
}

modelDate:any=new Date();

onOpenCalendar(container) {
  var that= this;
  container.monthSelectHandler = (event: any): void => {
    container._store.dispatch(container._actions.select(event.date));
    console.log(that.modelDate);
  };     
    container.setViewMode('month');
   
 }

 censor_detail(){
  var deviceObj =  $('#dbselect').multipleSelect('getSelects','value'); 
 
  console.log(deviceObj);
  var filter = {
   device : deviceObj
  }

  console.log(filter);

  this.onReportFIlter.emit(filter);

 }

 userArr=[];
 notifDevArr=[];
 getAllUser(){
   var that = this;
   var userObj = {
    "draw": 1,
    "columns": [
      {"data": "_id"},
      {
        "data": "first_name"},
      { "data": "phone"},
      {"data": "last_name"},
    ],
    "order": [
      {
        "column": 0,
        "dir": "desc"
      }
    ],
    "start": 0,
    "length": -1,
    "search": {
      "value": "",
      "regex": false
    },
    "op": {},
    "select": [],
    "find": {
      "supAdmin": this.useridd,
      "DeletedUser": {
        "$exists": false
      }
    }
  }

  if(this.deleteduser === true){
        userObj.find.DeletedUser.$exists = true;
  }
  
  var suburl = "/users/datatable";
   that.contactService.post(suburl, userObj).subscribe(resp => {
     this.userArrFunc(resp);
   },err=>{
     console.log(err);

   })
 }

 userArrFunc(uOb){
  this.userArr=[];
  this.userArr = uOb.data;
  console.log('userArr',this.userArr);
  setTimeout(()=>{
    this.loadropdown();
    // $("#dbselectPhone").multipleSelect("disable");
  },100)  

 }


 getAllDevice(){
  
  var findObj={};
   if(this.custtype === true){
    findObj = {
      "$and" : [{"Dealer":this.useridd},{ "deletedDevice": {"$exists": this.deleteddevice}}]
    };
   }else{
    findObj = {
      "$and" : [{"supAdmin":this.useridd},{ "deletedDevice": {"$exists":  this.deleteddevice}}]
    };
   }



  var devObj = {
    "draw": 1,
    "columns": [
      {
        "data": "_id"
      },
      {
        "data": "Device_Name"
      },
     
    
      {
        "data": "Device_ID"
      },
  
      {
        "data": "sim_number"
      },
   
 
    ],
    "order": [
      {
        "column": 0,
        "dir": "asc"
      }
    ],
    "start": 0,
    "length": -1,
    "search": {
      "value": "",
      "regex": false
    },
    "op": {},
    "select": [],
    "find": findObj
  }

  // if(this.deleteddevice === true){
  //   console.log("devObj.find['findObj']",devObj.find['findObj']);
    
  //   devObj.find['$and'][1]['deletedDevice']['$exists'] = true;
  // }
  console.log('devObj.find',devObj.find);

  var suburl = "/devices/datatable";
 
  this.contactService.post(suburl, devObj).subscribe(resp => {
    console.log('device api respoonse=>',resp);
    this.deviceArrFunc(resp);
  })

 }
 getDeviceForNotif(){
  
  var findObj={};
   if(this.custtype === true){
    findObj = {
      "$and" : [{"Dealer":this.useridd},{ "deletedDevice": {"$exists": this.deleteddevice}}]
    };
   } else if(this.superAdmin === true){
    findObj = {
      "$and" : [{"supAdmin":this.useridd},{ "deletedDevice": {"$exists":  this.deleteddevice}}]
    }
   }else{
    findObj = {
      "$and" : [{"user":this.useridd},{ "deletedDevice": {"$exists":  this.deleteddevice}}]
    }
   }


  var devObj = {
    "draw": 1,
    "columns": [
      {
        "data": "_id"
      },
      {
        "data": "Device_Name"
      },
     
    
      {
        "data": "Device_ID"
      },
  
      {
        "data": "sim_number"
      },
      {
        "data": "user"
      },
   
 
    ],
    "order": [
      {
        "column": 0,
        "dir": "asc"
      }
    ],
    "start": 0,
    "length": -1,
    "search": {
      "value": "",
      "regex": false
    },
    "op": {},
    "select": [],
    "find": findObj
  }

  // if(this.deleteddevice === true){
  //   console.log("devObj.find['findObj']",devObj.find['findObj']);
    
  //   devObj.find['$and'][1]['deletedDevice']['$exists'] = true;
  // }
  console.log('devObj.find',devObj.find);

  var suburl = "/devices/datatable";
 
  this.contactService.post(suburl, devObj).subscribe(resp => {
    console.log('device api respoonse=>',resp);
    this.deviceArrFunc1(resp);
    // notifDevArr
  })

 }



 deviceArr_1:any=[]
 deviceArrFunc(dOb){
  this.deviceArr_1=[];
  this.deviceArr_1 = dOb.data;
  console.log('deviceArr_1',this.deviceArr_1);
  var that= this;
  setTimeout(()=>{
    that.loadropdown();
   
  },100)  

 }

 deviceArrFunc1(dOb){
  this.notifDevArr=[];
  this.notifDevArr = dOb.data;
  console.log('deviceArr_1',this.deviceArr_1);
  var that= this;
  setTimeout(()=>{
    that.loadropdown();
   
  },100)  

 }
 userRadioButton(){
  console.log('userFilterType',this.userFilterType);
  // userRadio= ['Phone', 'Name'];
  // deviceRadio= ['IMEI','SIM'];
  if(this.userFilterType === 'Phone'){
    $("#dbselectPhone").multipleSelect("disable");
    $("#dbselectName").multipleSelect("enable");
  }
  if(this.userFilterType === 'Name'){
   
    $("#dbselectName").multipleSelect("disable");
    $("#dbselectPhone").multipleSelect("enable");
  }

 }


 deviceRadioButton(){
  console.log('userFilterType',this.deviceFilterType);
  if(this.deviceFilterType === 'IMEI'){
    $("#dbselectIMEI").multipleSelect("disable");
    $("#dbselectSIM").multipleSelect("enable");
  }
  if(this.deviceFilterType === 'SIM'){
    $("#dbselectSIM").multipleSelect("disable");
    $("#dbselectIMEI").multipleSelect("enable");
  
  }
 }
 userDeleted(ev){
   console.log('event=>',ev);
   this.deleteduser = ev.checked ;
      this.getAllUser();
 }

 deletedDevices(ev1){
   this.deleteddevice = ev1.checked ;
   this.getAllDevice();
 }

//  callMethod(id) {
  
//   if(id == 'grouped'){
//     $("#dbselect").multipleSelect("disable");
   
//   }else{
//     $("#dbselect").multipleSelect("enable");
//   }

// }


notificationArr= [
  {view:'Overspeed',value:'overspeed'}, {view:'Ignition',value:'IGN'}, {view:'Point of intrest',value:'Route'}, {view:'Geofence',value:'Geo-Fence'}, {view:'Maxstoppage',value:'MAXSTOPPAGE'}, {view:'Fuel',value:'Fuel'}, {view:'AC',value:'AC'}, {view:'Route POI',value:'route-poi'}, {view:'Power',value:'power'}, {view:'Panic button',value:'SOS'}, {view:'Relay',value:'immo'},{view:'Parking',value:'theft'}
]

getSuperAdminList(){
    console.log("KJDKJDKJKDJKJKDJD");
    
    this.contactService.getSuperAdminList().subscribe(res=>{
      console.log(res);
      this.distributers=res;
       var loadinguser1 = {
              user_type: "All",
              _id: "All User"
            }
            for(var i=0;i<this.distributers.length;i++){
              loadinguser1 = {
                user_type:  this.distributers[i].first_name + " " + this.distributers[i].last_name,
                _id: this.distributers[i]._id
              }
              this.disDataFIlter.push(loadinguser1);
            }
      
    })
  }

  distributerSelect = [];
  filterStates(usr1) {
    // console.log("userObj=>",usr);
    if(usr1.length == 0){
      this.distributerSelect =[];
    }
    
    if (usr1) {
      console.log("user=>",usr1);
      const filterdealerValue:any = usr1;
      this.distributerSelect=[];
       this.distributerSelect = this.disDataFIlter.filter(function(ppp){
       console.log(ppp);
       
        var t = ppp.user_type.toLocaleLowerCase().indexOf(filterdealerValue.toLocaleLowerCase());
      //  this.option = this.options[i];
      console.log("India1");
        return t > -1;    
      });
        console.log(this.distributerSelect);
        // if(this.distributerSelect.length==this.disDataFIlter.length){
        //   this.getdev()
        // }
        if(this.distributerSelect.length === 1){
          // this.getSuperAdminVehicles(this.distributerSelect);

        }else{
          // this.getdev()
        }
        return this.distributerSelect;
    }
  
  }

 licenceStatus(ev){
    console.log(this.liecenceStatus,ev);
    // this.getdev();
    
  }

  selectMonth(month){
    console.log(month);
    var date=new Date("1/"+month.value+"/"+moment().year());
    console.log(new Date(date));
    
     var md = new Date(moment().startOf('month').format());
     var ed= new Date(moment().endOf('month').format());
    this.from_date=new Date(md.setMonth(month.value));
    this.to_date=new Date(new Date(ed.setMonth(month.value)));
    console.log(this.to_date.getMonth(),this.to_date.getMonth()!=(month.value+1));
    
    if(!(this.to_date.getMonth()==(month.value+1))){
      console.log(this.to_date.getMonth(),month);
      
    }else{
      this.to_date.setDate(this.to_date.getDate()-this.to_date.getDate())
      console.log("IN ELSE",this.to_date);
      
    }
    // this.to_date.setDate(this.to_date.getDate()-1)

    // console.log(new Date(this.to_date.getFullYear(), date.getMonth(), 0).getDate())
    console.log("startDate=",md.toISOString(),ed.toISOString());
    // this.to_date = new Date();
    
  }

}



