import { Component, Inject, OnInit } from '@angular/core';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import * as moment from 'moment';
declare var swal: any;
declare var jsPDF:any;
// declare var qrcode:any;
// declare var QRCode :any;
declare var QRious:any;
declare var $:any;
@Component({
  selector: 'app-view-certificate',
  templateUrl: './view-certificate.component.html',
  styleUrls: ['./view-certificate.component.scss']
})
export class ViewCertificateComponent implements OnInit {
  devName:any;
  img1='/assets/images/liveTrackIcons/noImageAvailableIcon1.jpg'
  
phNum:any;
createdOn:any;
expOn:any;
supAdmin
DealerObj = [];
userObj = [];
// iconType:any;
simNum:any;
todayODO:any;
totalODO:any;
useridd: any;
emailId:any ="";
costumers: any = [];
deviceID: any;
userName:any;
devmodel:any;
newUserArr=[];
editTemplate:boolean=true;
deletetemplate:boolean=false;
  orignalEmail: any;
  initialUser: any;
  ExportPdf: boolean;
  devID: any;
  InvoiceDate: any;
  devicetype: any;
  fitmentDate: any;
  engineNo: any;
  typeOfVehicle: any;
  manufacturingCompany: any;
  lastFitnessDate: any;
  vehicleRegDate: any;
  vehicleManufacturingDate: any;

  IMSI: any;
  uniqueID: any;
  lattitude: any;
  longitude: any;
  userAddress: any;
  dealerAddress: any;
  CID_No: any;
  imgUrl: any;
  imgURL: any;
  companyName: any;
  companyAddress: any;
  transportOfficeCity: any;
  transportOfficeState: { data: string; };
  ChassisNo: any;
  deviceManufacturer: any;
  invoiceNum: any;
  numberOfSOS: any;
  expiration_date: any;
  organisationFlag: any;
  distributerName:any;
  distSelect: any=[];
  superAdmin: any;
  isDealer: any;
  dealerId: any;
  lastPingOn:any
  lastDeviceTime:any
  deviceImage=[];
  dealerName
  installationDate;
  ICCICD
  user: any;
  constructor(public dialogRef: MdDialogRef<ViewCertificateComponent>,
    @Inject(MD_DIALOG_DATA) public data: any ) {
      console.log(data);
      
     }

  ngOnInit() {

    this.lastDeviceTime=this.data.deviceInfo.last_device_time;
    this.lastPingOn=this.data.deviceInfo.last_ping_on
    this.devName = this.data.deviceInfo.Device_Name;
    this.devID = this.data.deviceInfo.Device_ID?this.data.deviceInfo.Device_ID:"";
    this.phNum =this.data.deviceInfo.contact_number;
    this.createdOn = this.data.deviceInfo.created_on?(new Date(this.data.deviceInfo.created_on).toISOString()):"";
    this.expOn = this.data.deviceInfo.expiration_date?(new Date(this.data.deviceInfo.expiration_date).toISOString()):"";
    // this.iconType=this.data.deviceInfo.iconType;
    this.simNum =this.data.deviceInfo.sim_number;
    this.orignalEmail =  this.data.deviceInfo.Email_ID
    this.emailId = this.data.deviceInfo.Email_ID;
    this.deviceImage=this.data.deviceInfo.deviceImage
       
    for(var i=0;i<this.deviceImage.length;i++){

        this.deviceImage[i] = 'https://www.oneqlik.in' + this.deviceImage[i].substring(6)
        
      
    }
    this.supAdmin=this.data.deviceInfo.supAdmin;
    if(this.supAdmin.imageDoc && this.supAdmin.imageDoc.length>0){
      this.supAdmin.imageDoc='https://www.oneqlik.in' + this.supAdmin.imageDoc[0].substring(6)
    }
     console.log(this.deviceImage);
     this.installationDate=this.data.deviceInfo.created_on
    this.todayODO=this.data.deviceInfo.today_odo;
    this.totalODO =this.data.deviceInfo.total_odo;
    this.deviceID = this.data.deviceInfo._id;
    this.initialUser = this.data.deviceInfo.user._id;
    this.user=this.data.deviceInfo.user
    this.userName = this.data.deviceInfo.OwnerName;
    this.userAddress = this.data.deviceInfo?this.data.deviceInfo.user.address:"";
    this.dealerName = this.data.deviceInfo.Dealer_name ;
    this.dealerId = this.data.deviceInfo.Dealer?this.data.deviceInfo.Dealer._id : ""; 
    console.log('this.dealerId',this.dealerId);
    this.dealerAddress = this.data.deviceInfo.DealerAddress;
    this.InvoiceDate = this.data.deviceInfo.invoiceDate?(new Date(this.data.deviceInfo.invoiceDate).toISOString()):"";
    this.invoiceNum = this.data.deviceInfo.invoiceNumber
    this.CID_No = this.data.deviceInfo.CID_No
    this.devicetype = this.data.deviceInfo.device_model?this.data.deviceInfo.device_model.device_type:"";
    this.ICCICD = this.data.deviceInfo.ICCICD;
    this.IMSI = this.data.deviceInfo.IMSI;
    this.uniqueID = this.data.deviceInfo.uniqueID;
    this.fitmentDate = this.data.deviceInfo.fitmentDate?new Date(this.data.deviceInfo.fitmentDate):"";
    this.expiration_date =this.data.deviceInfo.expiration_date?new Date(this.data.deviceInfo.expiration_date):"";
    this.engineNo = this.data.deviceInfo.engineNo;
    this.typeOfVehicle = this.data.deviceInfo.typeOfVehicle;
    this.manufacturingCompany = this.data.deviceInfo.manufacturingCompany;
  
    this.lastFitnessDate = this.data.deviceInfo.lastFitnessDate?new Date(this.data.deviceInfo.lastFitnessDate):"";
    this.vehicleRegDate = this.data.deviceInfo.vehicleRegDate? new Date(this.data.deviceInfo.vehicleRegDate):"";
    this.vehicleManufacturingDate = this.data.deviceInfo.vehicleManufacturingDate?new Date(this.data.deviceInfo.vehicleManufacturingDate):"";
    this.lattitude = this.data.deviceInfo.last_loc?this.data.deviceInfo.last_loc.coordinates[0]:"";
    this.longitude = this.data.deviceInfo.last_loc?this.data.deviceInfo.last_loc.coordinates[1]:"";
    this.qrCodeGenerator()
  }

   qrCodeGenerator() {
    var qrcodeDATA ="";
    if(this.userName){
      qrcodeDATA += "Owner Name : " + this.userName + " " ;
    }
    // if(this.userAddress){
    //    qrcodeDATA += "Owner Add" + this.userAddress + " " ;
    // }

    if(this.engineNo){
      qrcodeDATA += "Engine no. :" + this.engineNo + " " ;
    }
    if(this.ChassisNo){
      qrcodeDATA +=  "Chassis:" + this.ChassisNo + " " ;
    }
    if(this.uniqueID){
      qrcodeDATA +=  "UID:" + this.uniqueID + " " ;

    }
    if(this.devID){
      qrcodeDATA += "IMEI :" + this.devID +" " ;
    }
    if(this.devName){
      qrcodeDATA +=  "Device name :" +  this.devName  + " " ;
    }
    if(this.invoiceNum){
      qrcodeDATA += "Invoice Number :" + this.invoiceNum + " ";
    }
    if(this.ICCICD){
      qrcodeDATA += "ICCID :" + this.ICCICD + " " ; 
    }
    if(this.IMSI){
      qrcodeDATA += "IMSI :" + this.IMSI + " " ;
  
    }

    if(this.simNum){
      qrcodeDATA += "SIM :" +  this.simNum + " " ;
     
    }
    if(this.CID_No){
      qrcodeDATA +=   "CID no :" + this.CID_No + " " ;
     
    }
    if(this.typeOfVehicle){
      qrcodeDATA +=  "Vehicle:" + this.typeOfVehicle + " " ;
    }


 
    if((this.fitmentDate != undefined)&&(this.fitmentDate != '')){
     var fdate = new Date(this.fitmentDate);
     var  fDate =  moment(fdate).format('l');
  
     qrcodeDATA +=  "Fitment Date :" + fDate + " " ;

    }
    if((this.InvoiceDate != undefined)&&(this.InvoiceDate!='')){
      var iDate =  new Date(this.InvoiceDate);
      var invDate = moment(iDate).format('l');
      qrcodeDATA +=  "Invoice Date :" + invDate + " ";
    
    }

    if((this.vehicleRegDate != undefined)&&(this.vehicleRegDate != "")){ 
      console.log("vehRegistration Date =>",this.vehicleRegDate);
      var vehregD = new Date(this.vehicleRegDate);
      var vehRegDate = moment(vehregD).format('l');
      qrcodeDATA +=  "Reg Date :" + vehRegDate ;   
    }
     
    // var typeNumber = 4;
    // var errorCorrectionLevel = 'L';
    // var qr = qrcode(typeNumber, errorCorrectionLevel);
    // qr.addData(qrcodeDATA);
    // qr.make();
    // this.imgURL = qr.createDataURL();

   

    var qr = new QRious();
    qr.set({
      // background: 'green',
      backgroundAlpha: 0.8,
      // foreground: 'blue',
      foregroundAlpha: 0.8,
      level: 'L',
      padding: 25,
      size: 500,
      value: qrcodeDATA
    });
  

    this.imgURL= qr.toDataURL();
    
  
  
  }
  exportAsPdf() {
    var that=this
    var name="Installation Certificate "+this.devName?this.devName:"Test"+".pdf"
    console.log(this.imgURL);
    var doc = new jsPDF();
    var specialElementHandlers = {
      '#editor': function (element: any, renderer: any) {
        return true;
      }
    };
    // doc.text("Customer Copy", 110, 12);
    doc.setFontSize(10);
    doc.autoTable({
      theme: 'plain',
      html: '#testPdf', 
      styles :  {
        cellWidth : 50
      },     
      willDrawCell: data => {
        if(data.row.index === 0){ 
          data.row.height = 50;      
          data.row.cells[1].styles.halign = 'center';
           data.row.cells[1].styles.fontSize = 11;
          // data.row.cells[1].styles.lineHeight= "2.5";
          // doc.setLineHeightFactor()
           var img = new Image();
          img.src = this.supAdmin.imageDoc?this.supAdmin.imageDoc:'';
         img.crossOrigin="anonymous";
          if(this.supAdmin.imageDoc){
             img.onload = function(){
            console.log("1");
          doc.addImage(img , 'png', 10, 12,30,30)
           
      
          };
          }
          // doc.addImage(this.supAdmin.imageDoc,'JPEG', 140, 12,40,40);
          
          doc.addImage(this.imgURL,'JPEG',150, 12,30,30);
          
        }  
        if(data.row.index ===0){    
         data.row.cells[0].styles.halign = 'center';
          doc.halign = 'center';
           doc.setFontStyle('bold');
           doc.cellPadding=40
        }

        if((data.row.index ===1) ||(data.row.index ===3) || (data.row.index ===5) || (data.row.index ===7) ||(data.row.index ===8) ||(data.row.index ===11) || (data.row.index ===13)){
          doc.setFontStyle('bold');         
          
        }
        if(data.row.index ===7){
          data.row.height = 45;    
          // data.row.cells[0].styles.halign = 'center';
          // doc.halign = 'center';
        }

        if(data.row.index ===13){
          data.row.height = 25;    
          // data.row.cells[0].styles.halign = 'center';
          // doc.halign = 'center';
        }
       doc.setLineWidth(1);
     		doc.rect(7, 7, 195, 230);
   
      }
      
    });
   

    var myImage = new Image();
    myImage.src = that.deviceImage[0]?that.deviceImage[0]:this.img1;
    myImage.crossOrigin="anonymous";

    var myImage1 = new Image();
    myImage1.src = that.deviceImage[1]?that.deviceImage[1]:this.img1;
    myImage1.crossOrigin="anonymous";

    var myImage2 = new Image();
    myImage2.src = that.deviceImage[2]?that.deviceImage[2]:this.img1;
    myImage2.crossOrigin="anonymous";

    if(that.deviceImage.length==0){
       doc.save(name);
    }

    function f1() {
    return new Promise((resolve, reject) => {
      myImage.onload = function(){
      console.log("1");
      doc.addImage(myImage , 'png', 40, 150, 30, 20);
      if(that.deviceImage.length==1){
        doc.save(name);
      }
      
    };
        resolve('');
    });
}

function f3(){
 myImage2.onload = function(){
           console.log("3");
        
        doc.addImage(myImage2 , 'png', 120, 150, 30, 20);
          doc.save(name);
        
        
      };
}

function f2() {
  return new Promise((resolve, reject) => {
    myImage1.onload = function(){
        console.log("2");
        doc.addImage(myImage1 , 'png', 80, 150, 30, 20);
        if(that.deviceImage.length==2){
        doc.save(name);
      }
      };
       resolve('');
    })
      

}

f1().then(res => f2().then(res1=>f3()));


    
   
     

   
  }

    toDataURL(url, callback) {
     console.log(url);
     
        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();
    }
}
