import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { BsDatepickerConfig, BsModalRef, BsModalService } from 'ngx-bootstrap';
import { ContactService } from '../../contact.service';
import {Location} from '@angular/common';
import { T } from '../../../../node_modules3/@types/lodash/fp';
declare var $:any;
declare var swal: any;
@Component({
  selector: 'app-add-new-device',
  templateUrl: './add-new-device.component.html',
  styleUrls: ['./add-new-device.component.scss']
})
export class AddNewDeviceComponent implements OnInit {
  DeviceModelValue: any;
   modalRef: BsModalRef;
  contactMessage= '';
  submitted = false;
  date=new Date()
  expDate:any = new Date(this.date.getFullYear() + 1, this.date.getMonth(), this.date.getDate()).toLocaleString();
  Indianstate = [ "Andhra Pradesh",
                "Arunachal Pradesh",
                "Assam",
                "Bihar",
                "Chhattisgarh",
                "Goa",
                "Gujarat",
                "Haryana",
                "Himachal Pradesh",
                "Jammu and Kashmir",
                "Jharkhand",
                "Karnataka",
                "Kerala",
                "Madhya Pradesh",
                "Maharashtra",
                "Manipur",
                "Meghalaya",
                "Mizoram",
                "Nagaland",
                "Odisha",
                "Punjab",
                "Rajasthan",
                "Sikkim",
                "Tamil Nadu",
                "Telangana",
                "Tripura",
                "Uttarakhand",
                "Uttar Pradesh",
                "West Bengal",
                "Andaman and Nicobar Islands",
                "Chandigarh",
                "Dadra and Nagar Haveli",
                "Daman and Diu",
                "Delhi",
                "Lakshadweep",
                "Puducherry"]
  custtype: any;
  DealerId: any;
  constructor(private modalService: BsModalService,private location:Location,private fb:FormBuilder,private contactService:ContactService,private router:Router,private _flashMessagesService: FlashMessagesService,) { }
  deviceForm:FormGroup;
  userId
  deviceModel
  vehicleCat=[
  "Luxury Cab",
"Three wheeled vehicles for transport of passengers/goods",
"Goods carrier trucks or tankers or mail carriers",
"Power tiller and Tractors using public roads",
"Mobile clinic or X-Ray van or library vans",
"Mobile Workshops",
"Mobile canteens",
"Private Service Vehicle",
"maxi cab",
"motor cab",
"stage cariage",
"contract carriage",
"Tourist",
"Educational Institution buses",
"Ambulances",
"Animal Ambulances",
"Camper vans or trailers",
"Cash vans",
"Fire tenders, snorked ladders,auxiliary trailers and fire fighting vehicles",
"Articulated vehicles",
"Hearses",
"Motor car",
"Crane mounted vehicle",
"Agricultural Tractor and Power Tiller",
"Tow Trucks, Breakdown Van and Recovery Vehicles",
"Construction Equipment Vehicles",]

  // vehicleCat=['Truck','Bus','Car','School Van'];
  Load:boolean=false;
    bsConfig: Partial<BsDatepickerConfig>;
    dataDevModel: any[];
    vehicle_Type: any[];
    imageuploadObject = [{doctype:'Adhar card1 *',image:'',phone:'',docdate:new Date(),fill:false},
{doctype:'Adhar card2 *',image:'',phone:'',docdate:new Date(),fill:false},
{doctype:'Warrenty Card *',image:'',phone:'',docdate:new Date(),fill:false},
{doctype:'vehicle sales invoice *',image:'',phone:'',docdate:new Date(),fill:false},
{doctype:'vehicle RC',image:'',phone:'',docdate:new Date(),fill:true},
{doctype:'vehicle Photo',image:'',phone:'',docdate:new Date(),fill:true},
];
  dealerId
  sup_admin
  hrdwr
  hrdwr2
  custId
  vahanID
  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"
    }
    
  ];
  ngOnInit() {
    this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY' }, { containerClass: 'theme-dark-blue' });
    this.userId = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.dealerId=JSON.parse(window.atob(window.localStorage.token.split('.')[1])).Dealer_ID;
    if(JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin){
      this.sup_admin = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._id;
    }else{
      this.sup_admin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;
    }
    console.log("SUPPPERADMIN-----,",this.sup_admin);
    
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
     this.custId = localStorage.getItem('custId');
      if((this.custtype == false)&&(window.localStorage['Custumer'] == 'ON')){
  
       this.DealerId =  JSON.parse(window.atob(window.localStorage.Dealer_token.split(".")[1]))._id;  
      
    }
    this.deviceForm=this.fb.group({
      //ownerName:['',[Validators.required,Validators.pattern("[a-zA-Z][a-zA-Z ]+")]],
      first_name: ['', [Validators.required, Validators.pattern("[a-zA-Z][a-zA-Z ]+")]],
      last_name: ['', [Validators.required, Validators.pattern("[a-zA-Z][a-zA-Z ]+")]],
      contactNo:['',[Validators.required,Validators.pattern('[0-9 ]{10}')]],
      device_id:[''],
      address:['',Validators.required],
      state:[''],
      rtoOffice:[''],
      vehicleManufacture:[''],
      vehicleModel:[''],
      vehicleCategory:[''],
      vehicleType:[''],
      vehicleNo:['',[Validators.required,Validators.maxLength(10)]],
      chasisNo:['',Validators.required],
      engineNo:['',Validators.required],
      panic:[''],
      bsnlPlan:[''],
      hostingPlan:[''],
      SMSPlan:[''],
      city:[''],
      deviceModel:[''],
      trackingExp:new Date(this.expDate),
      eSimExpiry:[''],
      model:[''],
      email:[""],
      dealerFollowup:['',[Validators.required,Validators.pattern('[0-9 ]{10}')]],
      sim1:['',Validators.required],
      sim2:[''],
      iccid:[''],
      pin:['',[Validators.required,Validators.pattern('[0-9 ]{6}')]]


    })
     this.loadropdown()
    this.getDeviceModel();
    this.getvehDetail()
    this.getUserSetting(this.userId);
    this.getModelData()
    this. getAllState()
    var that=this
    $(document).on('change','#inventory',function() {
    var value = $('#inventory').val();
    that.checkDeviceEMI(value);
    for(var i=0;i<that.inventory.length;i++){
      if(value==that.inventory[i].IMEI){
        var date=new Date()
        var exp
        if(that.inventory[i].eSIMValidaity=="One Year"){
         exp= new Date(date.getFullYear() + 1, date.getMonth(), date.getDate()).toLocaleString();
        }else if(that.inventory[i].eSIMValidaity=="Two Year"){
           exp= new Date(date.getFullYear() + 2, date.getMonth(), date.getDate()).toLocaleString();
        }else{
           exp= new Date(date.getFullYear() + 1, date.getMonth(), date.getDate()).toLocaleString();
        }
      that.deviceForm.patchValue({
        iccid:that.inventory[i].IccidNo,
        sim1:that.inventory[i].Mob1,
        sim2:that.inventory[i].Mob2,
        eSimExpiry:new Date(exp),

        trackingExp: new Date(exp),
        
        device_id:value,
      })
        that.vahanID=that.inventory[i]['SerialNo']
        that.hrdwr=that.inventory[i].Mob1
        that.hrdwr2=that.inventory[i].Mob2
      }
    }
   
});
  }
   get f() { return this.deviceForm.controls; }
  states=[]
  getAllState(){
    this.contactService.get('/RTO_master/getAllState').subscribe((res:any)=>{
      for(var i=0;i<res.length;i++){
        this.states.push(res[i]._id.state)
      }
      // this.states=res;
    })
  }

  submit(){
    this.submitted = true;

        // stop here if form is invalid
        if (this.deviceForm.invalid) {
          const controls = this.deviceForm.controls;
        for (const name in controls) {
            if (controls[name].invalid) {
                // invalid.push(name);
                this.data_descip = "please enter valid "+name ;
                this.launch_toast();
                return;
            }
        }
        }

    for(var i=0;i<this.imageuploadObject.length;i++){
      if(!this.imageuploadObject[i].fill){
        swal(
      'Upload Error',
      'Please upload required documnets !!!',
      'error'
      )
      return;
      }
      if(i<=3 && this.imageuploadObject[i].phone==''){
        var err
        if(i==0 || i==1){
          err="Please Enter Adhar card number"
        }else if(i==2){
          err="Please Enter Warrenty card number"
        }else{
          err="Please Enter vehicle sales invoice number"
        }
         swal(
      'Upload Error',
      err,
      'error'
      )
      return;
      }
    }


    if(this.userFound){
      var data1={
        contactid:this.user._id
      }
       if(this.deviceForm.value.pin){
          data1['pin']=this.deviceForm.value.pin
        }
      this.contactService.post('/users/editUserDetails',data1).subscribe((res:any)=>{
          console.log(res);
          
          if(res.message=="Saved"){
              
            this.addDevice(this.user)
            
              //  this.addDevice(res._id)
            // this.router.navigateByUrl('/dashboard');
          }
        })


    }else{

      var expDate = new Date();
        expDate.setFullYear(expDate.getFullYear()+1);
       
        //var name=this.deviceForm.value.ownerName.split(' ')
  
        var data={
          // Dealer:this.reactiveForm.value.manager,
          custumer: true,
          expdate:new Date(expDate).toISOString(),
          first_name: this.deviceForm.value.first_name ? this.deviceForm.value.first_name:'',
          last_name: this.deviceForm.value.last_name ? this.deviceForm.value.last_name : '',
          isDealer: false,
          phone:this.deviceForm.value.contactNo,
          user_id:"",
          org_name: null,
          password:this.generatePassword(6),
          supAdmin:this.sup_admin,
          Dealer:this.userId,
          timezone: "Asia/Kolkata",
          std_code: {countryCode: "in", dialcode: "91"},
          
        }
        
        if(this.deviceForm.value.pin){
          data['pin']=this.deviceForm.value.pin
        }

        if(this.deviceForm.value.email){
          data['email']=this.deviceForm.value.email
        }
        if(this.deviceForm.value.address){
           data['address']=this.deviceForm.value.address
        }
        
        console.log(data);
  
        this.contactService.post('/users/signUp',data).subscribe((res:any)=>{
          console.log(res);
          
          if(res.message=="Registered Sucessfully" || res.message=="Registered and Message Sent Successfuly" || res.message=="Registered"){
              
            
               this.addDevice(res._id)
            // this.router.navigateByUrl('/dashboard');
          }
        })
    }

    }
    

    addDevice(data){
      var model= $('#dbselect').multipleSelect('getSelects','value');
      var type= $('#vehicleType').multipleSelect('getSelects','value');
      var deviceid
       if(this.inventoryManagement){
     
      var id=$('#inventory').multipleSelect('getSelects','value');
      deviceid=id[0]
    }else{
      deviceid=this.deviceForm.value.device_id
    }
      var newDevice = {
        devicename: this.deviceForm.value.vehicleNo,
        deviceid:  deviceid,
        // des: this.des,
        model: model[0],
       
        typdev: "Tracker",
        // emailid: this.emailid,
        Mileage : "10",
        phn: this.deviceForm.value.contactNo,
        sim_number: this.deviceForm.value.contactNo,
        created_by: this.userId,
        supAdmin:  this.sup_admin,
        // driver_name: this.driver,
        // contact_number: this.dcontact,
        device_model: model[0],
        expdate: new Date(this.expDate),
        user:data._id,
        bussinessType:1
        // License : this.licenseVal,
        // deviceDistanceVariation:this.selcetedSign+(this.deviceDistanceVariation?this.deviceDistanceVariation:'0')

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


//  hrdwr: this.deviceForm.value.sim1,
//         hrdwr1: this.deviceForm.value.sim1,
       if(this.deviceForm.value.sim1){
       newDevice['hrdwr'] = this.deviceForm.value.sim1
      }
      if(this.deviceForm.value.sim1){
       newDevice['sim_number'] = this.deviceForm.value.sim1
      }
      if(this.deviceForm.value.sim2){
       newDevice['sim_number2'] = this.deviceForm.value.sim2
      }

      if(this.deviceForm.value.eSimExpiry){
        newDevice['esim_validity'] = this.deviceForm.value.eSimExpiry
      }
      if (this.deviceForm.value.trackingExp) {
        newDevice['expdate'] = this.deviceForm.value.trackingExp
      }
      
      

       if(this.deviceForm.value.model){
        newDevice['model'] = this.deviceForm.value.model
      }
     

      if(this.deviceForm.value.dealerFollowup){
        newDevice['CID_No'] = this.deviceForm.value.dealerFollowup;
      }
      if(this.hrdwr){
        newDevice['hrdwr']=this.hrdwr
      }
      if(this.deviceForm.value.engineNo){
        newDevice['engineNo'] = this.deviceForm.value.engineNo;
      }

    if(this.deviceForm.value.city){
        newDevice['transportOfficeCity'] = this.deviceForm.value.city;
      }
      if(this.deviceForm.value.state){
        newDevice['transportOfficeState'] = this.deviceForm.value.state;
      }


      if(this.deviceForm.value.chasisNo){
        newDevice['ChassisNo'] = this.deviceForm.value.chasisNo
      }
      if(this.deviceForm.value.vehicleManufacture){
       newDevice['manufacturingCompany'] = this.deviceForm.value.vehicleManufacture;
      }

      


      if(type){
        newDevice['typeOfVehicle'] = type[0];  
      }
      if(type){
        newDevice['vehicleType'] = type[0];  
      }

      // if(this.transportOfficeCity){
      //   newDevice['transportOfficeCity'] = this.transportOfficeCity;
      // }
      if(this.deviceForm.value.state){
        newDevice['transportOfficeState'] = this.deviceForm.value.state;
      }
       if(this.deviceForm.value.iccid){
        newDevice['IccidNo'] = this.deviceForm.value.iccid;
      }
       if(this.vahanID){
        newDevice['vahanID'] = this.vahanID;
      }
      
      if(this.deviceForm.value.panic){
        newDevice['numberOfSOS'] = this.deviceForm.value.panic;
      }
     
      if(this.deviceImg != undefined){
        newDevice['deviceImage'] = this.deviceImg; 
      }

      if(this.deviceForm.value.vehicleCategory){
        newDevice['vehicleCategory'] = this.deviceForm.value.vehicleCategory; 
      }
      if(this.deviceForm.value.rtoOffice){
        newDevice['rto'] = this.deviceForm.value.rtoOffice; 
      }
      console.log("imageuploadDocument",this.imageuploadObject);
      if((this.imageuploadObject.length !=0)){
        newDevice['imageDoc'] = this.imageuploadObject ;
      }
      console.log("=======>",newDevice)
       this.Load = false;
      this.contactService.addKycDevice(newDevice)
        .subscribe((device) => {
          console.log(device);
          
          window.localStorage['DataUpdate'] = 'True';
           this.data_descip = "Device Added Successfully";
              launch_toast();
              this.router.navigateByUrl("dashboard");
            }
            // this.Load = false
          
          , (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;
              that.data_descip = "Duplicate Device ID (IMEI)";
              that.launch_toast();
             var devicesupAdmin = dupObj.supAdmin;
              var deviceDealer = dupObj.Dealer;
              var devOwner = dupObj.user;
              // debugger;
           
          }
          else {  
            var message
            if(err.status==401){
              message="Access Denied !!!"
              this.data_descip = "Access Denied !!!";
              launch_toast();

            }else{
               message="Network Error !!!"
               this.data_descip = "Network Error !!!";
              launch_toast();
            }
            console.log(err);
            
            this._flashMessagesService.show(message, { cssClass: 'alert-danger', timeout: 2000 });
            // this.Load = false
          }
        }
        )
        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);
    }

    }
  removeSpecialChar() {
    if (this.deviceForm.value.device_id) {
      this.deviceForm.controls.device_id.setValue(this.deviceForm.value.device_id.replaceAll(/[^0-9 ]/g, "").replaceAll(' ', ''));
    }
  }
 generatePassword(passwordLength) {
  var numberChars = "0123456789";
  var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var lowerChars = "abcdefghijklmnopqrstuvwxyz";
  var allChars = numberChars + upperChars + lowerChars;
  var randPasswordArray = Array(passwordLength);
  randPasswordArray[0] = numberChars;
  randPasswordArray[1] = upperChars;
  randPasswordArray[2] = lowerChars;
  randPasswordArray = randPasswordArray.fill(allChars, 3);
  return this.shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(Math.random() * x.length)] })).join('');
}

shuffleArray(array) {
  for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}
message
user
userFound:boolean=false;
onSearchChange(value){
  this.userFound=false
  this.contactMessage = '';
  console.log(value);
  var phone=this.deviceForm.value.contactNo
  if(phone.length==10){
    console.log("KLDJNDKjk");
    this.contactService.get('/users/searchUserByPhone?user='+this.userId+'&phone='+phone).subscribe((res:any)=>{
      console.log(res);
      if(res.message=="User already Present"){
        this.deviceForm.patchValue({
          //ownerName:res.data[0].first_name?res.data[0].first_name:""+" "+res.data[0].last_name?res.data[0].first_name:'',
          first_name: res.data[0].first_name ? res.data[0].first_name : "",
          last_name: res.data[0].last_name ? res.data[0].last_name : '',
          email:res.data[0].email?res.data[0].email:""
        })
        this.user=res.data[0]
        this.userFound=true;
        this.deviceForm.controls.first_name.disable();
        this.deviceForm.controls.last_name.disable();
        this.deviceForm.controls.email.disable();
      }else{
        this.userFound=false
        this.contactMessage = res.message
        console.log('this.contactMessage', this.contactMessage);
      }
    },err=>{
      console.log(err);
      this.contactMessage=err.error.message
      console.log('this.contactMessage err', this.contactMessage);
    })
  }
  
}
 device_Model: any;
  getDeviceModel() {
    this.contactService.get("/deviceModel/getDeviceModel?input=Nippon")
    // 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);
        this.loadropdown()
      })
  }

   loadropdown() {
    let that = this;
   
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
    document.getElementsByTagName("head")[0].appendChild(script);
    // ||(this.componentIdentifier === 'notification_master')
  
   
      setTimeout(() => {
        $('#dbselect').multipleSelect({
          width: 470,
          placeholder:"Select model",
          filter: true,
          single: true,
          selectAll: false
   
        })
         $('#vehicleType').multipleSelect({
            width: 470,
            placeholder: "Select Type",
            filter: true,
            single: true,
            selectAll: false  
          }) 
           $('#inventory').multipleSelect({
        width: 470,
        placeholder: 'Select IMEI',
        filter: true,
        single: true,
        selectAll: false
 
      })
    
      }, 100);
      

  }
  invalidEmeiSelected = false;
  checkDeviceEMI(id) {
   
    this.contactService.checkDeviceId(id)
      .subscribe(res => {
       try {
         this.invalidEmeiSelected = res['_body'] != 'No device Found';
       } catch (error) {
        
       }
          
        
      })
  }
   vehData:any;
getvehDetail(){
  this.contactService.getvehType(this.userId)
    .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);
        this.loadropdown()
    })
}
  
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);
// }
showUpload:boolean=true;
DeleteDocumentsField(index){
  console.log(this.imageuploadObject.length);
  if(this.imageuploadObject.length == 1){
    this.docRow = false;
    this.showUpload = false;
  }
  this.imageuploadObject.splice(index, 1);

}

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

  this.imageuploadObject[this.index].fill=true;
  console.log(this.imageuploadObject);
  const fd = new FormData();
    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';
    this.data_descip = "Image Uploaded";
    this.launch_toast();
      console.log(res);
      var resImage ='';
      resImage = res['_body'];
      console.log(res['_body']);
      this.imageuploadObject[this.index].image = resImage;
       console.log(this.imageuploadObject);
      // console.log(res);
      this.selectedFile=undefined
    },err=>{
      this.selectedFile=undefined
      this.Load= false;
      this.data_descip = "Internal server error , try again";
      this.launch_toast();
      this._flashMessagesService.show('Internal server error , try again', { cssClass: 'alert-success', timeout: 2000 }); 
    })
}
ifuploadArr: boolean ;
uploadStatus: any = 'Upload';
onUpload(imgIndex) {
  console.log(imgIndex);
  
  // console.log("selected file name =>",this.selectedFile.name);
  if(!this.selectedFile){
    swal(
      'Upload Error',
      'Please choose file before upload !!!',
      'error'
    )
  }else{
    this.imageuploadObject[this.index].fill=true;
  console.log(this.imageuploadObject);
  const fd = new FormData();
    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';
    this.data_descip = "Image Uploaded";
    this.launch_toast();
      console.log(res);
      var resImage ='';
      resImage = res['_body'];
      console.log(res['_body']);
      this.imageuploadObject[this.index].image = resImage;
       console.log(this.imageuploadObject);
      // console.log(res);
      this.selectedFile=undefined
    },err=>{
      this.selectedFile=undefined
      this.Load= false;
      this.data_descip = "Internal server error , try again";
      this.launch_toast();
      this._flashMessagesService.show('Internal server error , try again', { cssClass: 'alert-success', timeout: 2000 }); 
    })
  }
 }
documentType(docType){
  console.log("doctypeObject=>",docType);

}

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.userId,this.dealerId=JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer);
        var isDealer=JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer
        var isSuperAdmin=JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isSuperAdmin
        // var user
        // if(isSuperAdmin){
        //   var user
        // }else if(isDealer){

        // }
        var user=isSuperAdmin?this.userId:this.sup_admin?this.sup_admin:this.userId
        console.log(user);
        
        this.contactService.get('/Device_inventory/getInventoryDropdown?user='+this.userId).subscribe((res:any)=>{
          this.inventory=res;
          this.loadropdown()
        })
      }
    })
  }

   manufacturingData
  getModelData(){
     this.contactService.get('/model_master/GetNames').subscribe((res:any)=>{
      this.manufacturingData=res
    })
  }
  modelData
  selectModel(event){
  console.log(event.target.value);

  this.contactService.get('/model_master/getModel?name='+event.target.value).subscribe((res:any)=>{
    this.modelData=res
  })
  
}
cityList
onStateChange(event){
  this.contactService.get('/RTO_master/getCity?state='+event.target.value).subscribe((res:any)=>{
    this.cityList=res
  })
}
RTO
onCityChange(event){
   this.contactService.get('/RTO_master/getRTO?city='+event.target.value).subscribe((res:any)=>{
    this.RTO=res
  })
}
back(){
  this.location.back()
}
imageURL:any;
index2
 selectedDeviceFile:File;
 data_descip : any;
onDeviceImageChanged(event,index) {
  this.index2=index
  this.selectedDeviceFile = <File>event.target.files[0];
  if(this.selectedDeviceFile){
    this.Load = true;
    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){
              //  if(this.deviceImg[this.index2]){
                 this.deviceImg[this.index2]=res['_body']
              //  }else{
              //    this.deviceImg.push(res['_body'])
              //  }
             }
             this.selectedDeviceFile=undefined;
            console.log('this.deviceImg',this.deviceImg);
             this.data_descip = "Image Uploaded";
             launch_toast();
             this.Load = false;
       },err=>{
        this.data_descip = "Internal Server Error";
        launch_toast();
         this.selectedDeviceFile=undefined;
         console.log(err);
          this.Load = false;
       })

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

}
  deviceImg=['','',''];
onDeviceImageUploadUpload(index){
  if(!this.selectedDeviceFile){
    swal(
      'Upload Error',
      'Please choose file before upload !!!',
      'error'
    )
  }else{
  this.Load = true;
  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){
            //  if(this.deviceImg[this.index2]){
               this.deviceImg[this.index2]=res['_body']
            //  }else{
            //    this.deviceImg.push(res['_body'])
            //  }
           }
           this.selectedDeviceFile=undefined;
          console.log('this.deviceImg',this.deviceImg);
           this.data_descip = "Image Uploaded";
           launch_toast();
           this.Load = false;
     },err=>{
      this.data_descip = "Internal Server Error";
      launch_toast();
       this.selectedDeviceFile=undefined;
       console.log(err);
        this.Load = false;
     })
  }
 
     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);
    }
 
}
launch_toast() {
       console.log("ihjgdfds");
        var x = document.getElementById("toast")
        //console.log(x);
        x.className = "show";
        setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1500);
    }

    image;
docName
openModal(template: TemplateRef<any>,doc){
  console.log(doc);
  
   this.modalRef = this.modalService.show(template,{'backdrop':'static',class:'modal-lg modal-dialog-centered'});
  this.docName=doc.doctype
this.image="https://www.oneqlik.in"+doc.image.substring(6)
}
}
