import { Component, OnInit,Inject } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import {Device} from '../../device';
import {ContactService} from '../../contact.service';
import { SidebarComponent } from '../../sidebar/sidebar.component';
import { FlashMessagesService } from 'angular2-flash-messages';
declare var _ :any;
declare var swal: any;
@Component({
  selector: 'app-device-edit',
  templateUrl: './device-edit.component.html',
  styleUrls: ['./device-edit.component.scss'],
  providers: [ContactService,SidebarComponent]

})
export class DeviceEditComponent implements OnInit {
dealers_info: any[];
RTO;
RTOObj;
RTOSelect=[]
myInput;
installer
installerSelect
sellsPerson
  chassisno:any;
  companyName:any;
  EngineNo:any;
  companyAddress:any;
  typeofVeh:any;
  transportOfficeCity:any;
  transportOfficeState:any;
  manufacturingCompany:any;
  invoice_date:any
  invoice_number:any;
  UIDnumber:any;
  iccidNo:any;
  Imsi:any;
  dev: any;
  deviceModel:any;
  deviceId: any;
  group_info: any;
  dname:any;
  SIM_provider:any;
  desc:any;
  IntegrationId:any;
  sim:any;
  devices: Device[];
  device: Device;
  voltage_tank_empty:any;
  id:any;
  totalODO:any;
  iconType:any;
  fuel_tank_capicity:any;
  neww:any;
  speed:any;
  dcontact:any;
  drname:any;
  vehRegDate:any;
  vehManufacturingYear :any;
  lastFitnessDate : any;
  fitmentDate :any;
  vehicleType:any;
  userModel:any;
  tankfull_capicity:any;
  groupInfo:any;
  device_Id:any;
  date=new Date();
  expDate = new Date(this.date.getFullYear()+1,this.date.getMonth(), this.date.getDate()).toLocaleString();
  foodds = [
    {value: 'car', viewValue: 'Car'},
    {value: 'bike', viewValue: 'Bike'},
    {value: 'truck', viewValue: 'Truck'},
  ];
  model: any;
  integrationIdPresent:boolean=false
  mainmodel: any;
  custId: string;
  deviceInformation: any={};
  dev_IMEI: any;
  SIM_provider2: any;
  sim2: any;
  CIDNO: any;
  numberOfSOS: any;
  tpin:any;
  epin:any;
  models:any;
  colour:any;
  transmission:any;
  dealerStatus: any;
  superAdmin: any;
  superadminAccess: string;
  Cloned_exp_date: string;
  organisation: any;
  dealerData={fullName:'',_id:''}
  dealerSelect: any[];
   skip: number = 1;
  limit: number = 100;
showFieldsDealer:boolean=false;
    showFieldsUser:boolean=false;
  License:any;
  DealerId: any;
  mainData
  showRenewButton:boolean=false
  deviceDistanceVariation=0
  selcetedSign="+"
  installerData: any;
  installerObj: any;
  custtype: any;
  constructor(public dialogRef: MdDialogRef<DeviceEditComponent>,private _flashMessagesService: FlashMessagesService,
    @Inject(MD_DIALOG_DATA) public data: any,private contactService: ContactService,private sidebar: SidebarComponent) {
      //  console.log('data=>',data);
       this.mainData=data

       if(data.distanceVariation){
          this.selcetedSign=data.distanceVariation[0]
          // data.distanceVariation.slice(0,0);
  this.deviceDistanceVariation=data.distanceVariation.substring(1);
  console.log("___________",this.mainData,this.selcetedSign,this.deviceDistanceVariation);

       }
  
    
  this.dname = data.dname;
  this.DealerId=data.devObj.Dealer?data.devObj.Dealer._id?data.devObj.Dealer._id:data.devObj.Dealer:data.devObj.Dealer;
  if(data.devObj.License =="Yearly"){
    this.showRenewButton=true;
  }
  if(data.assigned_to){
    this.selectedUser = data.assigned_to._id;
  }
 
  this.desc = data.des;
  this.expDate = data.expdate;
  this.Cloned_exp_date = data.expdate ; 
  this.License = data.devObj.License;
  this.sim = data.sim;
  this.sim2 = data.simNUM2;
  this.id = data._id;
  this.drname = data.drname;
  this.dcontact = data.dcontact ;
  this.speed = data.maxSpeed; 
  this.deviceModel = data.mainmodel;
  this.userModel = data.assigned_to;
  this.vehicleType = data.vehicleType;
  this.dev_IMEI = data.devIMEI;
  this.SIM_provider = data.S_provider;
  this.SIM_provider2 = data.simProvider2;
  this.IntegrationId = data.itiId;
  if(this.IntegrationId){
    this.integrationIdPresent=true
  }
  this.totalODO = parseFloat(data.tot_ODO).toFixed(1);
 
  
  this.EngineNo=data.devObj.engineNo;
 
  this.typeofVeh=data.devObj.typeOfVehicle;
  this.companyName=data.devObj.companyName;
  this.companyAddress=data.devObj.companyAddress;
  this.transportOfficeCity=data.devObj.transportOfficeCity;
  this.transportOfficeState= data.devObj.transportOfficeState;
  this.manufacturingCompany= data.devObj.manufacturingCompany;
  this.numberOfSOS = data.devObj.numberOfSOS ;
  this.invoice_date= "";
  this.chassisno=data.devObj.ChassisNo;
  this.invoice_number=data.devObj.invoiceNumber;
  this.UIDnumber=data.devObj.uniqueID;
  this.iccidNo=data.devObj.ICCICD;
   this.Imsi = data.devObj.IMSI ;
   this.CIDNO = data.devObj.CID_No;
   console.log("TPIN--",data.devObj.tpin);
   
   if(data.devObj.tpin){
     this.tpin=data.devObj.tpin
   }
   if(data.devObj.epin){
     this.epin=data.devObj.epin
   }
   if(data.devObj.model){
     this.models=data.devObj.model
   }
    if(data.devObj.transmission){
     this.transmission=data.devObj.transmission
   }
    
    if(data.devObj.colour){
     this.colour=data.devObj.colour
   }
   if(data.devObj.invoiceDate){
     this.invoice_date = new Date(data.devObj.invoiceDate);
   }
   if(data.devObj.fitmentDate){
     this.fitmentDate = new Date(data.devObj.fitmentDate);
   }
   if(data.devObj.lastFitnessDate){
     this.lastFitnessDate = new Date(data.devObj.lastFitnessDate);
  }
  if(data.devObj.vehicleRegDate){
    this.vehRegDate = new Date(data.devObj.vehicleRegDate)
  }
  if(data.devObj.vehicleManufacturingDate){
    this.vehManufacturingYear = new Date(data.devObj.vehicleManufacturingDate);
  }

   if(data.sellsPerson){
    this.sellsPerson =data.sellsPerson
  }

  //  if(data.installer){
  //   this.installer =data.installer._id
  // }

  if(data.installer!=undefined){
    this.installer= data.installer.first_name+" "+data.installer.last_name;
    this.installerObj=data.installer._id
    // {
    //   fullName:data.installer.first_name+" "+data.installer.last_name ,
    //   _id:data.installer._id   
    // }
    // data.assigned_to;
 }


 
  // console.log("deviceId=>",this.id);
 if(data.assigned_to==undefined){
   this.userModel ={
     user_type:"",
     _id:""
   }
 }else{
    this.userModel= {
      user_type:data.assigned_to.first_name+" "+data.assigned_to.last_name ,
      _id:data.assigned_to._id   
    }
    // data.assigned_to;
 }

 if(data.vehicleType==undefined){
  this.vehicleType ={
    veh_type:"",
    _id:""
  }
}else{
   this.vehicleType= {
    veh_type:data.vehicleType.brand+" "+data.vehicleType.model ,
    _id:data.vehicleType._id    
   }
  //  data.vehicleType;
}

  if(data.mainmodel==undefined){
    this.deviceModel={
      device_type:"",
      _id:""
    }
    }else{

      this.deviceModel = {
        device_type:data.mainmodel.device_type,
        _id:data.mainmodel._id
      }
      data.mainmodel;
    }

  
  
  // console.log(this.speed);
  for(let r=0;r<this.foodds.length;r++){
    if( data.iconType == this.foodds[r].value){
       this.neww = this.foodds[r];
    }
  }
 
 // this.neww.viewValue = data.iconType;
  this.speed = data.speed
    // console.log(data)
     }
    onNoClick(a): void {
      this.dialogRef.close(a);
     }

  

     errorField = false;
    
     editRecord(){


     if(this.groupInfo==undefined){
      this.device_Id="";
     
     }else{
      this.device_Id=this.groupInfo.devId;
     }

      // console.log(this.device_Id);
      // console.log(this.groupInfo);


      let currDate = new Date().getTime();
      let chkDate = new Date(this.expDate).getTime();

      console.log(currDate,chkDate);
    
      console.log(currDate,chkDate);

      if(currDate>chkDate){
        console.log('expiration date should not be greater then current date');
        swal(
          'Expiration Date Error',
          'Expiration date should not be greater then current date',
          'error'
        ) 
        // let error = "dateError" 
        // this.tost1(error);
        this.errorField =true;

      }else{  

        // console.log(this.device_Model);
        // console.log(this.userModel);
        // console.log(this.vehicleType);

        let cust;
        var outerThis=this;
        var model =  _.find(this.newArr, function(o) { 
          if(o._id ==outerThis.deviceModel._id){
            return o;
          } 
        });

        // let user2 =  _.find(this.newUserArr, function(p) { 
        //   if(p._id ==outerThis.userModel._id){
        //     return p;
        //   } 
        // });

      
        let vType =  _.find(this.vehName, function(q) { 
          if(q._id ==outerThis.vehicleType._id){
            return q;
          } 
        });

       
        if(this.dataSelect2.length!=0){
          console.log("==",this.dataSelect2[0]._id,model);
          
          this.deviceInformation.device_model=this.dataSelect2[0]._id
        }else{
           this.deviceInformation.device_model = model._id
        }

        if(this.dataSelect1.length!=0){
          vType=this.dataSelect1[0]._id
        }else{
           this.deviceInformation.vehicleType = vType._id
        }

        // console.log("userObj=>",this.dataSelect);

        if (this.dataSelect.length!=0) {
        
          cust = this.dataSelect[0]._id;

        }else{
          
          cust = this.custId;
        }
        this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
        // if(user2==undefined){
        //   cust = this.custId;
        // }else{
        //   cust= user2._id;
        // }
    
        // console.log("costumerDetail=>",cust);
        if (this.custtype == true) {
          var owner = this.useridd;
        } else {
          var owner = this.useridd;
        }
        this.deviceInformation = {
          _id: this.id,
          devicename: this.dname,
          des: this.desc,
          sim: this.sim,
          deviceid: this.dev_IMEI,
          // iconType:this.neww.value,
          speed: this.speed,
          user: cust,
          drname: this.drname,
          dphone: this.dcontact,
          vehicleGroup: this.device_Id,
          updatedBy: owner,
          device_model: this.device_type?this.device_type:this.deviceModel._id,
          vehicleType:this.vehicle_Type?this.vehicle_Type:this.vehicleType._id,
          Dealer:this.DealerId,
           deviceDistanceVariation:this.selcetedSign+(this.deviceDistanceVariation?this.deviceDistanceVariation:'0')
        // tpin:this.tpin,
        // epin:this.epin
        }

        // expdate: new Date(this.expDate)
        // var ed = new Date(this.expDate);
        // var ced = new Date(this.Cloned_exp_date);       
        //  var difference = ed.getTime() - ced.getTime()  ;
        //  var hour = (difference / (60 * 60 * 1000));
        //  var diff_hr = Math.round(hour);
        //  console.log('diff_hr',diff_hr);
        //  if (diff_hr > 24) {
          let rnw_by;
          this.deviceInformation['expdate'] =  new Date(this.expDate) ;    
           let sAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
           let orgName = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isOrganisation ; 
           let s_Admin = localStorage.getItem('superadmin');
          //  superAdminToken
          console.log('sAdmin',sAdmin);
          console.log('orgName',orgName);
       
           if((sAdmin === true)||(orgName === true)||(s_Admin === 'ON')){
            this.deviceInformation['renew_by']  = this.useridd; 
          
           }else{ 
             console.log("In Else block");
                
            let sAdminId = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._id ;      
            this.deviceInformation['renew_by'] = sAdminId;
           
           }     
          // }
          if(this.tpin){
          this.deviceInformation['tpin'] = this.tpin;
        }
         if(this.epin){
          this.deviceInformation['epin'] = this.epin;
        }
         if(this.colour){
          this.deviceInformation['colour'] = this.colour;
        }
        if(this.transmission){
          this.deviceInformation['transmission'] = this.transmission;
        }
        if(this.models){
          this.deviceInformation['models'] = this.models;
        }

        if(this.integrationIdPresent){
          this.deviceInformation['integrationId'] = this.IntegrationId;
        }else{
          if(this.IntegrationId)
          this.deviceInformation['integrationId'] = this.IntegrationId;
        }

        if(this.sim2 == undefined){
          this.deviceInformation;
        }else{
          this.deviceInformation['sim_number2'] = this.sim2;
        }
        if(this.SIM_provider2 == undefined){
          this.deviceInformation;
        }else{
          this.deviceInformation['sim_provider2'] = this.SIM_provider2;
        }

        if(this.EngineNo){
          this.deviceInformation['engineNo'] = this.EngineNo;
        }
  
        if(this.CIDNO){
          this.deviceInformation['CID_No'] = this.CIDNO;
        }
        if(this.typeofVeh){
          this.deviceInformation['typeOfVehicle'] = this.typeofVeh;
        }
        
        if(this.manufacturingCompany){
         this.deviceInformation['manufacturingCompany'] = this.manufacturingCompany;
        }
        if(this.UIDnumber){
          this.deviceInformation['uniqueID'] = this.UIDnumber;
        }
        if(this.iccidNo){
          this.deviceInformation['ICCICD'] = this.iccidNo;
        }
        if(this.Imsi){
          this.deviceInformation['IMSI'] = this.Imsi;
        }
  
        if(this.vehRegDate){
          this.deviceInformation['vehicleRegDate'] = new Date(this.vehRegDate);  
        }
  
        if(this.vehManufacturingYear){  
          this.deviceInformation['vehicleManufacturingDate'] = new Date(this.vehManufacturingYear);
        }
  
        if(this.lastFitnessDate){
          this.deviceInformation['lastFitnessDate'] = new Date(this.lastFitnessDate);
        }
  
        if(this.fitmentDate){
          this.deviceInformation['fitmentDate'] = new Date(this.fitmentDate);
        }

        if(this.invoice_date){
          this.deviceInformation['invoice_date'] = this.invoice_date;
        }
        if(this.chassisno){
          this.deviceInformation['ChassisNo'] =this.chassisno

        }
        if(this.invoice_number){
          this.deviceInformation['invoiceNumber'] = this.invoice_number

        }

        if(this.companyName){
          this.deviceInformation['companyName'] = this.companyName;
        }
        if(this.companyAddress){
          this.deviceInformation['companyAddress'] = this.companyAddress;
        }
        if(this.transportOfficeCity){
          this.deviceInformation['transportOfficeCity'] = this.transportOfficeCity;
        }
        if(this.transportOfficeState){
          this.deviceInformation['transportOfficeState'] = this.transportOfficeState;
        }

        if(this.numberOfSOS){
          this.deviceInformation['numberOfSOS'] = this.numberOfSOS;
        }
        // if(user2){
        //   this.deviceInformation.user = cust;
        // } 
        // console.log(this.deviceInformation.user);
        if(this.SIM_provider==undefined){
          this.deviceInformation;
        }else{
          this.deviceInformation.sim_provider = this.SIM_provider;
        }      

        if(this.totalODO){
          this.deviceInformation.total_odo= this.totalODO
        }

       if(this.sellsPerson){
        this.deviceInformation['sellsPerson']=this.sellsPerson;
      }
      if(this.installerObj){
         this.deviceInformation['installer'] =this.installerObj
      }
      if(this.groupInfo){
        this.deviceInformation['groupName'] =this.groupInfo.GroupName
      }
        
    console.log("INFO==",this.deviceInformation);
        this.contactService.editdevice(this.deviceInformation)
        .subscribe(device => {
          window.localStorage['DataUpdate'] = 'True'
          this.sidebar.sidebarData()
          this.onNoClick("done");
           this.devices.push(device);   
           }, (err: any) => { 
             if(err.status==401){
               swal(
                 "Access Denied !!"
               )
             }else{
               var errorMsgShow = "Internal Server Error, Please try after Sometime !!!"
               var ErrorMsgHead = "Server Error";
                 var errormsg = JSON.parse(err._body).errmsg.split(':')[2] ; 
                 if(errormsg){
                    errorMsgShow = errormsg ; 
                    ErrorMsgHead = "Duplicate Entry" ;
                    console.log("handle Error =>",errormsg);
                 }
                 this._flashMessagesService.show(errorMsgShow, { cssClass: 'alert-warning', timeout: 2000 });
                 swal(
                   'Duplicate IMEI',
                   "Device IMEI is already used",
                   'error'
               )     

             }

          
        }
      );
      } 

     }
     groups=[]
     useridd:any;
     getDealerId:any;
    
  ngOnInit() {
     console.log('data=>',this.mainData);
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id; 
    this.getDealerId = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).Dealer_ID ;
    this.custId = localStorage.getItem('custId');
    this.dealerStatus = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.organisation = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isOrganisation
    this.superadminAccess = localStorage.getItem('superadmin');
    // console.log("costumerID=>",this.custId);
    this.groups=[];
    this.contactService.getGroup(this.useridd).subscribe(      
      res => {
        // console.log("grpDetails=>",res);

        this.group_info = res["group_details"];
        // console.log(this.group_info.length);
 
        for(var i = 0;i<this.group_info.length;i++) {
          let group_logs = this.group_info[i];
          // console.log(group_logs);
          let group_name = group_logs.name;
          let status = group_logs.status;
          let date = new Date(group_logs.last_modified);
          let d = date.toLocaleDateString();
          this.deviceId = group_logs._id;
     

          this.groups.push({
            "GroupName":group_name,
            "Status":status,
            "created_date":d,
            "Vehicles":this.dev,
            "devId":this.deviceId,        
          })
        }
      }); 


      this.getDeviceModel();
      this.getvehDetail();
      this.getUser();
      this.dealerDetail() 
      this.getInstallerData();
      this.getRTOData()
      if(this.superAdmin){
        
        // var isSUP= JSON.parse(window.atob(window.localStorage.Dealer_token.split('.')[1])).isSuperAdmin
        // console.log("IISNSJKNSKJ",isSUP,JSON.parse(window.atob(window.localStorage.Dealer_token.split('.')[1])));
        this.showFieldsDealer=true
           this.showFieldsUser=true; 

      }else if((!localStorage.getItem('superadmin')) || 
       (localStorage.getItem('superadmin')=='ON' && localStorage.getItem('Dealer')=='OFF' && localStorage.getItem('Custumer')=='OFF') 
       ||(localStorage.getItem('superadmin')=='ON' && localStorage.getItem('Dealer')=='OFF' && localStorage.getItem('Custumer')=='OFF') )
      {
            this.showFieldsDealer=true
           this.showFieldsUser=true; 
      }else if(((localStorage.getItem('superadmin')=='ON' || (!localStorage.getItem('superadmin'))) && localStorage.getItem('Dealer')=='ON' && localStorage.getItem('Custumer')=='OFF' || (!localStorage.getItem('Custumer'))) )
      {
          this.showFieldsDealer=false
           this.showFieldsUser=true; 
      }else if(this.superAdmin==true && this.dealerStatus==true){
         this.showFieldsDealer=true;
           this.showFieldsUser=true; 
      } else if(this.superAdmin==false && this.dealerStatus==true){
         this.showFieldsDealer=false;
           this.showFieldsUser=true; 
      }else{
         this.showFieldsDealer=false;
           this.showFieldsUser=false; 
      }
  }
  newArr=[]
  device_Model:any;
    getDeviceModel(){
  
      this.contactService.getDevModel()
      .subscribe(res=>{
        // console.log("abinash")
          console.log(res);
          this.device_Model=res;
          // console.log( "thisisdeviceModel",this.device_Model);
          let dummyData=[]
          for(var i=0;i<this.device_Model.length;i++){
            var loadingObj={
              device_type:this.device_Model[i]?this.device_Model[i].device_type:"NA",
              _id:this.device_Model[i]?this.device_Model[i]._id:"NA"    
            }
            dummyData.push(loadingObj);
          }
          this.newArr=_.cloneDeep(dummyData)
         
      })
      // console.log(this.newArr);
    }
    data_descip:any;

    tost1(divid){
      if(divid == "dateError"){
        this.data_descip = "Expiration date must be greater than current date!!!";
        launch_toast();
      }
        function launch_toast() {
    
         // console.log(divid);
          var x = document.getElementById("toast")
          //console.log(x);
          x.className = "show";
          setTimeout(function(){ x.className = x.className.replace("show", ""); }, 2500);
      }
       }
      
       costumers:any; 
       newUserArr=[];
       dummyuserData=[];
       getUser(){
    this.costumers=[]
        console.log(this.DealerId);
        
        var passDealer;
        if(this.DealerId !=undefined){
          passDealer=this.DealerId._id?this.DealerId._id:this.DealerId
        }else if(this.getDealerId !=undefined){
           passDealer = this.getDealerId._id;
        }else{
          passDealer = this.useridd;
        }
          console.log(passDealer);
         this.contactService.getContactsbyDealer(passDealer)
         .subscribe(res=>{
           console.log("Alluserobject",res);
           this.costumers = res;
          //  console.log(this.costumers)
            this.dummyuserData=[]
           for(var i=0;i<this.costumers.length;i++){
             var loadinguser={
              user_type:this.costumers[i].first_name+" "+this.costumers[i].last_name ,
               _id:this.costumers[i]._id    
             }               
             this.dummyuserData.push(loadinguser);
           }
           console.log('this.dummyuserData',this.dummyuserData);
    

          //  this.selectedUser = 
          //  this.newUserArr=_.cloneDeep(dummyuserData)

         },err=>{
           this.dataSelect=[]
            this.costumers=[]
         })
       }

       dataSelect=[];
       dataSelect1=[];
       dataSelect2=[];
       option:any;
       selectedUser:any;
       vehicle_Type:any;
       device_type:any
  filterStates(val) {
    console.log(val)
    // console.log(this.dummyuserData)
    if (val) {
      const filterValue: any = val.user_type ; 
      this.dataSelect = this.dummyuserData.filter(function (d) {
    // console.log("inside Search Method=>",d);
        return d.user_type.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase()) > -1;
      });
      return this.dataSelect;
    }
    
    console.log("searched user=>",this.dataSelect);
  }

filterStatess(val) {
    console.log("===>",val)
    if (val) {
      const filterValue: any = val.veh_type ; 
      this.dataSelect1 = this.vehName.filter(function (d) {
    // console.log("inside Search Method=>",d);
        return d.veh_type.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase())>-1;
      });
      if(this.dataSelect1.length!=0){
        this.vehicle_Type=this.dataSelect1[0]._id
        console.log("searched vehical=>",this.dataSelect1,"----------",this.vehicle_Type);
      }
      return this.dataSelect1;
    }

  }

  
  
filterStates1(val) {
  console.log("===>",val)
    if (val) {
      const filterValue: any = val.device_type ; 
      this.dataSelect2 = this.newArr.filter(function (d) {
        // console.log("inside Search Method=>",d);
        return d.device_type.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase())>-1;
      });
      if(this.dataSelect2.length!=0){
        for(var i=0;i<this.dataSelect2.length;i++){
          if(val.device_type==this.dataSelect2[i].device_type){
            this.device_type=this.dataSelect2[i]._id
          }
        }
        console.log("searched model=>",this.dataSelect2,"----------",this.device_type);
      }
      return this.dataSelect2;
    }
  }
  filtergrpStatess12(val) {
  console.log(val)
  if (val) {
// this.userDetail=undefined
    const filtergrpValue:any = val;

    this.installerSelect=[];
     this.installerSelect = this.installerData.filter(function(g){
      var c = (g.first_name).toLocaleLowerCase().indexOf(filtergrpValue.toLocaleLowerCase());
    //  this.option = this.options[i];
    console.log("TESTINg",c)
      return c > -1;    
    });
    if(this.installer){
      for(let i=0;i<this.installerData.length;i++){
        if(this.installerData[i].fullName==this.installer){
          this.installerObj=this.installerData[i]._id
          console.log(this.installerData[i]);
          
          // this.getUser(this.installerData[i]._id)
        }
      }
    }
      console.log(this.installerSelect,this.installer, this.installerObj);
      return this.installerSelect;
  }

}

  // filterStatess2(val) {
  //   console.log("===>",val)
  //   if (val) {
  //     const filterValue: any = val; 
  //     this.dataSelect1 = this.installerData.filter(function (d) {
  //   // console.log("inside Search Method=>",d);
  //       return d.veh_type.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase())>-1;
  //     });
  //     if(this.dataSelect1.length!=0){
  //       this.vehicle_Type=this.dataSelect1[0]._id
  //       console.log("searched vehical=>",this.dataSelect1,"----------",this.vehicle_Type);
  //     }
  //     return this.dataSelect1;
  //   }

  // }

// filterStates1(val) {
//     console.log("===>",val)
//     if (val) {
//       const filterValue: any = val.device_type ; 
//       this.dataSelect2 = this.newArr.filter(function (d) {
//     // console.log("inside Search Method=>",d);
//         return d.device_type.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase())>-1;
//       });
//       if(this.dataSelect2.length!=0){
//       this.device_type=this.dataSelect2[0]._id
//       console.log("searched model=>",this.dataSelect2,"----------",this.device_type);
//     }
//       return this.dataSelect2;
//     }
//   }
  filtergrpStates3(val) {

  console.log(val)
  // console.log(this.options)
 this.userModel.user_type=undefined
  if (val) {

    const filtergrpValue:any = val;

    this.dealerSelect=[];
     this.dealerSelect = this.dealers_info.filter(function(g){
      var c = (g.first_name).toLocaleLowerCase().indexOf(filtergrpValue.toLocaleLowerCase());
    //  this.option = this.options[i];
      return c > -1;    
    });
    console.log(this.dealerData);
    
    for(let i=0;i<this.dealers_info.length;i++){
      if(this.dealers_info[i].fullName==this.dealerData.fullName){
        console.log(this.dealers_info[i]._id);
        
        this.DealerId=this.dealers_info[i]._id
        this.getUser();
      }
    }
    return this.dealerSelect;
  }

}
dealerDetail() {
   
   console.log("Inside function",this.useridd, this.skip, this.limit,this.myInput,null);
  
 this.contactService.dealer_Info1(this.useridd, this.skip, this.limit,this.myInput,null)    
   .subscribe((res:any) => {
        this.dealers_info = res;
        this.DealerId=this.data.devObj.Dealer?this.data.devObj.Dealer._id:this.data.devObj.Dealer
        if(res.length!=0){
              for(let i=0;i<res.length;i++){
                  if(res[i]._id==this.DealerId){
                  this.dealerData.fullName=res[i].first_name+' '+res[i].last_name;  
                  this.dealerData._id=res[i]._id;                
                }
                this.dealers_info[i].fullName=this.dealers_info[i].first_name+this.dealers_info[i].last_name

              }
              console.log('DEALER DATA', this.dealerData);
              
              // for(let i=0;i<this.dealers_info.length;i++){

              // }
        }
      }, err => {
        this.dealers_info=[];
        
      })

  }
  

       vehData:any;
       dummyVehData=[]
       vehName = [];
       getvehDetail(){
         this.contactService.getvehType(this.useridd)
           .subscribe(res=>{
            //  console.log(res);
             this.vehData=res;
             this.dummyVehData = [];
            //  console.log("allveh",this.vehData);
             for(var i=0;i<this.vehData.length;i++){
              var loadingVehType={
                veh_type:this.vehData[i].brand+" "+this.vehData[i].model ,
                _id:this.vehData[i]._id    
              }
            
              this.dummyVehData.push(loadingVehType);
            }
            this.vehName=_.cloneDeep(this.dummyVehData);
 

          
           })
       }


       getDevmodel(ev){
        //  console.log(ev);
       

       }

       getVehdata(evVh){
          // console.log(evVh)
       }


       getUserdata(evUser){
        //  console.log(evUser);

       }
selectDealer(value){
  if(value){  
  this.DealerId=value
  console.log("value",this.DealerId);
  this.getUser();
  }
  
}
renew(){
  console.log(this.mainData);
  
}

getInstallerData(){
  this.contactService.getTechnician(this.useridd, this.skip, this.limit,this.myInput,false).subscribe(
    (res:any)=>{
      this.installerData=res;
       for(let i=0;i<this.installerData.length;i++){
          this.installerData[i].fullName=this.installerData[i].first_name+' '+this.installerData[i].last_name;
        }
    })
}
 RTOData
  getRTOData(){
    this.contactService.get('/RTO_master/get').subscribe((res:any)=>{
      this.RTOData=res
    })
  }

filtergrpStatess2(val) {
  console.log(val)
  if (val) {
// this.userDetail=undefined
    const filtergrpValue:any = val;

    this.RTOSelect=[];
     this.RTOSelect = this.RTOData.filter(function(g){
     
      var c = (g.RTO_Code).toLocaleLowerCase().indexOf(filtergrpValue.toLocaleLowerCase());
    //  this.option = this.options[i];
    console.log("TESTINg",c)
      return c > -1;    
    });
    if(this.RTO){
      for(let i=0;i<this.RTOData.length;i++){
        if(this.RTOData[i].RTO_Code==this.RTO){
          this.transportOfficeCity=this.RTOData[i].city;
          this.transportOfficeState=this.RTOData[i].state

          this.RTOObj=this.RTOData[i]._id
          console.log(this.RTOData[i]);
          
          // this.getUser(this.RTOData[i]._id)
        }
      }
    }
      console.log(this.RTOSelect,this.RTO, this.RTOObj);
      return this.RTOSelect;
  }

}
   
}
