import { Component, Inject, OnInit, TemplateRef } from '@angular/core';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { BsDatepickerConfig, BsModalRef, BsModalService } from 'ngx-bootstrap';
import { ContactService } from '../../contact.service';
import { OtpScreenComponent } from '../otp-screen/otp-screen.component';
import { saveAs } from 'file-saver';
import { ShowPullDataLinkComponent } from '../show-pull-data-link/show-pull-data-link.component';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ResetPasswordComponent } from '../reset-password/reset-password.component';
declare var swal: any;
declare var $:any;
@Component({
  selector: 'app-view-customer-details',
  templateUrl: './view-customer-details.component.html',
  styleUrls: ['./view-customer-details.component.scss']
})
export class ViewCustomerDetailsComponent implements OnInit {
  testDocuments;
   documentList = [
    {
      "docId": "Adhar card",
      "docName": "Adhar Card"
    },
    {
      "docId": "voter Id",
      "docName": "Voter Id"
    },
    {
      "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": "Other",
      "docName": "Other"
    }
    
  ];
  otp
  data_descip
  doclist:boolean=true;
  showUpload: boolean=false;
  Load: boolean;
  uploadStatus: any = 'Upload';
  ifuploadArr: boolean ;
  useridForDocUpload: any;
  disableDelete: boolean;
  errorMsg: string;
  showError: boolean = false;
  dealerStatus: any;
  superAdmin: any;
  superadminAccess: any;
  imageuploadObject = [];
  label: any;
   modalRef: BsModalRef;
  header: any;
  useridd;
  options: any=[{selectedValue : '',value:''}];
  transactionForm:FormGroup;
  items=['New GPS','GPS Renewal','Service','SIM + Software','Software','SIM']
  PaymentMode =['Cash','Cheque','Net Banking','UPI','Wallet','Others']
  custtype: any;
  bsConfig: Partial<BsDatepickerConfig>;
  constructor(public dialogRef: MdDialogRef<ViewCustomerDetailsComponent>,private fb:FormBuilder,public dialog: MdDialog,private contactService: ContactService,private modalService: BsModalService,
    @Inject(MD_DIALOG_DATA) public data: any) {
      this.testDocuments = this.data.imageDoc;
      console.log(data,this.testDocuments);
      this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
      if(this.testDocuments){
        console.log("INDJj");
        
        if(this.testDocuments.length != 0){
        for(var i=0;i<this.testDocuments.length;i++){
          if(this.testDocuments[i].image){
            var ext=this.testDocuments[i].image.split('.').pop(); 
            this.testDocuments[i].ext=ext
            this.testDocuments[i].image=(this.testDocuments[i].image).substring(6);
    
          }
        }
         this.doclist = false;
      }
      }else{
        this.doclist = true;
      }
    
    
       this.useridForDocUpload = this.data.dealer_id?this.data.dealer_id:this.data._id
       this.getVehicles(this.data)
    }

  ngOnInit() {
     this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
     this.transactionForm=this.fb.group({
      Amount:[''],
      Customer_ID:this.data._id,
      Status:[''],
      TransactionID:[''],
      Remarks:[''],
      VehicleNo:[''],
      Items :[''],
      PaymentMode:[''],
      supAdmin: this.useridd,
      date:new Date()
     })
     this.getPayments()
     
  }


getVehicles(data:any){
  
  this.contactService.get('/devices/getDeviceByUser?email='+data.email+'&id='+data._id).subscribe((resp:any) => {
    console.log('device api respoonse=>',resp);
    for(let i=0;i<resp.devices.length;i++){
  
            // if(resp.devices[i].type_of_device =="Tracker"){
              let a ={
                value : resp.devices[i].Device_Name,
                viewValue:resp.devices[i].Device_Name,
                did:resp.devices[i].Device_ID,
                id:resp.devices[i]._id,
                user:resp.devices[i].user,
                  
              }
             
            
                a['selectedValue'] = resp.devices[i]._id ; 
              
              this.options.push(a);
            // }
          }
          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: 384,
          placeholder: 'Select Vehicles',
          filter: true,
          // single: false,
          // selectAll: false
   
        })
    
      //  that.showLoader = false;
      }, 100);
      

   
  }

  verify(){

     let dialogRef = this.dialog.open(OtpScreenComponent,{
        //   width: '800px',
        // //  height: '600px', 
        disableClose: true,
        data:this.data
    
        });
    
        dialogRef.afterClosed().subscribe(result => {
         console.log(result);
         
          if (result.value == "done") {
          this.data.phone_verfi=true;
    
          }
        });

  }


  
  downloadDoc(doc:any){
    console.log(doc.image);
    var imageLink = doc.image; 
    var filetext  = imageLink.split('.');
    console.log(filetext[1]);
    
    this.contactService.DownloadDocument(doc.image).subscribe(res=>{
      console.log(res);
      this.saveToFileSystem(res,doc,filetext[1]);
    },err=>{
      console.log(err);
    })
  }

  private saveToFileSystem(response,doc,fileex) { 
    console.log(response._body);
    if(fileex == 'pdf'){
      console.log("Inside pdf");
      var blob = new Blob([response._body], { type: "application/pdf" });
    }else{
      var blob = new Blob([response._body], { type: "image/png" });
    }
   
    var filename = doc.doctype+'_'+doc.phone;
    // console.log(filename);
    saveAs(blob,filename);
  }

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

  }

  Adddocuments(doc){
    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:''};
       this.imageuploadObject.push(obj);
       console.log(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) { 
    console.log(event.target.files[0]);
    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;
   
        console.log(res);
        var resImage ='';
        resImage = res['_body'];
        console.log(res['_body']);
        this.imageuploadObject[imgIndex].image = resImage;
         console.log(this.imageuploadObject);
    
      },err=>{
        this.Load= false;
        // this._flashMessagesService.show('Internal server error , try again', { cssClass: 'alert-success', timeout: 2000 }); 
      })
    }
   }


   SaveDocuments(actionString,objIndex){
    console.log(this.imageuploadObject);
    console.log("Save");
    var imageuploadArr = {
      _id : this.useridForDocUpload
    }
    if(actionString == 'deldoc'){
      this.testDocuments.splice(objIndex,1);
      console.log("testArray after deleting doc =>",this.testDocuments); 
    }
     for(var d = 0 ;d <this.imageuploadObject.length;d++){
      if((this.imageuploadObject[d].doctype == "")&&(this.imageuploadObject[d].image == "")&&(this.imageuploadObject[d].phone == "")){   
            this.imageuploadObject.splice(d,1);         
      }
    }
   console.log(this.imageuploadObject);
   for(var j = 0;j< this.testDocuments.length;j++){
        console.log(this.testDocuments[j]);
        this.imageuploadObject.push(this.testDocuments[j]);
   }
   
   imageuploadArr['imageDoc'] = this.imageuploadObject;
   console.log(this.imageuploadObject.length);
   this.contactService.updateImage(imageuploadArr).subscribe(res=>{
     console.log(res);
     if(actionString != 'deldoc'){
      // this.thisDialogRef.close("imageupdated"); 
     }   
     if(actionString == 'deldoc'){
      this.imageuploadObject = [];
     }
   },err=>{
    // this._flashMessagesService.show('Internal server error , try again', { cssClass: 'alert-success', timeout: 2000 }); 
   })
   }

   expand(value){
     console.log(value);
     if(value){
       document.getElementById('container').style.width='80vh'
     }else{
       
     }
     

   }

   
changeKYC(event){
  console.log(event);
  var req={
    user:this.data.dealer_payload._id,
    status:event
  }
  this.contactService.changeKycStatus(req).subscribe(res=>{
    console.log(res);
    //  this.tost1('kyc');
    this.dialogRef.close('yes')
  })
  
}

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

  onChange(cust, ev) {
 
    let status = ev;
    // console.log(status.checked);

    let cust_status = cust;
    let cust_id = cust._id;
    let cust_activity = cust.status
    // console.log(cust_activity);


    var cust_load = {
      "uId": cust_id,
      "loggedIn_id": this.useridd,
      "status": status.checked
    }
    // console.log(cust_id);


    console.log(cust_load);
    this.contactService.custStatus(cust_load)
      .subscribe(res => {
        let a = res;
        // console.log(a);
        // console.log("Status changed");
      })
  }

  accountStatus:boolean = true;
accountStatusOnChange(custObj, event){


    console.log(custObj,event.checked);
    var payload = {
      accountSuspended : event.checked,
      acoountId : custObj._id  ,
      suspendedBy : 'distributer' 
    }
      var that = this;
    swal("Are you sure ?", "Do you want to change account status ?").then((ans)=>{
      console.log(ans);
      that.contactService.accountSuspend(payload).subscribe(res=>{
        console.log(res);
        // that.getCustomer();
        that.data_descip =  "Account Status Changed";
        launch_toast();
        function launch_toast() {
          // console.log(divid);
           var x = document.getElementById("toast")
           //console.log(x);
           x.className = "show";
           setTimeout(function(){ x.className = x.className.replace("show", ""); }, 4500);
       }    
      })
     
    },err=>{
      // that.getCustomer();
      console.log(err);
    });
  
}

adm_alert:boolean=false;
alertStatus(ev,cobj){
 
  var aAlert= ev.checked;
 
  var pld= {
    uid : cobj._id,
    adminAlert : aAlert
  }
  console.log(pld);
  this.contactService.setlanguage(pld).subscribe(res=>{
    console.log(res);
    // this.tost1('alertset');
  })

}

dealerAlert(ev,cobj){
 
  var aAlert= ev.checked;
 
  var pld= {
    uid : cobj._id,
    dealerAlert : aAlert
  }
  console.log(pld);
  this.contactService.setlanguage(pld).subscribe(res=>{
    console.log(res);
    // this.tost1('alertset');
  })

}


generatePullData(ev,data){
  // if(ev.checked){
    console.log(ev,data);

    var request={
      pullData:ev.checked,
      pass:data.pass
    }
    if(data.user_id){
      request['user_id']=data.user_id
    }
     if(data.phone){
      request['phone']=data.phone
    }
    console.log(request);
    
    this.contactService.post('/users/getToken',request).subscribe((res:any)=>{
      console.log(res);
      if(ev.checked){
        let dialogRef = this.dialog.open(ShowPullDataLinkComponent, {
          width: '800px',
        //  height: '600px', 
          data:res.token
        });
      }
      
    })


}

show:boolean=false;
 verify1(){
  console.log(this.otp);
    this.contactService.post('/users/verifyOtp',{user:this.data._id,otp:this.otp}).subscribe((res:any)=>{
      this.data_descip = res.message;
      launch_toast()
      this.dialogRef.close({value:'done'});
    },err=>{
      console.log(err);
      var message=JSON.parse(err._body);
      console.log(message);
      
      this.data_descip = "You entered wrong OTP"
      this.show=true;
      var that=this;
      //  this.data_descip = res.message;
      launch_toast()
     setTimeout(function () {that.show=false  }, 4500);
    })

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

 add:boolean=true;

addPayment(){
  if(this.buttonText=="Update"){
    this.updatePayment()
  }else{
    this.transactionForm.patchValue({
      VehicleNo:$('#dbselect').multipleSelect('getSelects','value')
  
    })
  
    this.contactService.post('/CustomerPayment/add',this.transactionForm.value).subscribe(res=>{
      // console.log(res);
        this.getPayments()
    })
  }


}
payementsArray
getPayments(){
this.payementsArray=[]
  this.contactService.get('/CustomerPayment/get?Customer_ID='+this.data._id).subscribe(res=>{
    // console.log(res);
    this.payementsArray=res
  })

}
paymentId
buttonText="Save"
editPayment(data){
  this.paymentId=data._id
  this.transactionForm.patchValue({
         Customer_ID:data.Customer_ID,
        Amount:data.Amount,
        Items:data.Items,
        PaymentMode:data.PaymentMode,
        Remarks:data.Remarks,
        Status:data.Status,
        TransactionID:data.TransactionID,
        VehicleNo:data.VehicleNo,
        supAdmin:data.supAdmin,
  })
this.buttonText="Update";
this.add=!this.add;
  
}

updatePayment(){
  this.contactService.post('/CustomerPayment/update',{id:this.paymentId,data:this.transactionForm.value}).subscribe(res=>{
    this.getPayments()
  })
}

deletePayment(data){
  this.contactService.post('/CustomerPayment/delete',{_id:data._id}).subscribe(res=>{
    this.getPayments()
  })
}

addButton(){
  this.add=!this.add;
  this.buttonText="Save";
  // this.transactionForm.reset()
}

shareUserCredential(){
    console.log('this.data',this.data);
    var cost_id = this.data._id;
    this.contactService.shareCostumerInfo(cost_id).subscribe(res=>{
      console.log(res);
      let message =res.message;
      let action
      // this.snackBar.open(message, action, {
      //   duration: 4000,
      // });
   
    },err=>{
      console.log(err);
    })

    
  }

  resetPassword(){
    // console.log("Inside reset",cust_array);
    let dialogRef = this.dialog.open(ResetPasswordComponent, {
      width: '400px',
      data : this.data
    //  height: '600px', 

    });

    dialogRef.afterClosed().subscribe(result => {
      // console.log(result);
      if (result == "succ") {
        // this.tost1("password_changed");
        this.ngOnInit();
      }

      if (result == "close") {
        // this.tost1("succ");
        // this.ngOnInit();
      }
    });
    
  }

}
