import { Component, Inject, OnInit } from '@angular/core';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
declare var jsPDF : any;
declare var html2canvas:any;
import * as moment from 'moment';
import { ContactService } from '../../contact.service';
declare var $: any;
declare var QRious:any;
@Component({
  selector: 'app-download-certificate',
  templateUrl: './download-certificate.component.html',
  styleUrls: ['./download-certificate.component.scss']
})
export class DownloadCertificateComponent implements OnInit {
devName:any;
  img1='/assets/images/liveTrackIcons/noImageAvailableIcon.jpg'
  stamp='/assets/images/liveTrackIcons/Stamp.png'
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
  simNum1
  model
  user: any;
  org
  link: string;
  kycApprovalDate
  esim_validity;
  fitmentCertificateNo
  vahanID: any;
  myImage: HTMLImageElement;
  myImage1: HTMLImageElement;
  myImage2: HTMLImageElement;
  stamp1: HTMLImageElement;
  img: HTMLImageElement;
  gnnsModule
  gsmModule
  constructor(public dialogRef: MdDialogRef<DownloadCertificateComponent>,private contactService:ContactService,
    @Inject(MD_DIALOG_DATA) public data: any ) {
      console.log(data);
      
     }

  ngOnInit() {
    this.org=JSON.parse(localStorage.getItem('ORG'))
    if(!this.data.deviceInfo.esim_validity){
      if(this.data.deviceInfo.License=="Yearly"){
        this.esim_validity=this.data.deviceInfo.kycApprovalDate?moment(new Date(this.data.deviceInfo.kycApprovalDate), "DD-MM-YYYY").add(1, 'years').format("DD/MM/YYYY"):undefined;
      }
    }else{
      this.esim_validity=this.data.deviceInfo.esim_validity?moment(new Date(this.data.deviceInfo.esim_validity)).format("DD/MM/YYYY"):undefined
    }
    this.fitmentCertificateNo=this.data.deviceInfo.fitmentCertificateNo;
    this.ChassisNo=this.data.deviceInfo.ChassisNo;
    this.lastDeviceTime=this.data.deviceInfo.last_device_time;
    this.numberOfSOS=this.data.deviceInfo.numberOfSOS
    this.kycApprovalDate=this.data.deviceInfo.kycApprovalDate 
    this.model=this.data.deviceInfo.Model
    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.simNum1 =this.data.deviceInfo.sim_number2;
    this.orignalEmail =  this.data.deviceInfo.Email_ID
    this.emailId = this.data.deviceInfo.Email_ID;
    this.deviceImage=this.data.deviceInfo.deviceImage
       if(this.org.imageDoc && this.org.imageDoc.length>0){
      this.org.imageDoc='https://www.oneqlik.in' + this.org.imageDoc[0].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.Device_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:"";
    if(this.devicetype=="Nippon-NVT-1820"){
      this.gsmModule='Telit GE910'
    }else if(this.devicetype=="Nippon-NVT-1820"){
      this.gnnsModule="Telit, Jupiter SL869T3-| Nav|C/IRNSS";
       this.gsmModule='Telit GE910'
    }else{
      this.gnnsModule="Quectel L89(GPS+IRNSS)";
       this.gsmModule='Quectel M66'
    }

    for(var i=0;i<this.deviceImage.length;i++){

        this.deviceImage[i] = this.deviceImage[i] &&  this.deviceImage[i]!=""?'http://nipponsecura.in' + this.deviceImage[i].substring(6):''
        
      
    }
    this.ICCICD = this.data.deviceInfo.IccidNo;
    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.vahanID= this.data.deviceInfo.vahanID?this.data.deviceInfo.vahanID:'';
    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.getLocationLink()
    var that=this
       this.myImage = new Image();
    this.myImage.src = this.deviceImage[0]?this.deviceImage[0]:this.img1;
    this.myImage.crossOrigin="anonymous";

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

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

    this.stamp1=new Image();
    this.stamp1.src=this.stamp;
    this.stamp1.crossOrigin="anonymous";

    this.img = new Image();
     this.img.src = this.org.imageDoc?this.org.imageDoc:'';
     this.img.crossOrigin="anonymous";
    // one()
    // function one(){
    //   stamp.onload = function(){
        

    
    //         two()
    //         doc.addImage(stamp , 'png', 15,210,30,30);
    //         };
    // }

    // function two(){
    //   img.onload = function(){
    //         console.log("-1");
    //         three()
    //         doc.addImage(img , 'png', 15, 9,50,40)
    //       };
    // }

    // function three(){
    //   four()
    //   myImage.onload = function(){
    //   console.log("1");
    //   doc.addImage(myImage , 'png', 40, 170, 30, 20);
      
    // };
    // }

    // function four(){
    //   myImage1.onload = function(){
    //     console.log("2");
    //     five()
    //     doc.addImage(myImage1 , 'png', 80, 170, 30, 20);
    // };
    // }

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

    // var stamp=new Image();
    //         stamp.src=that.stamp;
    //         stamp.crossOrigin="anonymous";
    //         stamp.onload = function(){
    //         console.log("0");
    //         doc.addImage(stamp , 'png', 15,210,30,30)
    //         };
    // var img = new Image();
    //       img.src = this.org.imageDoc?this.org.imageDoc:'';
    //      img.crossOrigin="anonymous";
    //       // if(this.org.imageDoc){
    //          img.onload = function(){
    //         console.log("-1");
    //         doc.addImage(img , 'png', 15, 9,50,40)
            
    //       };doc.addImage(myImage , 'png', 40, 170, 30, 20);

    function f1() {
    return new Promise((resolve, reject) => {
      that.myImage.onload = function(){
      console.log("1");
    };
    // var isLoaded = this.myImage.complete && this.myImage.naturalHeight !== 0;
    // if(isLoaded)
    resolve('');
    });
}

function f3(){
 that.myImage2.onload = function(){
           console.log("3");
        
      };
}

function f2() {
  return new Promise((resolve, reject) => {
    that.myImage1.onload = function(){
        console.log("2");
        // doc.addImage(myImage1 , 'png', 80, 170, 30, 20);
        // if(that.deviceImage.length==2){
        // doc.save(name);
      // }
    };
  //  var isLoaded = this.myImage1.complete && this.myImage1.naturalHeight !== 0;
  //   if(isLoaded)
    resolve('');
    })
  
}
f1().then(res => f2().then(res1=>f3()));





  }
  getLocationLink(){
     var data = {
          id: this.data.deviceInfo._id,
          imei: this.data.deviceInfo.Device_ID,
          sh: this.data.deviceInfo.user._id,
          ttl: 15*60
          };

          this.contactService.shareLiveLocation(data).subscribe(res=>{
            console.log(res); 
            console.log('shareToken',res);
            this.link = 'http://nipponsecura.in' + "/share/liveShare?t=" + res.t;
            console.log(this.link);
            // this.shareLocationToDevice(link);
            this.qrCodeGenerator()
          },err=>{
            console.log(err);
          })
  }
   qrCodeGenerator() {
  
    var qr = new QRious();
    qr.set({
      // background: 'green',
      backgroundAlpha: 0.8,
      // foreground: 'blue',
      foregroundAlpha: 0.8,
      level: 'L',
      padding: 25,
      size: 500,
      value: this.link
    });
  

    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;
      }
    };
    var stamp=new Image();
            stamp.src=that.stamp;
            stamp.crossOrigin="anonymous";
            // stamp.onload = function(){
            console.log("0");
            doc.addImage(that.stamp1 , 'png', 15,210,30,30)
            // };
    var img = new Image();
          img.src = this.org.imageDoc?this.org.imageDoc:'';
         img.crossOrigin="anonymous";
          // if(this.org.imageDoc){
            //  img.onload = function(){
            console.log("-1");
            doc.addImage(that.img , 'png', 15, 9,50,40)
            
          // };
    // doc.text("Customer Copy", 110, 12);
    doc.setFontSize(3);
    doc.autoTable({
      theme: 'plain',
      html: '#testPdf', 
      
        tableWidth: 'auto',

      // styles :  {
      //   cellWidth : 10,
      //    overflow: "linebreak"
      // },     
      willDrawCell: data => {
        if(data.row.index === 0){ 
          data.row.height = 30;    
          doc.setFontStyle('bold');  
          data.row.cells[0].styles.halign = 'center';
          data.row.cells[0].styles.fontSize = 25;
          data.row.cells[0].styles.overflow= "linebreak"
          data.row.cells[0].styles.lineHeight= "2.5";
          // doc.setLineHeightFactor()
           
          // }

          // doc.addImage(this.supAdmin.imageDoc,'JPEG', 140, 9,40,40);
          
          doc.addImage(this.imgURL,'JPEG',150, 9,50,40);
          
        }  
        if(data.row.index ===1 ){    
        //  data.row.cells[0].styles.halign = 'center';
          doc.halign = 'center';
           doc.setFontStyle('bold');
           doc.cellPadding=60
        }

        if(data.row.index ===3 ){    
        //  data.row.cells[0].styles.halign = 'center';
          doc.halign = 'center';
        
        }
        if( data.row.index ===6){    
        //  data.row.cells[0].styles.halign = 'center';
          doc.halign = 'center';
        
        }

        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 ===5){
          data.row.height = 30;    
          // data.row.cells[0].styles.halign = 'center';
          // doc.halign = 'center';
        }

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

    // 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";

    // var stamp=new Image();
    // stamp.src=that.stamp;
    // stamp.crossOrigin="anonymous";

    //  var img = new Image();
    //  img.src = this.org.imageDoc?this.org.imageDoc:'';
    //  img.crossOrigin="anonymous";
    function f1() {
       return new Promise((resolve, reject) => {
       console.log("1");
      doc.addImage(that.myImage , 'png', 40, 170, 30, 20);
       resolve('');
       })
    }

     function f2() {
       return new Promise((resolve, reject) => {
       console.log("2");
      doc.addImage(that.myImage1 , 'png', 80, 170, 30, 20);
       resolve('');
       })
    }

    function f3(){
//  myImage2.onload = function(){
           console.log("3");
        
        doc.addImage(that.myImage2 , 'png', 120, 170, 30, 20);
          doc.save(name);
        
}
//     function f1() {
//     return new Promise((resolve, reject) => {
//       myImage.onload = function(){
//       console.log("1");
//       doc.addImage(myImage , 'png', 40, 170, 30, 20);
     
      
//     };
//     var isLoaded = myImage.complete && myImage.naturalHeight !== 0;
//     if(isLoaded)
//     resolve('');
//     });
// }

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

// function f2() {
//   return new Promise((resolve, reject) => {
//     myImage1.onload = function(){
//         console.log("2");
//         doc.addImage(myImage1 , 'png', 80, 170, 30, 20);
//         // if(that.deviceImage.length==2){
//         // doc.save(name);
//       // }
//     };
//    var isLoaded = myImage1.complete && myImage1.naturalHeight !== 0;
//     if(isLoaded)
//     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();
    }
}