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';
declare var $:any;
declare var swal: any;
@Component({
  selector: 'app-new-edit-device',
  templateUrl: './new-edit-device.component.html',
  styleUrls: ['./new-edit-device.component.scss']
})
export class NewEditDeviceComponent implements OnInit {
 DeviceModelValue: any;
 deviceImg=["","",""];
 modalRef: BsModalRef;
  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"]
  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",]
  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
  deviceData
  deviceModel
  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
  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.deviceData=JSON.parse(localStorage.getItem('deviceData'));
    if(localStorage.getItem('deviceData')){
      
      console.log(this.deviceData);
      var data={target:{value:this.deviceData.transportOfficeState?this.deviceData.transportOfficeState:''}}
      var data1={target:{value:this.deviceData.transportOfficeCity?this.deviceData.transportOfficeCity:''}}
      var data3={target:{value:this.deviceData.manufacturingCompany?this.deviceData.manufacturingCompany:''}}
      this.selectModel(data3)
      this.onCityChange(data1)
      this.onStateChange(data);
      this.imageuploadObject=this.deviceData.imageDoc
      this.deviceImg=this.deviceData.deviceImage?this.deviceData.deviceImage:["","",""]
      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;
      this.sup_admin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;
      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;  
        
      }
      
      var fname=this.deviceData.user?this.deviceData.user.first_name?this.deviceData.user.first_name:'':"";
      var lname=this.deviceData.user?this.deviceData.user.last_name?this.deviceData.user.last_name:'':""
      this.deviceForm=this.fb.group({
        ownerName:[fname+' '+lname,[Validators.required,Validators.pattern("[a-zA-Z][a-zA-Z ]+")]],
        contactNo:[this.deviceData.user?this.deviceData.user.phone?this.deviceData.user.phone:'':'',[Validators.required,Validators.pattern('[0-9 ]{10}')]],
        device_id:[this.deviceData.Device_ID?this.deviceData.Device_ID:""],
        address:[this.deviceData.user?this.deviceData.user.address?this.deviceData.user.address:'':'',Validators.required],
        state:[this.deviceData.transportOfficeState?this.deviceData.transportOfficeState:''],
        rtoOffice:[this.deviceData.rto?this.deviceData.rto:''],
        vehicleManufacture:[this.deviceData.manufacturingCompany?this.deviceData.manufacturingCompany:''],
        vehicleModel:[this.deviceData.Model?this.deviceData.Model:''],
        vehicleCategory:[this.deviceData.vehicleCategory?this.deviceData.vehicleCategory:''],
        vehicleType:[this.deviceData.vehicleType?this.deviceData.vehicleType._id:''],
        vehicleNo:[this.deviceData.Device_Name?this.deviceData.Device_Name:'',[Validators.required,Validators.maxLength(10)]],
        chasisNo:[this.deviceData.ChassisNo?this.deviceData.ChassisNo:'',Validators.required],
        engineNo:[this.deviceData.engineNo?this.deviceData.engineNo:'',Validators.required],
        panic:[this.deviceData.numberOfSOS?this.deviceData.numberOfSOS:''],
        bsnlPlan:[''],
        hostingPlan:[''],
        SMSPlan:[''],
        city:[this.deviceData.transportOfficeCity?this.deviceData.transportOfficeCity:''],
        deviceModel:[this.deviceData.device_model?this.deviceData.device_model._id:''],
        trackingExp:new Date(this.expDate),
        eSimExpiry:[this.deviceData.esim_validity?new Date(this.deviceData.esim_validity):''],
        model:[this.deviceData.Model?this.deviceData.Model:''],
        email:[this.deviceData.user?this.deviceData.user.email?this.deviceData.user.email:'':''],
        dealerFollowup:[this.deviceData.CID_No?this.deviceData.CID_No:'',Validators.required],
        sim1:[this.deviceData.sim_number?this.deviceData.sim_number:'',Validators.required],
        sim2:[this.deviceData.sim_number2?this.deviceData.sim_number2:''],
        iccid:[this.deviceData.IccidNo?this.deviceData.IccidNo:''],
        pin:[this.deviceData.user?this.deviceData.user.pin?this.deviceData.user.pin:'':'',[Validators.required,Validators.pattern('[0-9 ]{6}')]]
        
  
      })
      console.log("DEVICEFORM=>",this.deviceForm);
    }else{
      this.location.back()
    }
    
     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();
    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),
        device_id:value
      })

        that.hrdwr=that.inventory[i].Mob1
        that.hrdwr2=that.inventory[i].Mob2
      }
    }
    var value=this.deviceData.Device_ID
    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),
        device_id:value
      })

        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) {
            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(this.userFound){
      this.addDevice(this.user)

    }else{

      var expDate = new Date();
        expDate.setFullYear(expDate.getFullYear()+1);
       
        var name=this.deviceForm.value.ownerName.split(' ')
  
        var data={
          // Dealer:this.reactiveForm.value.manager,
          contactid:this.deviceData.user._id,
          custumer: true,
          expdate:new Date(expDate).toISOString(),
          first_name:name[0]?name[0]:'',
          last_name:name[1]?name[1]:'',
          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/editUserDetails',data).subscribe((res:any)=>{
          console.log(res);
          
          if(res.message=="Saved"){
              
            
               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){
      deviceid=$('#inventory').multipleSelect('getSelects','value');
    }else{
      deviceid=this.deviceForm.value.device_id
    }
      var newDevice = {
        _id:this.deviceData._id,
        devicename: this.deviceForm.value.vehicleNo,
        deviceid:  this.deviceForm.value.device_id,
        // des: this.des,
        model: model[0],
       
        typdev: "Tracker",
        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: this.deviceForm.value.deviceModel,
        expdate: new Date(this.expDate),
        user:this.deviceData.user._id,
        kycStatus:'Pending',
        bussinessType:1
      }
       if (this.custtype) {
        newDevice['Dealer'] = this.userId;
      } else if((this.custtype == false)&&(window.localStorage['Custumer'] == 'ON') ) {
        newDevice['Dealer'] = this.DealerId
      }


//  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.sim2){
       newDevice['hrdwr1'] = this.deviceForm.value.sim2
      }

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

       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(this.deviceForm.value.eSimExpiry){
       newDevice['esim_validity'] = this.deviceForm.value.eSimExpiry;
      }
       if(this.deviceForm.value.vehicleCategory){
        newDevice['vehicleCategory'] = this.deviceForm.value.vehicleCategory; 
      }
      if(this.deviceForm.value.rtoOffice){
        newDevice['rto'] = this.deviceForm.value.rtoOffice; 
      }

      if(type){
        newDevice['typeOfVehicle'] = type[0];  
      }
       if(this.deviceForm.value.vehicleType){
        newDevice['vehicleType'] = this.deviceForm.value.vehicleType
      }

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

      if(this.deviceForm.value.panic){
        newDevice['numberOfSOS'] = this.deviceForm.value.panic;
      }
     
      if(this.deviceImg != undefined){
        newDevice['deviceImage'] = this.deviceImg; 
      }
      console.log("imageuploadDocument",this.imageuploadObject);
      if((this.imageuploadObject.length !=0)){
        newDevice['imageDoc'] = this.imageuploadObject ;
      }
      console.log("=======>",newDevice)
      //  this.Load = false;
      this.contactService.editdevice(newDevice)
        .subscribe((device) => {
          window.localStorage['DataUpdate'] = 'True';
         
              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;
             var devicesupAdmin = dupObj.supAdmin;
              var deviceDealer = dupObj.Dealer;
              var devOwner = dupObj.user;
              debugger;
           
          }
          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
          }
        }
        

    }

 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.message=undefined
  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:'',
          email:res.data[0].email?res.data[0].email:""
        })
        this.user=res.data[0]
        this.userFound=true;
        this.deviceForm.controls.ownerName.disable();
        this.deviceForm.controls.email.disable();
      }else{
        this.userFound=false
        this.message=res.message
      }
    },err=>{
      console.log(err);
      this.message=err.error.message
    })
  }
  
}
 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);
        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);
      

  }

   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;
onFileChanged(event,imgIndex) { 
  this.selectedFile = <File>event.target.files[0];
  console.log(this.selectedFile); 

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

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

   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.length==3){
              //  if(this.deviceImg[index]){
                 this.deviceImg[index]=(res['_body'])
              //  }else{
              //    this.deviceImg.push(res['_body'])
              //  }
            //  }else{
            //    this.deviceImg.push(res['_body'])

            //  }
           }
           this.Load = false;
           this.selectedDeviceFile=undefined
          console.log('this.deviceImg',this.deviceImg);
           this.data_descip = "Image Uploaded";
           launch_toast();
     },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);
    }
}
  
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.length==3){
               if(this.deviceImg[index]){
                 this.deviceImg[index]=(res['_body'])
               }else{
                 this.deviceImg.push(res['_body'])
               }
             }else{
               this.deviceImg.push(res['_body'])

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