import { Component, Inject, OnInit, TemplateRef } from '@angular/core';
import { MdDialogRef, MdSnackBar, MD_DIALOG_DATA } from '@angular/material';
import { FlashMessagesService } from 'angular2-flash-messages';
import { BsDatepickerConfig, BsModalRef, BsModalService } from 'ngx-bootstrap';
import { ViewCustomerDetailsComponent } from '../../add/view-customer-details/view-customer-details.component';
import { ContactService } from '../../contact.service';
declare var swal: any;
import { Observable, Observer } from "rxjs";
@Component({
  selector: 'app-device-doc',
  templateUrl: './device-doc.component.html',
  styleUrls: ['./device-doc.component.scss']
})
export class DeviceDocComponent implements OnInit {
 docRow:boolean=false;

//  adhar front - mandatory
// adhar back  - mandatory
// warranty card - mandatory
// vehicle sales invoice/vehicle RC - mandatory
// vehicle RC   - 
// vehicle Photo -
 modalRef: BsModalRef;
 disabled:boolean=false
  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:''},
];
    uploadStatus: any = 'Upload';
  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"
    }
    
  ];
    bsConfig: Partial<BsDatepickerConfig>;
    imageDoc;
    show:boolean=false;
    hide:boolean=false
    title="Upload Certificates"
  data_descip: string;
  constructor(private modalService: BsModalService,public dialogRef: MdDialogRef<ViewCustomerDetailsComponent>,public snackBar: MdSnackBar,
     private contactService: ContactService, private _flashMessagesService: FlashMessagesService,@Inject(MD_DIALOG_DATA) public data: any) {
        console.log(data);
        this.hide=data.dealer_payload.hide?data.dealer_payload.hide:false;
        if(data.dealer_payload.vaahan_certificate && data.dealer_payload.state_rto_certificate_path){
          this.show=true;
          console.log(this.hide,this.show);
          
          this.title="Show Certificates";
          this.statePic=data.dealer_payload.state_rto_certificate_path;
           this.vahanPic=data.dealer_payload.vaahan_certificate;
           this.state_certifcate_date=data.dealer_payload.state_certifcate_date;
          this.vaahan_certifcate_date=data.dealer_payload.vaahan_certifcate_date
        }
        if(data.dealer_payload.kycStatus=="Approved" || data.dealer_payload.kycStatus=="Reject"){
          this.disabled=true
        }
        this.imageDoc=data.dealer_payload.imageDoc
  }
  ngOnInit() {
    this.bsConfig = Object.assign({}, { containerClass:  'theme-dark-blue' });
  }


   
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);
}
selectedFile: File;
statePic;
vahanPic
onFileChanged(event1,type) { 
  this.selectedFile = <File>event1.target.files[0];
  console.log(this.selectedFile,type); 

  var fileToUpload = event1.target.files.item(0);

    //Show image preview
    if(type=="state"){
      console.log("in STATE");
      
      let reader = new FileReader();
      reader.onload = (event: any) => {
        this.statePic = event.target.result;
        reader.readAsDataURL(fileToUpload);
      }

    }else{
       let reader = new FileReader();
      reader.onload = (event: any) => {
        this.vahanPic = event.target.result;
        reader.readAsDataURL(fileToUpload);
      }
      
    }

}
Load:Boolean=false;
ifuploadArr:Boolean=false;
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']);
      if(imgIndex=='vahan'){
        this.vahanPic=resImage
      }else{
        this.statePic=resImage
      }
      // 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 }); 
    })
  }
 }
showUpload
 DeleteDocumentsField(index){
  console.log(this.imageuploadObject.length);
  if(this.imageuploadObject.length == 1){
    this.docRow = false;
    this.showUpload = false;
  }
  this.imageuploadObject.splice(index, 1);

}
//  vaahan_certificate:{
//       type:String
//     },
//     state_rto_certificate_path:{
//       type:String
//     },
//     vaahan_certifcate_date:{
//       type:Date
//     },
//     state_certifcate_date:{
//       type:Date
//     },
vaahan_certifcate_date;
state_certifcate_date;
submit(){

  if(this.vahanPic && this.statePic){
    var request={
      _id:this.data.dealer_payload._id,
      device_model: this.data.dealer_payload.device_model._id,
      vehicleType:this.data.dealer_payload.device_model._id,
      vaahan_certificate:this.vahanPic,
      state_rto_certificate_path:this.statePic,
      vaahan_certifcate_date:new Date(),
      state_certifcate_date:new Date()
    }
  console.log(request);
  
    this.contactService.editdevice(request).subscribe((res)=>{
      this.dialogRef.close('yes')
    })

  }else{
    this.data_descip = "All Documents are mandatory !!!"; 
    launch_toast();
    

     this._flashMessagesService.show('All Documents are mandatory', { cssClass: 'alert-danger', timeout: 2000 }); 
  }
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);
    }

}
image
number
key=[];
value=[];
titleForDoc

openModal(template: TemplateRef<any>,doc){
   this.modalRef = this.modalService.show(template,{'backdrop':'static',class:'modal-dialog-centered'});
  //  this.number=doc.phone;
  var name=(this.data.dealer_payload.user?this.data.dealer_payload.user.first_name?this.data.dealer_payload.user.first_name:"":''+" "+
      this.data.dealer_payload.user?this.data.dealer_payload.user.last_name?this.data.dealer_payload.user.last_name:"":'')
  this.titleForDoc=doc.doctype?doc.doctype=="Adhar card1"?"Adhar card Front":doc.doctype=="Adhar card2"?"Adhar card Back":doc.doctype:doc.doctype
  this.key=[];
  this.value=[]
   if(doc.doctype=="Adhar card1" || doc.doctype=="Adhar card1 *"){
     this.key=['Name',"Address","Adhaar no"];
     this.value=[name,
      this.data.dealer_payload.user?this.data.dealer_payload.user.address?this.data.dealer_payload.user.address:"":'',
      doc.phone]
    
   }else if(doc.doctype=="Adhar card2"  || doc.doctype=="Adhar card2 *"){
      this.key=['Name',"Address","Adhaar no"];
     this.value=[this.data.dealer_payload.user?this.data.dealer_payload.user.first_name?this.data.dealer_payload.user.first_name:"":''+" "+
      this.data.dealer_payload.user?this.data.dealer_payload.user.last_name?this.data.dealer_payload.user.last_name:"":'',
      this.data.dealer_payload.user?this.data.dealer_payload.user.address?this.data.dealer_payload.user.address:"":'',
      doc.phone]

   }else if(doc.doctype=="vehicle sales invoice"|| doc.doctype=="vehicle sales invoice *" ){
      this.key=['Name',"Address","Chassis no","Engine no","Number"];
     this.value=[name,
      this.data.dealer_payload.user?this.data.dealer_payload.user.address?this.data.dealer_payload.user.address:"":'',
      this.data.dealer_payload.engineNo?this.data.dealer_payload.engineNo:"",
      this.data.dealer_payload.ChassisNo?this.data.dealer_payload.ChassisNo:"",
      doc.phone]


   }else if(doc.doctype=="vehicle RC"|| doc.doctype=="vehicle RC"){
      this.key=['Name',"Vehicle Number","Address","Engine No.","Chassis No.","Number"];
      this.value=[name,
      this.data.dealer_payload.user?this.data.dealer_payload.user.address?this.data.dealer_payload.user.address:"":'',
      this.data.dealer_payload.Device_Name?this.data.dealer_payload.Device_Name:"",
      this.data.dealer_payload.engineNo?this.data.dealer_payload.engineNo:"",
      this.data.dealer_payload.ChassisNo?this.data.dealer_payload.ChassisNo:"",
      doc.phone]
   }
   else if(doc.doctype=="vehicle Photo"){
     this.key=['Name',"Vehicle Number","IMEI.","Number"];
      this.value=[name,
      this.data.dealer_payload.Device_Name?this.data.dealer_payload.Device_Name:"",
      this.data.dealer_payload.Device_ID?this.data.dealer_payload.Device_ID:"",

      doc.phone]
//      Warranty card
// 1. Name
// 2. IMEI no
// 3. Mobile no
// 4. Address
// 5. Vehicle chassi no
// 6. Engine number
// 7 vehicle RC
   } else if(doc.doctype=="Warrenty Card" || doc.doctype=="Warrenty Card *"){
     this.key=['Name',"Vehicle Number","IMEI.","Address","Engine No.","Chassis No","Number"];
      this.value=[name,
      this.data.dealer_payload.Device_Name?this.data.dealer_payload.Device_Name:"",
      this.data.dealer_payload.Device_ID?this.data.dealer_payload.Device_ID:"",
        this.data.dealer_payload.user?this.data.dealer_payload.user.address?this.data.dealer_payload.user.address:"":'',
         this.data.dealer_payload.engineNo?this.data.dealer_payload.engineNo:"",
      this.data.dealer_payload.ChassisNo?this.data.dealer_payload.ChassisNo:"",

      doc.phone]
     
   }
this.image='https://www.oneqlik.in'+doc.image.substring(6)
}

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

submit1(status){

  if(status=="reject"){
    swal({
  title: 'Please Enter Remark',
  input: 'text',
  inputAttributes: {
    autocapitalize: 'off'
  },
  showCancelButton: true,
  confirmButtonText: 'Submit',
  showLoaderOnConfirm: true,
  
}).then((result) => {
   console.log(result)
    if(!result){
       swal({
      title: "Remark is mandatory",
    })
    }else{
      var request={
            _id:this.data.dealer_payload._id,
            device_model: this.data.dealer_payload.device_model._id,
            vehicleType:this.data.dealer_payload.device_model._id,
            kycStatus:'Reject',
            remark:result,
            kycApprovalDate:new Date()
          }
        console.log(request);
        var title
          if(status=="reject"){
            title="KYC Rejected"
          }else{
            title="KYC Approved"
          }
          this.contactService.editdevice(request).subscribe((res)=>{
            swal({
             title:title,
            })
            this.dialogRef.close('yes')
          })
    }

  
  
})

  }else{
     var request={
            _id:this.data.dealer_payload._id,
            device_model: this.data.dealer_payload.device_model._id,
            vehicleType:this.data.dealer_payload.device_model._id,
            kycStatus:'Approved',
            kycApprovalDate:new Date()
            
          }
          this.contactService.editdevice(request).subscribe((res)=>{
             swal({
              title: "KYC approved successfully",
             })
            this.dialogRef.close('yes')
          })
  }
}

base64Image
downloadImage(imageUrl,name) {
 
    this.getBase64ImageFromURL(imageUrl).subscribe(base64data => {
      this.base64Image = "data:image/jpg;base64," + base64data;
      // save image to disk
      var link = document.createElement("a");

      document.body.appendChild(link); // for Firefox

      link.setAttribute("href", this.base64Image);
      link.setAttribute("download", name);
      link.click();
    });
  }

  getBase64ImageFromURL(url: string) {
    return Observable.create((observer: Observer<string>) => {
      const img: HTMLImageElement = new Image();
      img.crossOrigin = "Anonymous";
      img.src = url;
      if (!img.complete) {
        img.onload = () => {
          observer.next(this.getBase64Image(img));
          observer.complete();
        };
        img.onerror = err => {
          observer.error(err);
        };
      } else {
        observer.next(this.getBase64Image(img));
        observer.complete();
      }
    });
  }

  getBase64Image(img: HTMLImageElement) {
    const canvas: HTMLCanvasElement = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx: CanvasRenderingContext2D = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    const dataURL: string = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
  }

}
