import { Component, OnInit, Inject,ViewChild ,ElementRef} from '@angular/core';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { ContactService } from '../../contact.service';
declare var jsPDF : any;
declare var html2canvas :any;
import * as moment from 'moment';



@Component({
  selector: 'app-normal-cert',
  templateUrl: './normal-cert.component.html',
  styleUrls: ['./normal-cert.component.scss']
})
export class NormalCertComponent implements OnInit {
  @ViewChild('content') content : ElementRef;
  certificateImgage: any;
  customerName: string;
  address: any;
  device_name: any;
  engineno: any;
  chessisno: any;
  imei: any;
  sim_number: any;
  fromDate: any;
  todate: any;
  imgurl: any;
  validity: any;
  dealerName
  dealerAddress;
  manufacturer
  deviceModel
  dealerPhone;
  convertedImage: any;
  constructor(public dialogRef: MdDialogRef<NormalCertComponent>,
    @Inject(MD_DIALOG_DATA) public data: any,private contactService: ContactService) {
      console.log(data);
      var devObject = data.deviceInfo;
    this.dealerName = devObject.Dealer_name ? devObject.Dealer_name:''
    this.dealerAddress = devObject.DealerAddress ? devObject.DealerAddress:''
    this.dealerPhone = devObject.Dealer ? devObject.Dealer.phone:''
    this.deviceModel = devObject.device_model ? devObject.device_model.device_type:''
     if(devObject.user){
       var fName =devObject.user?devObject.user.first_name:"";
       var lName = devObject.user?devObject.user.last_name:"";
       console.log(fName+ lName)
       this.customerName =fName + " " + lName  }
       this.address = devObject.user?devObject.user.address:"NA";
       this.device_name =(devObject.Device_Name?devObject.Device_Name:"NA");
       this.engineno =(devObject.engineNo?devObject.engineNo:"NA");
       this.chessisno = (devObject.ChassisNo? devObject.ChassisNo:"NA");
       this.imei =(devObject.Device_ID?devObject.Device_ID:"NA");
       this.sim_number =devObject.sim_number?devObject.sim_number:"NA";
       if(devObject.created_on){   
         var created_time = new Date(devObject.created_on);
         this.fromDate= moment(created_time).format('DD-MM-YYYY');


       }else{
        this.fromDate = 'NA';
       }
       if(devObject.expiration_date){
        
         var e_time = new Date(devObject.expiration_date);
         this.todate =    moment(e_time).format('DD-MM-YYYY');

       }else{
        this.todate ="NA"
       }

       this.validity =  "VELIDITY OF DEVICE" + ":"+" " + this.fromDate + " " + 'TO' + " " + this.todate;
       

     }

  ngOnInit() {
    var that = this ;
    if (localStorage.getItem('profilePic')){
      this.imgurl = localStorage.getItem('profilePic');
    }else
    this.imgurl= '../../assets/image/f2_logo.png';
  this.toDataURL(this.imgurl, function(dataUrl) {
  console.log('RESULT:', dataUrl)
  that.convertedImage = dataUrl ; 
})
  }



  


  cancel(){
    this.dialogRef.close('cancel');
  }
  

  toDataURL(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
      var reader = new FileReader();
      reader.onloadend = function() {
        callback(reader.result);
      }
      reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
  }
  
  download1(){
    var that = this;
    var doc = new jsPDF();
   
    var specialElementHandlers = {
      '#editor': function (element: any, renderer: any) {
        return true;
      }
    };

    doc.autoTable({
      theme: 'plain',
      html: '#testPdf', 
      margin:{left:25,right:25},
      styles :  {
        cellWidth : 50
      }, 
         
      willDrawCell: data => {
        if(data.row.index === 0){ 
          data.row.height = 25;             
          // data.row.cells[0].styles.lineHeight= "30";
          // doc.setLineHeightFactor()   
          doc.addImage(that.convertedImage,'JPEG',25, 10,25,15);
        }  

        doc.text(28, 200, 'DEALER STAMP & SEAL');
        doc.text(100, 200, 'CUSTOMER SIGNATURE');

        if((data.row.index === 1)){
          // data.row.cells[0].styles.halign = 'right';
          data.row.height = 15;             
        }
        
        if((data.row.index === 7)){
             
        }
        if((data.row.index===1)||(data.row.index===4)||(data.row.index===5)){
          doc.setFontStyle('bold');    
        }
        
      }
      
    });
    doc.save('Device_Cert.pdf');

  }
  download(){
console.log("in ");
    
    var that=this
    let doc = new jsPDF('p', 'pt', 'a4');
    doc.setFontSize(18);
    // doc.text('Travel Path Report', 350, 30);
    doc.text("INSTALLATION CERTIFICATE", 160, 30);
    doc.setFontSize(13);
    doc.text("DECLARATION :", 40, 120);
    doc.addImage(that.convertedImage, 'JPEG', 500, 10, 80, 80);
    doc.setFontSize(10);
    doc.text("This is to certify that the vehicle with below mentioned details has been fitted with VTS device, programmed with GPRS.", 50, 140);

    var header = function (data) {
      doc.setFontSize(13);
      doc.setTextColor(40);
      doc.setFontStyle('normal');
      //doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50);

      doc.text("VEHICLE DETAILS :", data.settings.margin.left, 190);
    };
    
    doc.autoTable({
      // beforePageContent: header,
      beforePageContent: header,
      startY: doc.autoTableEndPosY() + 200,
      theme: 'grid',
      margin:{top:80},
      headStyles: { fontSize: 10 },
      bodyStyles: { fontSize: 10 },

      // head: [['ID', 'Name', 'Country']],
      body: [['Registration No :',this.device_name, 'Chassis No:',that.chessisno],
        ['Vehicle Owner :', that.customerName, ],
        ['Model of Vehicle :', this.deviceModel, 'Year of Manufacture', '']],

    });
    var header1 = function (data) {
      doc.setFontSize(13);
      doc.setTextColor(40);
      doc.setFontStyle('normal');
      //doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50);
      doc.text("VTS DETAILS :", data.settings.margin.left, 310);
    };
    doc.autoTable({
      beforePageContent: header1,
      theme: 'grid',
      headStyles: { fontSize: 10 },
      bodyStyles: { fontSize: 10 },
      startY: doc.autoTableEndPosY() + 50,
      // head: [['ID', 'Name', 'Country']],
      body: [['Serial No:', that.imei, 'GPRS SIM No :',  that.sim_number],
        ['Date of Installation :', '', 'Technician Name:',''],
        ['Comments / Remarks :', '', ]],
    });
    var header2 = function (data) {
      doc.setFontSize(13);
      doc.setTextColor(40);
      doc.setFontStyle('normal');
      //doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50);
      doc.text("DEALER DETAILS :", data.settings.margin.left, 420);
    };
    doc.autoTable({
      beforePageContent: header2,
      startY: doc.autoTableEndPosY() + 50,
      theme: 'grid',
      headStyles: { fontSize: 10 },
      bodyStyles: { fontSize: 10 },

      // head: [['ID', 'Name', 'Country']],
      body: [['Date of Inspection :', '', 'Next calibration date :', ''],
        ['Installation Hub Name :', ''],
        ['Address & Phone :', that.dealerAddress, that.dealerPhone]],
    });
    doc.setFontSize(9);
    doc.text("1) 1 YEAR WARRANTY ON THE UNIT FROM DATE OF INSTALLATION AGAINST ANY MANUFACTURING DEFECT", 50, 540);
    doc.text("2) WARRANTY WILL BE VOID IF ANY REPAIR / MISUSE / TAMPERING WITHOUT WRITTEN CONCENT FROM DEALER", 50, 555);
    doc.text("3) RENEWAL ON OR BEFORE THE NEXT CALIBRATION DATE ENSURES THE UNINTERRUPTED SERVICE", 50, 570);
    doc.text("4) SOFT COPY OR HARD COPY OF VALID CERTIFICATE IS MANDATORY FOR ANY SERVICE REQUESTS", 50, 585);
    doc.text("5) ALL SERVICE REQUESTS SHOULD BE COMMUNICATED VIA EMAIL TO SUPPORT@AURATRAQ.COM", 50, 600);
    doc.text("6) THIS CERTIFICATE IS VALID ONLY WITH STAMP & SIGNATURE", 50, 615);

    doc.text("Stamp & Signature", 450, 795);

    
    doc.save('table.pdf');  
    // doc.output('dataurlnewwindow'); //to check pdf generate

    // }).then(canvas => {
    //   const contentDataURL = canvas.toDataURL('image/png')
    //   let pdf = new jsPDF('l', 'cm', 'a4'); //Generates PDF in landscape mode
    //   // let pdf = new jspdf('p', 'cm', 'a4'); Generates PDF in portrait mode
    //   pdf.addImage(contentDataURL, 'PNG', 0, 0, 29.7, 21.0);
    //   pdf.save('Filename.pdf');
    // }); 
  }

}

