import { Component, OnInit } from '@angular/core';
import { JSONEditor } from 'jsoneditor';
import { Device } from '../device';
import { Token } from '../token';
import { Contact } from '../contact';
import { MdSnackBar } from '@angular/material';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SidebarComponent } from '../sidebar/sidebar.component';
import { ContactService } from '../contact.service';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Observable, Subject } from 'rxjs/Rx';
import { MyaccountComponent } from '../myaccount/myaccount.component';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { BsDatepickerConfig } from 'ngx-bootstrap/datepicker';
import { ReportService } from '../report/report.service';
declare var swal: any;
// import * as FileSaver from 'file-saver';
// import * as XLSX from 'xlsx';
declare var XLSX:any;
declare var $:any;
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
@Component({
  selector: 'app-dialog-content-example-dialog',
  templateUrl: './dialog-content-example-dialog.component.html',
  styleUrls: ['./dialog-content-example-dialog.component.css'],
  providers: [ContactService, SidebarComponent]
})
export class DialogContentExampleDialogComponent implements OnInit {
  colorTheme = 'theme-dark-blue';
  bsConfig: Partial<BsDatepickerConfig>;
  modelChanged: Subject<string> = new Subject<string>();
  date1=new Date()
  EngineNo:any;
  name1;
  sellsPerson
  installerData;
  installer;
  RTO;
  RTOObj;
  ignitionWire:Boolean=true;
  installerSelect=[];
  typeofVeh:any;
  manufacturingCompany:any;
  UIDnumber:any;
  iccidNo:any;
  Imsi:any;
  device_Id: string;
  dev: any;
  SIM_provider:any;
  SIM_provider2:any;
  deviceId: any;
  deviceModel: any;
  group_info: any;
  executed2: any;
  companyName:any;
  companyAddress:any;
  groupInfo: any;
  groupName
  dealers:any;
  date = new Date();
  vehRegDate:any;
  licenseVal:any='Yearly';
  licenseArr=['Yearly','Two years','Three years','Lifetime'];
  licenseArr1=['One Year','Two years'];
  vehicleCat=['Truck','Bus','Car','School Van'];
  vehicleCategory="Car"
  vehManufacturingYear :any;
  lastFitnessDate : any;
  fitmentDate :any;
  invoice_date:any;
  uploadStatus: any = 'Upload';
  devices: Device[] = []
  device: Device
  fuel_tank_capicity: any;
  voltage_tank_empty: any;
  tankfull_capicity: any;
  tokens: Token[] = []
  token: Token;
  docdate:any;
  expDate:any = new Date(this.date.getFullYear() + 1, this.date.getMonth(), this.date.getDate()).toLocaleString();
  superAdmin:Boolean = false;
  userDetail:any;
  vehType:any;
  custId: any;
  deviceInformation: {
  devicename: any; deviceid: any; des: any; model: any; hrdwr: any;hrdwr2: any; typdev: string; emailid: any; phn: any; sim_number: any; created_by: any;
    // iconType: this.neww.value,
    driver_name: any; contact_number: any; vehicleGroup: string;
    // fuelCapicity: this.fuel_tank_capicity,
    // voltageTankempity: this.voltage_tank_empty,
    // tankfullcapicity: this.tankfull_capicity,
    device_model: any; expdate: Date; vehicleType: string; user: any;
  };
  newDevInfo:any;
  newDevice: any;
  dataSelect: any[];
  datagrpSelect: any;
  dealerData:any
  datauserSelect: any;
  numberOfSOS:any;
  tpin:any;
  epin:any;
  colour:any;
  models:any;
  transmission:any
  userObj: any;
  IntegrationId:any;
  sup_admin: any;
  Dealer: any;
  DealerId: any;
  CIDNO: any;
  chassisno:any;
  transportOfficeCity: any;
  transportOfficeState: any;
  invoice_number: any;
  DeviceModelValue: any;
  dataDevModel: any[];
  vehicle_Type: any[];
    skip: number = 1;
  limit: number = 100;
  vehicleTypevalue: any;
  showCustomer:boolean=true
  // uploadStatus: any = 'UPLOAD';
  imageuploadObject = [{doctype:'Adhar card1',image:'',phone:'',docdate:''},
{doctype:'Adhar card2',image:'',phone:'',docdate:''},
{doctype:'Warrenty Card',image:'',phone:'',docdate:''},
{doctype:'vehicle sales invoice',image:'',phone:'',docdate:''},
{doctype:'vehicle RC',image:'',phone:'',docdate:''},
{doctype:'vehicle Photo',image:'',phone:'',docdate:''},
];
  array=[
    {
        "Device_Name": "test1021",
        "DeviceID": 102123,
        "SimNumber": 48839,
        "SimNumber2": 843993,
        "SIMProvider": "Vodafone",
        "VehicleType": "6225fe23046ce87675b0cfd4",
        "DeviceModel": "6110fabd99b02346e558abe9",
        "phone": 57655656,
        "first_name": "test",
        "last_name": "customer",
        "expire_validity": "One Year/Two Year",
        "expDate": "2024-03-08T06:16:20.530Z",
        "superAdmin": "61408bce53c0112864ef594f",
        "DealerId": "61408bce53c0112864ef594f",
        "userId": "61408bce53c0112864ef594f",
        "emailId": "employeetrack@gmail.com",
        "phone_num": "8434838439"
    }
]
  documentList = [
    {
      "docId": "Adhar card1",
      "docName": "Adhar Card Front"
    },
     {
      "docId": "Adhar card2",
      "docName": "Adhar Card Back"
    },
    {
      "docId": "vehicle sales invoice",
      "docName": "vehicle sales invoice"
    },
    {
      "docId": "voter Id",
      "docName": "Voter Id"
    },
    {
      "docId": "vehicle RC",
      "docName": "vehicle RC"
    },
    {
      "docId": "vehicle Photo",
      "docName": "vehicle Photo"
    },
    {
      "docId": "PAN card",
      "docName": "Pan Card"
    },
    {
      "docId": "Driving License",
      "docName": "Driving License"
    },
    {
      "docId": "RC Book",
      "docName": "RC Book"
    },
    {
      "docId": "Device Image",
      "docName": "Device Image"
    },
    {
      "docId": "Co.registered Card",
      "docName": "Co.registered Card"
    },
    {
      "docId": "Nepal Citizenship",
      "docName": "Nepal Citizenship"
    },
    {
      "docId": "Blue Book",
      "docName": "Blue Book"
    },
    {
      "docId": "Warrenty Card",
      "docName": "Warrenty Card"
    },
    {
      "docId": "Other",
      "docName": "Other"
    }
    
  ];

  showError1: boolean;
  showError2: boolean;
  showError0: boolean;
  editDeviceObject: any;
  uploadJSON: any;
  showErrorupload: boolean;
  faileduploadDevices: any;
  showErrorupload_1: boolean =false;
  portValue: any;
  showport: boolean = false;
  deviceImg=[];
  dealers_info: any[];
  myInput: string;
  dealerObj: any;
  installerObj:any
  dealerSelect: any[];
  RTOSelect:any[]
  deviceDistanceVariation
  selcetedSign='+'
  myaccount() {

    this.cond = false
    this.router.navigateByUrl("accountSettings");
    // 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.cond = false
    this.router.navigateByUrl("vehicleRoute");

  }

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

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

  route_map() {
    this.cond = false;
    this.router.navigateByUrl("routeMapping");

  }



  // new_1(){
  //   this.router.navigateByUrl("new");

  // }




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


  }

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

  }



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


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

  addgeo() {
    this.router.navigateByUrl("geofence-add");
  }
  geo() {
    this.router.navigateByUrl("geofencing");

  }

  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");
  }
  devicename: any;
  deviceid: any;
  des: any;
  model: any;
  Des: any;
  hrdwr: any;
  hrdwr2: any;
  typdev: any;
  Device_ID: string;
  Serial_Num: string;
  Manf: string;
  Model: string;
  tkstatus: any;
  value: any;
  Lo: string;
  Hardware_Ver: string;
  Loca: string;
  temp: any
  food: any
  new: any;
  email: any;
  message: string;
  selectedValue: any;
  show: boolean = false;
  showFieldsDealer:boolean=false;
    showFieldsUser:boolean=false;

  /* ../../assets/image/bgtry2.jpg */
  foods = [
    { value: 'Smart Switch', viewValue: 'Smart Switch' },
    { value: 'Tracker', viewValue: 'Tracker' },
    { value: 'Smart Motor', viewValue: 'Smart Motor' },
    { value: 'Sensors', viewValue: 'Sensors' },
  ];
  foodds = [
    { value: 'car', viewValue: 'Car' },
    { value: 'bike', viewValue: 'Bike' },
    { value: 'truck', viewValue: 'Bus/Truck' },
  ];
  cultivoChange(val) {

    if (val.value == "Tracker") {
      this.show = true
    }
    else {
      this.show = false
    }
  }

  back2home() {
    //console.log("Runnig Back")
    this.router.navigateByUrl("dashboard");

  }

  constructor(private _formBuilder: FormBuilder, private router: Router, public snackBar: MdSnackBar, private contactService: ContactService, private _flashMessagesService: FlashMessagesService, private sidebar: SidebarComponent, public dialog: MdDialog,private reportService:ReportService) { 
    this.bsConfig = Object.assign({}, { containerClass: this.colorTheme });
     this.reportService.addCustomer.subscribe(value => {
       console.log("INNSJNSKHJBNKDHB");
       
         this.ngOnInit()       
      
      }); 
 
  }
  test() {
    //console.log("Runnig Test")
    //console.log(this.new.value);
  }

  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");
    }
  }
  /*  TOKEN GENERATION  */
  tokenn() {
    if (this.deviceid == null) {

      this._flashMessagesService.show('Error : Empty Device ID', { cssClass: 'alert-danger', timeout: 2000 });
      this.tkstatus = 0;
    }
    else {
      // console.log("GENERATING TOKEN")
      /*  const newToken ={
         deviceid: this.deviceid,
         eid: "test@test.com",
         }
          this.contactService.addToken(newToken)
           .subscribe(token => {
             this.tokens.push(token);
           });   
           this.tkstatus=1;  */
    }
  }

  /*  ADD DEVICE   */

  mess: any;
  mess2: any;
  mess3: any;
  neww: any;
  driver: any;
  before: any;
  dcontact: any;
  timer: any;
  subscription: any;
  Load: boolean = false
  ign() {
    this.router.navigateByUrl("device-report/ign-report");

  }

showDate:boolean=false;
  
  addDevice(btnindex) {
    console.log("In addDevice");
    
    if(btnindex == 0){
      this.showError0 = true;
    }
     if(btnindex == 1){
       this.showError1 = true;
     }
     if(btnindex == 2){
      this.showError2 = true;
    }
    if(this.inventoryManagement){
      this.deviceid=$('#inventory').multipleSelect('getSelects','value');
    }
  
    if (this.deviceid == null) {
console.log("1");

      this._flashMessagesService.show('Error : Empty Device ID', { cssClass: 'alert-danger', timeout: 2000 });
      this.Load = false ; 
      return
    }
    else if ((this.devicename == null) ||(this.devicename == undefined)) {
      console.log("2");
      this._flashMessagesService.show('Error : Empty Device Name', { cssClass: 'alert-danger', timeout: 2000 });
      this.Load = false ; 
      return
    }
    else if (this.hrdwr == null) {
      console.log("3");
      this._flashMessagesService.show('Error : Empty SIM Number', { cssClass: 'alert-danger', timeout: 2000 });
      this.Load = false ; 
      return ; 
    }else if((!this.DeviceModelValue)||(this.dataDevModel.length ==0)||(this.DeviceModelValue  == undefined)){
      console.log("4");
      this._flashMessagesService.show('Error : Select Device model ', { cssClass: 'alert-danger', timeout: 2000 });
      this.Load = false ; 
      return ; 
    }
    else {
      console.log("In Else Block");
      
      this.Load = true
      // console.log(this.groupInfo);
      if(this.custtype==true){
        var owner = this.useridd;
      }else {
        var owner = this.dealerId?typeof(this.dealerId)=="object"?this.dealerId._id:this.dealerId:this.useridd;
      }


      // console.log(this.expDate)
   
      // console.log("userDetailTopass",this.userDetail._id);
      // console.log("vehdata",this.vehType._id)
      //this._flashMessagesService.show('Congratulation Device Added as '+this.deviceid, { cssClass: 'alert-success', timeout: 2000 });
      this.newDevice = {
        devicename: this.devicename,
        deviceid: this.deviceid,
        des: this.des,
        model: this.model,
        hrdwr: this.hrdwr,
        typdev: "Tracker",
        emailid: this.emailid,
        Mileage : "10",
        phn: this.phoneno,
        sim_number: this.hrdwr,
        created_by: owner,
        supAdmin: this.sup_admin,
        driver_name: this.driver,
        contact_number: this.dcontact,
        device_model: this.DeviceModelValue,
        expdate: new Date(this.expDate),
        License : this.licenseVal,
        deviceDistanceVariation:this.selcetedSign+(this.deviceDistanceVariation?this.deviceDistanceVariation:'0')

        // Dealer:this.dealerObj?this.dealerObj:this.sup_admin
      }
      if(this.inventoryManagement){
         this.newDevice['inventoryManagement']=this.inventoryManagement;
      }
      if(this.ignitionWire==true){
         this.newDevice['ignWire']=this.ignitionWire;
         this.newDevice['ignDetection']="ACC"
      }else{
        this.newDevice['ignWire']=this.ignitionWire;
         this.newDevice['ignDetection']="MOVEMENT"
      }
      if(this.sellsPerson){
        this.newDevice['sellsPerson']=this.sellsPerson;
      }
      if(this.installerObj){
         this.newDevice['installer'] =this.installerObj
      }


      
      if (this.custtype) {
        this.newDevice['Dealer'] = this.useridd;
      } else if((this.custtype == false)&&(window.localStorage['Custumer'] == 'ON') ) {
        this.newDevice['Dealer'] = this.DealerId
      }else{
        this.newDevice['Dealer'] =this.dealerObj?this.dealerObj:this.sup_admin
      }

      if((this.custId==undefined)&&(this.userObj==undefined)){
        this.newDevice['user'] = this.useridd
        // var userID= this.useridd;
  
      }else if((this.custId)&&(this.userObj==undefined)){
        this.newDevice['user'] = this.custId
        // var userID= this.custId;
      }
      else{
        this.newDevice['user'] = this.userObj;
        // var userID= 
      }

      if(this.EngineNo){
        this.newDevice['engineNo'] = this.EngineNo;
      }

      if(this.CIDNO){
        this.newDevice['CID_No'] = this.CIDNO;
      }

      if(this.fastag){
        this.newDevice['fastag'] = this.fastag;
      }

      if(this.licenseVal === 'Lifetime'){
        var eDate = new Date();
        var LifeTimeyear = eDate.getFullYear() + 5;
        eDate.setFullYear(LifeTimeyear);
        this.newDevice['expdate'] = new Date(eDate);
        
      }
      
      if(this.licenseVal === 'Two years'){
        var eDate = new Date();
        var LifeTimeyear = eDate.getFullYear() + 2;
        eDate.setFullYear(LifeTimeyear);
        this.newDevice['expdate'] = new Date(eDate);
       
      }
      if(this.licenseVal === 'Three years'){
        var eDate = new Date();
        var LifeTimeyear = eDate.getFullYear() + 3;
        eDate.setFullYear(LifeTimeyear);
        this.newDevice['expdate'] = new Date(eDate);
        
      }
      if(this.licenseVal === 'One Year'){
        var eDate = new Date();
        var LifeTimeyear = eDate.getFullYear() + 1;
        eDate.setFullYear(LifeTimeyear);
        this.newDevice['expdate'] = new Date(eDate);
        
      }




      if(this.chassisno){
        this.newDevice['ChassisNo'] = this.chassisno;
      }
      if(this.manufacturingCompany){
       this.newDevice['manufacturingCompany'] = this.manufacturingCompany;
      }
      if(this.UIDnumber){
        this.newDevice['uniqueID'] = this.UIDnumber;
      }
      if(this.iccidNo){
        this.newDevice['ICCICD'] = this.iccidNo;
      }
      if(this.Imsi){
        this.newDevice['IMSI'] = this.Imsi;
      }

      if(this.vehRegDate){
        this.newDevice['vehicleRegDate'] = new Date(this.vehRegDate);  
      }


      if(this.typeofVeh){
        this.newDevice['typeOfVehicle'] = this.typeofVeh;  
      }


      
      if(this.vehManufacturingYear){  
        this.newDevice['vehicleManufacturingDate'] = new Date(this.vehManufacturingYear);
      }

      if(this.lastFitnessDate){
        this.newDevice['lastFitnessDate'] = new Date(this.lastFitnessDate);
      }

      if(this.fitmentDate){
        this.newDevice['fitmentDate'] = new Date(this.fitmentDate);
      }
       
      if(this.invoice_date){
        this.newDevice['invoice_date'] = new Date(this.invoice_date);
      }

      if(this.invoice_number){
        this.newDevice['invoice_number'] = this.invoice_number;
      }




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

      if(this.numberOfSOS){
        this.newDevice['numberOfSOS'] = this.numberOfSOS;
      }
      if(this.epin){
        this.newDevice['epin'] = this.epin;
      }
      if(this.tpin){
        this.newDevice['tpin'] = this.tpin;
      }
     if(this.colour){
        this.newDevice['colour'] = this.colour;
      }
       if(this.models){
        this.newDevice['model'] = this.models;
      }
       if(this.transmission){
        this.newDevice['transmission'] = this.transmission;
      }

      if(this.SIM_provider==undefined){
        this.newDevice;
      }else{
        this.newDevice.sim_provider = this.SIM_provider;
      }

      if(this.SIM_provider2==undefined){
        this.newDevice;
      }else{
        this.newDevice.sim_provider2 = this.SIM_provider2;
      }

      if(this.hrdwr2==undefined){
        this.newDevice;
      }else{
        this.newDevice.sim_number2= this.hrdwr2;
      }

      if (this.grpObject == undefined) {
        this.newDevice;

      } else {
        this.newDevice.vehicleGroup = this.grpObject.devId;
        this.newDevice.groupName=this.grpObject.GroupName;
      }

      if(this.deviceImg != undefined){
        this.newDevice['deviceImage'] = this.deviceImg; 
      }

      if ((!this.vehicleTypevalue) || (this.vehicle_Type.length == 0)|| (this.vehicleTypevalue == undefined)) {
        this._flashMessagesService.show('Error : Select Vehicle type', { cssClass: 'alert-danger', timeout: 2000 });
        this.Load = false;
        return;
      } else {
        this.newDevice.vehicleType = this.vehicleTypevalue;
      }

      console.log("imageuploadDocument",this.imageuploadObject);
      if((this.imageuploadObject.length !=0)&&(btnindex == 2)){
        this.newDevice['imageDoc'] = this.imageuploadObject ;
      }
      console.log("=======>",this.newDevice,this.dealerData,this.userObj,this.DealerId,this.sup_admin)
       this.Load = false;
      this.contactService.addDevice(this.newDevice)
        .subscribe((device) => {
          window.localStorage['DataUpdate'] = 'True';
          this.sidebar.sidebarData();
          // console.log("deviceAdded", device);
          this.timer = Observable.timer(100, 100);
          this.subscription = this.timer.subscribe(t => {
            if (window.localStorage['DataUpdate'] == 'False') {
              window.localStorage['FinalAddDevice'] = 'True'
              this.subscription.unsubscribe();
              this.Load = false;
              this.router.navigateByUrl("dashboard");
            }
            this.Load = false
          })
          this.router.navigateByUrl("dashboard");
          // this.devices.push(device);
        }, (err: any) => {
          // console.log(err.status);
          // console.log(err);
          var that = this;
          if (err.status == 400) {
              console.log(JSON.parse(err._body).deviceObj);
            var dupObj = JSON.parse(err._body).deviceObj ; 
              this.Load = false;
             var devicesupAdmin = dupObj.supAdmin;
              var deviceDealer = dupObj.Dealer;
              var devOwner = dupObj.user;
              debugger;
            if((this.useridd === devicesupAdmin)||(this.useridd === deviceDealer)||(this.useridd===devOwner)){
              swal({
                title: 'Duplicate Entry',
                text: "The Device ID already exists in our system, do you want to delete this it ?",
                type: 'error',
                showCancelButton: true, 
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                cancelButtonText: 'NO',
                confirmButtonText: 'Yes'
              }).then((result1) => {   
                if (result1) {   
                    console.log(result1);
                    that.contactService.deletePermanently(that.deviceid)
                    .subscribe(res => {
                        // console.log(res);
                        that._flashMessagesService.show("Device Deleted", { cssClass: 'alert-success', timeout: 2000 });      
                    }, err => {
                      if(err.status==401){
                         that._flashMessagesService.show("Access Denied", { cssClass: 'alert-warning', timeout: 2000 });
                      }else
                        that._flashMessagesService.show("Internal Server Error", { cssClass: 'alert-warning', timeout: 2000 }); 
                        // console.log(err);
                    })
                    
                }
              },err=>{
                console.log(err);
                if(err == 'cancel'){
                    console.log('cancel clicked');
                }
              }) 
              console.log("Error");

            }else{

              swal("Duplicate Entry", "This device is already added to the system and its not associated with you account, Contact admin.", "error");
            }

            // this._flashMessagesService.show(this.mess2 + this.mess3 + " Duplicate Entry", { cssClass: 'alert-danger', timeout: 3000 });
       
        
          }
          else {  
            var message
            if(err.status==401){
              message="Access Denied !!!"

            }else{
               message="Network Error !!!"
            }
            console.log(err);
            
            this._flashMessagesService.show(message, { cssClass: 'alert-danger', timeout: 2000 });
            this.Load = false
          }
        }
        );

    }

  }
  call(e) {
    {
      if (e.keyCode == 32) {
        e.preventDefault();
      }
    }
  }
  click1(event) {

    if ((event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 9 || event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39) {
    }
    /* if(event.keyCode===13){
    this.otp_window();
    } */

    else
      event.preventDefault();
  }
  fs: any;
  ls: any;
  or: any;
  userid: any;
  emailid: any;
  useridd: any;
  custtype: any;
  cust: boolean = true;
  isLinear = false;
  firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;
  phoneno: any;
  logo: any;
  text: any;
  dealerId:any;
  ideal() {
    this.router.navigateByUrl("device-report/ideal-report");
  }
  mb: any
  logoutbut: boolean;
  dealer: boolean;
  groups = [];
  ngOnInit() {
    let that = this;
    this.neww = this.foodds[0];
    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.dealerId=JSON.parse(window.atob(window.localStorage.token.split('.')[1])).Dealer_ID;
    var temp =JSON.parse(window.atob(window.localStorage.token.split('.')[1]));
    console.log(temp);
    // this.testTable()
    this.sup_admin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;
   
    if(this.superAdmin){
      this.sup_admin = this.useridd;
    }
    // console.log("superAdmin=>",this.sup_admin);
  
    this.mb = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    this.custId = localStorage.getItem('custId');

    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    console.log(this.custtype);
    

    if((this.custtype == false)&&(window.localStorage['Custumer'] == 'ON')){
   this.showCustomer=false;
       this.DealerId =  JSON.parse(window.atob(window.localStorage.Dealer_token.split(".")[1]))._id;  
       console.log("DealerID",this.DealerId) 
    }
  
    
    // this.superadmin
    //this.getdev();
    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
    }

//     $(".sel").change(function(){

//     var selValue = $(this).val();

//     alert(selValue);

// });
$(document).on('change','#inventory',function() {
    var value = $('#inventory').val();
    for(var i=0;i<that.inventory.length;i++){
      if(value==that.inventory[i].IMEI){
        that.hrdwr=that.inventory[i].Mob1
        that.hrdwr2=that.inventory[i].Mob2
      }
    }
   
});

    
    this.logo = window.localStorage['logo'];
    this.text = window.localStorage['text'];
    this.getInstallerData()
    $("#excelFile").change(function(e){
      let _e:any = e;
      console.log("Inside function");
        var reader = new FileReader();
        console.log(reader);
        reader.onload = function(e) {
         
          let _E:any = e;
          var data = _E.target.result;
       
        
        let workbook = XLSX.read(data, {type: 'binary' });
      
         let first_sheet_name = workbook.SheetNames[0];
      
       let worksheet = workbook.Sheets[first_sheet_name];
       let d:any = XLSX.utils.sheet_to_json(worksheet,{raw:true});
      
         
       that.uploadJSON=d.map(function(d){  
        console.log(d);
        var exp=new Date();
        if(d.expire_validity=="One Year"){
          
        var LifeTimeyear = exp.getFullYear() + 1;
        exp.setFullYear(LifeTimeyear);
        d.expDate = new Date(exp);
        }else{
        var LifeTimeyear = exp.getFullYear() + 2;
        exp.setFullYear(LifeTimeyear);
        d.expDate = new Date(exp);
        }
          // var splitDeviceModel = d.DeviceModel.split("(")[1].split(")")[0];
        
          // var splitvehicletype = d.VehicleType.split("(")[1].split(")")[0];
      
        d.SIMProvider  = "Vodafone";
        // d.DeviceModel = splitDeviceModel;
        // d.VehicleType = splitvehicletype;     
        d.superAdmin =   that.sup_admin;
        d.DealerId = (that.custtype==true) ? that.useridd : that.sup_admin ;
        d.userId = that.useridd;
        d.emailId =that.emailid;
        d.phone_num =that.mb;
       
        return d;
        });
        console.log("file=>",that.uploadJSON);
     
        };
           reader.readAsBinaryString(_e.target.files[0]); 
      
      });
     this.contactService.getDevice(this.emailid, this.useridd)
      .subscribe(devices => this.devices = devices);
        this.tkstatus = 0;
    // console.log(this.devices);


    this.groups = [];
    this.contactService.getGroup(this.useridd).subscribe(
      res => {
        // console.log(res);

        this.group_info = res["group_details"];
        // console.log(this.group_info);
     
        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,
          })
        }
        // console.log(this.groups);

      });

     console.log("dskfdshfkdsgndfgk;dfgjhfkgdfntgkjdbnfdjk",localStorage.getItem('deviceforedit'));
     var objectforedit = localStorage.getItem('deviceforedit')?localStorage.getItem('deviceforedit'):null;
   this.loadropdown()
    // this.updateFieldswithvalue(objectforedit);
    this.getDeviceModel();
    this.getUser(this.useridd);
    this.getvehDetail();
     this.getUserSetting(this.useridd);
     this.getRTOData()
     this.getModelData()
    // this.modelChanged
    //   .debounceTime(1000) // wait 300ms after the last event before emitting last event
    //   .distinctUntilChanged() // only emit if value is different from previous value
      // super==on and dealer==on and cust=?---dealer
      //super=?
      //cistomer== three on super==false, dealer=false

      // condition For SuperAdmin



      // 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') )
      if(this.superAdmin)
      {
        console.log("1");
        
            this.showFieldsDealer=true
           this.showFieldsUser=true; 
      }
       if(((localStorage.getItem('superadmin')=='ON' || (!localStorage.getItem('superadmin'))) && localStorage.getItem('Dealer')=='ON' && localStorage.getItem('Custumer')=='OFF' || (!localStorage.getItem('Custumer'))) && !this.superAdmin )
      {console.log("2");
          this.showFieldsDealer=false
           this.showFieldsUser=true; 
      } 
      if(this.superAdmin==true && this.custtype==true){
        console.log("3");
         this.showFieldsDealer=true;
           this.showFieldsUser=true; 
      }  
      if(this.superAdmin==false && this.custtype==true){
        console.log("4");
         this.showFieldsDealer=false;
           this.showFieldsUser=true; 
      }
      if(this.superAdmin==false && this.custtype==false){
        console.log("4");
         this.showFieldsDealer=false;
           this.showFieldsUser=false; 
      }
      // else{
      //   console.log("5");
      //    this.showFieldsDealer=false;
      //      this.showFieldsUser=false; 
      // }
      console.log(this.showFieldsDealer,this.showFieldsUser,this.superAdmin);
      
       this.dealerDetail();
     


  }
  RTOData
  getRTOData(){
    this.contactService.get('/RTO_master/get').subscribe((res:any)=>{
      this.RTOData=res
    })
  }
  manufacturingData
  getModelData(){
     this.contactService.get('/model_master/GetNames').subscribe((res:any)=>{
      this.manufacturingData=res
    })
  }

   loadropdown() {
    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(() => {
      $('#inventory').multipleSelect({
        width: 380,
        placeholder: 'Select IMEI',
        filter: true,
        single: true,
        selectAll: false
 
      })
  
   
    }, 100);

  }

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


  fuel_calibration() {
    // console.log("Inside fuel Callibration !!!");
    if (this.fuel_tank_capicity == null) {

      this._flashMessagesService.show('Error : Empty entry', { cssClass: 'alert-danger', timeout: 2000 });
      this.Load = false
    }
    else if (this.voltage_tank_empty == null) {
      this._flashMessagesService.show('Error : Empty entry', { cssClass: 'alert-danger', timeout: 2000 });
      this.Load = false
    }
    else if (this.tankfull_capicity == null) {
      this._flashMessagesService.show('Error : Empty entry', { cssClass: 'alert-danger', timeout: 2000 });
      this.Load = false
    }


    const fuelCapicity = {
      fuelCapacity: this.fuel_tank_capicity,
      voltageTankempty: this.voltage_tank_empty,
      tankfullcapacity: this.tankfull_capicity,

    }

    // console.log(fuelCapicity);
  }



  device_Model: any;
  getDeviceModel() {
    this.contactService.getDevModel()
      .subscribe(res => {
        this.device_Model = res;
        var devname = [];
        console.log("Device_Model",this.device_Model);
        for(var i = 0 ; i<this.device_Model.length;i++){
          var a = {
            model :this.device_Model[i].device_type,
            id : this.device_Model[i]._id
          }
          var modelName;
        
          if(this.device_Model[i].deviceport != undefined){
            modelName = this.device_Model[i].device_type + " " + "(Port : " + this.device_Model[i].deviceport + ")";
         
          }else{
            modelName = this.device_Model[i].device_type;
          }
          this.device_Model[i].modelName = modelName ; 
          devname.push(a);
        }
        console.log('this.device_Model',this.device_Model);
        console.log(devname);
      })
  }
  inventoryManagement:Boolean=false;
  inventory=[]
  getUserSetting(userId){
    
    this.contactService.post('/users/get_user_setting',{uid: userId}).subscribe((res:any)=>{
      this.inventoryManagement=res.inventoryManagement;
      if(this.inventoryManagement){
        console.log(this.useridd,this.dealerId=JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer);
        var isDealer=this.dealerId=JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer
        var user=isDealer?this.useridd:this.sup_admin
        console.log(user);
        
        this.contactService.get('/Device_inventory/getInventory?user='+user).subscribe((res:any)=>{
          this.inventory=res;
          this.loadropdown()
        })
      }
    })
  }
  
  costumers:any;
  getUser(userId){
    this.datauserSelect=[]
    this.costumers=[]
    this.contactService.getContactsbyDealer(userId)
    .subscribe(res=>{
      // console.log("Alluserobject",res);
      this.costumers = res;
      for(var i =0; i<this.costumers.length;i++){
        var n = this.costumers[i].first_name + " " + (this.costumers[i]?this.costumers[i].last_name:"") +(this.costumers[i]?this.costumers[i].user_id?" ("+this.costumers[i].user_id+")":"":"");
        this.costumers[i].full_name = n; 
      }

      // console.log("new costumer Object",this.costumers);  

    })
  }
 vehData:any;
getvehDetail(){
  this.contactService.getvehType(this.useridd)
    .subscribe(res=>{
      // console.log(res);
      this.vehData=res;
      var vdata = res;
      for(var a = 0;a<this.vehData.length;a++){
          var vehtypename = vdata[a].brand + " " + vdata[a].model;
          this.vehData[a].vehicle_name = vehtypename;
      }
       console.log("allveh",this.vehData);
    })
}


filtergrpStates(val) {

  // console.log(val)
  // console.log(this.options)
 
  if (val) {

    const filtergrpValue:any = val;
    this.datagrpSelect=[];
     this.datagrpSelect = this.groups.filter(function(g){
      var c = g.GroupName.toLocaleLowerCase().indexOf(filtergrpValue.toLocaleLowerCase());
    //  this.option = this.options[i];

      return c > -1;    
    });
      // console.log(this.datagrpSelect);
      return this.datagrpSelect;
  }

}
filtergrpStatess(val) {

  console.log(val)
  // console.log(this.options)
 
  if (val) {
this.userDetail=undefined
    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];
    console.log("TESTINg",c)
      return c > -1;    
    });
    if(this.dealerData){
      for(let i=0;i<this.dealers_info.length;i++){
        if(this.dealers_info[i].fullName==this.dealerData){
          this.dealerObj=this.dealers_info[i]._id
          console.log(this.dealers_info[i]);
          
          this.getUser(this.dealers_info[i]._id)
        }
      }
    }
      console.log(this.dealerSelect,this.dealerData, this.dealerObj);
      return this.dealerSelect;
  }

}

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

}

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

}

grpObject:any;
selectMainGrp(grp){
this.grpObject=grp;
console.log(this.grpObject);

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

selectedDevModel(devModel){
  this.DeviceModelValue = devModel;
  console.log('this.DeviceModelValue',this.DeviceModelValue);
  console.log(this.DeviceModelValue);
}

filterUserStates(userVal){
  // console.log(userVal)
  // console.log(this.options)
 
  if (userVal) {

    const filteruserValue:any = userVal;
    this.datauserSelect=[];
    console.log("testCostumer=>",this.costumers);
     this.datauserSelect = this.costumers.filter(function(d){
      var t = d.first_name.toLocaleLowerCase().indexOf(filteruserValue.toLocaleLowerCase());
    //  this.option = this.options[i];

      return t > -1;    
    });
    //  if(this.userObj){
      for(let i=0;i<this.costumers.length;i++){
        if(this.costumers[i].full_name==this.userDetail){
          console.log(this.costumers[i]);
          
          this.userObj=this.costumers[i]._id
        // }
      }
    }
      console.log(this.datauserSelect,this.userObj,this.userDetail);
    
      return this.datauserSelect;
}

}

filterDeviceModelState(devModelVal){ 
  if(devModelVal == ''){
    this.dataDevModel=[];
  }
  
  if (devModelVal) {
 
    const filterDevModelVal:any = devModelVal;
    this.dataDevModel=[];
      // console.log('device_model' , this.device_Model);
     this.dataDevModel = this.device_Model.filter(function(k){
      // console.log('devicemodel object=>',k)
      var z = k.modelName.toLocaleLowerCase().indexOf(filterDevModelVal.toLocaleLowerCase());
    

      return z > -1;    
    });
    for(let i=0;i<this.device_Model.length;i++)
    {
      if(this.device_Model[i].modelName==this.deviceModel){
        this.DeviceModelValue=this.device_Model[i]._id
        console.log("Device Model",this.device_Model[i]._id);
      }
    }    
      
      return this.dataDevModel;
}

}

selectvehType(v_type){
  
  this.vehicleTypevalue = v_type;
  console.log("vehicletypevalue",this.vehicleTypevalue)

}

filterVehType(vehicle_type){
  console.log("vehicle_type",vehicle_type);
  if(vehicle_type == ''){
    this.vehicle_Type=[];
  }

  if (vehicle_type) {
    const filtervehTypevalue:any = vehicle_type;
    this.vehicle_Type=[];
    console.log("vehicle Array=>",this.vehData);
     this.vehicle_Type = this.vehData.filter(function(tt){    
      var vt = tt.vehicle_name.toLocaleLowerCase().indexOf(filtervehTypevalue.toLocaleLowerCase());
   
      return vt > -1;    
    });
    for(let i=0;i<this.vehData.length;i++){
      if(this.vehData[i].vehicle_name==this.vehType){
        this.vehicleTypevalue=this.vehData[i]._id
      }
    }
  
      return this.vehicle_Type;
}
}

// neww-------------------




selectMainUser(userSelect){
  this.userObj = userSelect;
  // console.log(this.userObj)
}

deleteDoc(doc,index){
  console.log(index);
  console.log(doc);

}
// imageuploadObject = [{doctype:'',image:'',phone:'',docdate:''}];
disableDelete: boolean;
showUpload: boolean=false;
ifuploadArr: boolean ;
Adddocuments(doc:any){
  console.log(doc);
  this.disableDelete = true;
  this.showUpload = true;
  if(this.imageuploadObject.length == 0){
    this.ifuploadArr = false;
  }
}

docRow:boolean=false;
AddDocumentsField(addedRow:any){
  console.log("Inside function !!!");
    if(addedRow){    
      this.docRow = true;
    }
    
     var obj={doctype:'',image:'',phone:'',docdate:''};
     this.imageuploadObject.push(obj);
     console.log(this.imageuploadObject);
    // console.log("ImageuploadObject=>",this.imageuploadObject);
}

DeleteDocumentsField(index){
  console.log(this.imageuploadObject.length);
  if(this.imageuploadObject.length == 1){
    this.docRow = false;
    this.showUpload = false;
  }
  this.imageuploadObject.splice(index, 1);

}

documentType(docType){
  console.log("doctypeObject=>",docType);

}
selectedFile: File;
onFileChanged(event) { 
  this.selectedFile = <File>event.target.files[0];
  console.log(this.selectedFile); 
}

onUpload(imgIndex) {
  console.log(imgIndex);
  console.log(this.imageuploadObject);
  const fd = new FormData();
  console.log("selected file name =>",this.selectedFile.name);
  if(this.selectedFile.name == " "){
    swal(
      'Upload Error',
      'Please select document type before upload !!!',
      'error'
    )
  }else{
    fd.append('photo',this.selectedFile,this.selectedFile.name)
    console.log("imgURL=>",fd) ;
    this.Load = true;
    this.contactService.imageupload(fd)
    .subscribe(res=>{
      this.Load = false;
      this.ifuploadArr = true;
   //   this.uploadStatus = 'Uploaded';
      console.log(res);
      var resImage ='';
      resImage = res['_body'];
      console.log(res['_body']);
      this.imageuploadObject[imgIndex].image = resImage;
       console.log(this.imageuploadObject);
      // console.log(res);
    },err=>{
      this.Load= false;
      this._flashMessagesService.show('Internal server error , try again', { cssClass: 'alert-success', timeout: 2000 }); 
    })
  }
 }

 devInformationUpdate(btnpress){
   if(btnpress == 0){
      // swal({
      //   title: 'Are you sure ?',
      //   text: "Do you want to add additional information ?",
      //   type: 'success',
      //   showCancelButton: true,
      //   confirmButtonColor: '#3085d6',
      //   cancelButtonColor: '#d33',
      //   cancelButtonText: 'NO',
      //   confirmButtonText: 'Yes'
      // }).then((result) => {
      //   console.log(result);
      //   if (result) {   
      //     console.log(result);
      //   }
      // },err=>{
      //   console.log(err);
      //   if(err == 'cancel'){
          this.addDevice(btnpress);
      //   }
      // }) 
   }

   if(btnpress == 1){
      // swal({
      //   title: 'Are you sure ?',
      //   text: "Do you want to upload device document now ?",
      //   type: 'warning',
      //   showCancelButton: true,
      //   confirmButtonColor: '#3085d6',
      //   cancelButtonColor: '#d33',
      //   cancelButtonText: 'No',
      //   confirmButtonText: 'Yes'
      // }).then((result: { value: boolean; }) => {
      //   console.log(result);
      //   if (result) {
      //    console.log(result);
         
      //   }
      // },err=>{
      //   console.log(err);
      //   if(err == 'cancel'){
          this.addDevice(btnpress);
      //   }
      // }) 
   }

   if(btnpress == 2){
      // swal({
      //   title: 'Document uploaded Successfully',
      //   text: "Are you sure to add Device ?",
      //   type: 'warning',
      //   showCancelButton: true,
      //   confirmButtonColor: '#3085d6',
      //   cancelButtonColor: '#d33',
      //   confirmButtonText: 'Yes, add it!'
      // }).then((result: { value: boolean; }) => {
      //   console.log(result);
      //   if (result) {
          this.addDevice(btnpress);
      //   }else{
      //     console.log("no clicked");
      //   }
      // })
   }
   
  }
  dealerDetail() {
    this.Load = true;
   console.log("Inside function");
  //  this.contactService.dealer_Info1(this.useridd,1,10000,2,null)
 this.contactService.dealer_Info1(this.useridd, this.skip, this.limit,this.myInput,null)    
   .subscribe(res => {
        // console.log(res);
        this.Load = false ;
        this.dealers_info = res;
        for(let i=0;i<this.dealers_info.length;i++){
          this.dealers_info[i].fullName=this.dealers_info[i].first_name+' '+this.dealers_info[i].last_name;
        }
        console.log('this.dealers_info',this.dealers_info);
      }, err => {
        this.Load = false;
        this.dealers_info=[];
        // this.firstcall = true;
        // this.lastcall = false;
      })

  }

 


  // updateFieldswithvalue(deviceobjectforedit) {
  //   console.log("gfdjgdlkgfdngfdlkgndk;flngfdkgnfdkbdfnd=>", JSON.parse(deviceobjectforedit));
  //   var tempdevobj = JSON.parse(deviceobjectforedit);
  //   if (deviceobjectforedit != null) {
  //     console.log(JSON.parse(deviceobjectforedit))
  //     this.deviceid = tempdevobj.Device_ID;
  //     this.devicename = tempdevobj.Device_Name;
  //     this.hrdwr = tempdevobj.sim_number;
  //     this.SIM_provider = tempdevobj.sim_provider;
  //     this.hrdwr2 = tempdevobj.sim_number2;
  //     this.SIM_provider2 = tempdevobj.sim_provider2;
  //     this.EngineNo = tempdevobj.engineNo;
  //     this.manufacturingCompany = tempdevobj.manufacturingCompany;
  //     this.typeofVeh = tempdevobj.typeOfVehicle;
  //     this.iccidNo = tempdevobj.ICCICD;
  //     this.Imsi = tempdevobj.IMSI;
  //     this.UIDnumber = tempdevobj.uniqueID;
  //     this.chassisno = tempdevobj.ChassisNo;
  //     this.companyName = tempdevobj.companyName;
  //     this.companyAddress = tempdevobj.companyAddress;
  //     this.transportOfficeCity = tempdevobj.transportOfficeCity;
  //     this.transportOfficeState = tempdevobj.transportOfficeState;
  //     this.invoice_number = tempdevobj.invoiceNumber;
  //     this.IntegrationId = tempdevobj.integrationId
  //     this.numberOfSOS = tempdevobj.numberOfSOS;
  //     this.CIDNO = tempdevobj.CID_No;
  //     this.driver = tempdevobj.driver_name;
  //     this.dcontact = tempdevobj.contact_number;
  //     this.des = tempdevobj.Device_Des;
  //     if (tempdevobj.expDate) {
  //       console.log(tempdevobj.expDate);
  //       this.expDate = tempdevobj.expdate;
  //     }
  //     if (tempdevobj.invoiceDate) {
  //       this.invoice_date = new Date(tempdevobj.invoiceDate);
  //     }
  //     if (tempdevobj.fitmentDate) {
  //       this.fitmentDate = new Date(tempdevobj.fitmentDate);
  //     }
  //     if (tempdevobj.lastFitnessDate) {
  //       this.lastFitnessDate = new Date(tempdevobj.lastFitnessDate);
  //     }
  //     if (tempdevobj.vehicleRegDate) {
  //       this.vehRegDate = new Date(tempdevobj.vehicleRegDate)
  //     }
  //     if (tempdevobj.vehicleManufacturingDate) {
  //       this.vehManufacturingYear = new Date(tempdevobj.vehicleManufacturingDate);
  //     }

  //     if(tempdevobj.imageDoc){
  //       if(tempdevobj.imageDoc.length != 0){
  //         console.log(tempdevobj.imageDoc);
  //         for(var i =0;i<tempdevobj.imageDoc.length;i++){
  //           if(tempdevobj.imageDoc[i].docdate){
  //             tempdevobj.imageDoc[i].docdate = new Date(tempdevobj.imageDoc[i].docdate);        
  //           }
  //         }   
  //         this.imageuploadObject = tempdevobj.imageDoc ; 
  //         console.log("kdjfbsafkjbdskjfbvdskjfbjdsfbsdj=>",this.imageuploadObject[0].image);
  //       }
  //     }
  //   }  
  // }

 ngOnDestroy(){
   localStorage.removeItem('deviceforedit');

 }
 fastag:any;

 responseMessage:any;
 failedReason:any;
 failedUploadFiles:any;
 uploadExcel(){
  console.log("Device Json Payload",this.uploadJSON);
  this.failedUploadFiles = [];
  this.Load =true;
  this.contactService.addMultipleDevice(this.uploadJSON)
      .subscribe(res=>{
        console.log(res);
        this.failedUploadFiles =  res.failedJson;
        this.responseMessage  =   res.message;
        // this.failedReason=res.reason;
       
        if(this.failedUploadFiles.length == 0){
          // this.showErrorupload = true;
          // this._flashMessagesService.show("Device" + " " + this.responseMessage, { cssClass: 'alert-success', timeout: 2000 });
          
          this.Load = false;
          this.router.navigateByUrl("dashboard");
        }else{
          this.showErrorupload_1 = true;
          this.Load = false;
          this.faileduploadDevices = [];
          console.log(this.failedUploadFiles); 
          for(var k = 0 ;k < this.failedUploadFiles.length; k ++ ){
            var failedObj = {
              Device_ID : this.failedUploadFiles[k].DeviceID,
              Device_Name : this.failedUploadFiles[k].Device_Name,
              Reason : this.failedUploadFiles[k].reason
            }

            this.faileduploadDevices.push(failedObj);
          }
          // this._flashMessagesService.show("Device" + " " + this.responseMessage + "with Some fialed condition", { cssClass: 'alert-success', timeout: 2000 });
          // this.Load = false;
          // this.router.navigateByUrl("dashboard");
        }
      
        // console.log(this.failedReason);
      },err=>{
        this.Load = false;
        this.router.navigateByUrl("dashboard");
        console.log(err);
      })
 }




 imageURL:any;
 selectedDeviceFile:File;
 data_descip : any;
onDeviceImageChanged(event) {
  this.selectedDeviceFile = <File>event.target.files[0];
}

onDeviceImageUploadUpload(){
  const fdDevice = new FormData();
  fdDevice.append('photo',this.selectedDeviceFile,this.selectedDeviceFile.name)
   console.log("Binaryimage = > ",fdDevice );
   this.contactService.deviceImageupload(fdDevice)
     .subscribe(res=>{
           console.log(res);
           if(res){
             this.deviceImg.push(res['_body'])
           }

          console.log('this.deviceImg',this.deviceImg);
           this.data_descip = "Image Uploaded";
           launch_toast();
     },err=>{
      this.data_descip = "Internal Server Error";
      launch_toast();
       console.log(err);
     })
 
     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", ""); }, 1500);
    }
 
}

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;
        }
    })
}
changeLiecence(licenseVal)
{
  console.log(licenseVal);
  
  if(licenseVal == 'Lifetime'){
        var eDate = new Date();
        var LifeTimeyear = eDate.getFullYear() + 5;
        eDate.setFullYear(LifeTimeyear);
       this.expDate = new Date(eDate);
        this.showDate=true;
      }else if(licenseVal == 'Two years'){
        var eDate = new Date();
        var LifeTimeyear = eDate.getFullYear() + 2;
        eDate.setFullYear(LifeTimeyear);
       this.expDate = new Date(eDate);
        this.showDate=true;
      }else if(licenseVal == 'Three years'){
        var eDate = new Date();
        var LifeTimeyear = eDate.getFullYear() + 3;
        eDate.setFullYear(LifeTimeyear);
       this.expDate = new Date(eDate);
         this.showDate=true;
      }else{
        this.showDate=false;
      }
}
modelData
selectModel(event){
  console.log(event);

  this.contactService.get('/model_master/getModel?name='+event).subscribe((res:any)=>{
    this.modelData=res
  })
  
}


tabelObj
testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function () {
      that.tabelObj = $('#sample').DataTable({
      
        "autoWidth": true,
        'deferRender':true,
        "processing": true,
        stateSave: true,
        "bDestroy": true,
        "searching": true,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: false,
        "scrollX": true,
        "scrollY": '65vh',
        "scrollCollapse": true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "createdRow": function(row: Node, data: any | Object, index: number){
       
        
        },
        ajax: (dataTablesParameters, callback) => {
         
        callback({data:that.array})

        },
// "Device_Name": "test1021",
//         "DeviceID": 102123,
//         "SimNumber": 48839,
//         "SimNumber2": 843993,
//         "SIMProvider": "Vodafone",
//         "VehicleType": "6225fe23046ce87675b0cfd4",
//         "DeviceModel": "6110fabd99b02346e558abe9",
//         "phone": 57655656,
//         "first_name": "test",
//         "last_name": "customer",
//         "expire_validity": "Two Year",
//         "expDate": "2024-03-08T06:16:20.530Z",
//         "superAdmin": "61408bce53c0112864ef594f",
//         "DealerId": "61408bce53c0112864ef594f",
//         "userId": "61408bce53c0112864ef594f",
//         "emailId": "employeetrack@gmail.com",
//         "phone_num": "8434838439"
        "columns": [
          {
            "data": "Device_Name",
            "render": function (data, row) { 
             return data?data:'N/A';  
            }
          },
          {
            "data": "DeviceID",
           
            "render": function (data, row) {             
              return data;   
            }
          },
           {
            "data": "SimNumber",
           
            "render": function (data, row) {             
              return data;   
            }
          },
           {
            "data": "SimNumber2",
           
            "render": function (data, row) {             
              return data;   
            }
          },
          {
            "data": "SIMProvider",
           
            "render": function (data, row) {             
              return data;   
            }
          },
           {
            "data": "VehicleType",
           
            "render": function (data, row) {             
              return data;   
            }
          },
          {
            "data": "DeviceModel",
           
            "render": function (data, row) {             
              return data;   
            }
          },
           {
            "data": "phone",
            "render": function (data, row) {  
              return data?data:'N/A';   
            }
          },
         
           {
            "data": "first_name",
           
            "render": function (data, row) {             
              return data;   
            }
          },
           {
            "data": "last_name",
           
            "render": function (data, row) {             
              return data;   
            }
          },
            {
            "data": "expire_validity",
           
            "render": function (data, row) {             
              return data;   
            }
          },
            
        ],
        
      });
 
    });

  }
exportExcel()
{
this.downloadFile(this.array);
}


downloadFile(data) {

    let arrHeader = ["Device_Name", "DeviceID","SimNumber", "SimNumber2", "SIMProvider","VehicleType","DeviceModel","phone","first_name","last_name","expire_validity"];
    let csvData = this.ConvertToCSV(data, arrHeader);
    let blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' });
    let dwldLink = document.createElement("a");
    let url = URL.createObjectURL(blob);
    let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
    if (isSafariBrowser) {  //if Safari open in new window to save file with random filename.
      dwldLink.setAttribute("target", "_blank");
    }
    dwldLink.setAttribute("href", url);
    dwldLink.setAttribute("download", "Sample.csv");
    dwldLink.style.visibility = "hidden";
    document.body.appendChild(dwldLink);
    dwldLink.click();
    document.body.removeChild(dwldLink);
  }
  ConvertToCSV(objArray, headerList) {
    let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

    let str = ""
    let row = 'S.No,';


    let newHeaders =["Device_Name", "DeviceID","SimNumber", "SimNumber2", "SIMProvider","VehicleType","DeviceModel","phone","first_name","last_name","expire_validity"];

    for (let index in newHeaders) {
      row += newHeaders[index] + ',';
    }
    row = row.slice(0, -1);
    str += row + '\r\n';
    for (let i = 0; i < array.length; i++) {
      let line = (i + 1) + '';
      if(i<array.length){}
      for (let index in headerList) {
        let head = headerList[index];       
        line += ',' + this.strRep(array[i][head]);
      }
      str += line + '\r\n';
      
    }
    return str;
  }

    strRep(data) {
    if(typeof data == "string") {
      let newData = data.replace(/,/g, " ");
       return newData;
    }
    else if(typeof data == "undefined") {
      return "-";
    }
    else if(typeof data == "number") {
      return  data.toString();
    }
    else {
      return data;
    }
  }

  //  exportAsExcelFile(json: any[], excelFileName: string): void {
    
  //   const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
  //   console.log('worksheet',worksheet);
  //   const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
  //   const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  //   //const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
  //   this.saveAsExcelFile(excelBuffer, excelFileName);
  // }

  // private saveAsExcelFile(buffer: any, fileName: string): void {
  //   const data: Blob = new Blob([buffer], {
  //     type: EXCEL_TYPE
  //   });
  //   FileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
  // }
}


