import { Component, OnInit,Inject } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { DeviceEditComponent } from '../../dashboard/device-edit/device-edit.component';
import { ContactService } from '../../contact.service';
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;
declare var html2canvas:any
@Component({
  selector: 'app-edit-device-master',
  templateUrl: './edit-device-master.component.html',
  styleUrls: ['./edit-device-master.component.scss']
})
export class EditDeviceMasterComponent implements OnInit {
devName:any;
phNum:any;
createdOn:any;
expOn:any;

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;
  ICCICD: 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=[]
  constructor(public dialogRef: MdDialogRef<EditDeviceMasterComponent>,
    @Inject(MD_DIALOG_DATA) public data: any,private contactService: ContactService) { 
      this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id; 
      this.organisationFlag = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isOrganisation  ;     
        this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
        this.isDealer = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
      //  this.deviceImage=this.data.deviceImage
      //   console.log(this.deviceImage);
    }

  ngOnInit() {
    console.log("Init function call");
    var that = this;
    this.getUser();
    this.dealerDetail();
    console.log("DATA",this.data);
    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)
        
      
    }
     console.log(this.deviceImage);
    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.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]:"";
    // console.log(this.CID_No,this.devicetype,this.ICCICD,this.IMSI,this.uniqueID,this.fitmentDate,this.engineNo,this.typeOfVehicle,this.manufacturingCompany);
    // console.log(this.lastFitnessDate,this.vehicleRegDate,this.vehicleManufacturingDate,this.lattitude,this.longitude)
    if(this.data.deviceInfo['actionId']=="exportPdf"){
      this.companyName = this.data.deviceInfo.companyName;
      this.companyAddress = this.data.deviceInfo.companyAddress;
      this.transportOfficeCity = this.data.deviceInfo.transportOfficeCity;
      this.transportOfficeState = this.data.deviceInfo.transportOfficeState;
      this.ChassisNo = this.data.deviceInfo.ChassisNo;
      this.deviceManufacturer = this.data.deviceInfo.device_model?this.data.deviceInfo.device_model.Manufacturer:"";
      this.numberOfSOS = this.data.deviceInfo.numberOfSOS;
      this.editTemplate =false;
      this.deletetemplate = false;
      this.ExportPdf =true;
    }

    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);

      setTimeout(() => {
        $('#dbselect').multipleSelect({
          width: 200,
          placeholder: "Select Dealer",
          filter: true,
          single: true,
          selectAll: false
   
        })
      }, 100);
  
      setTimeout(() => {
        $('#dbselect_1').multipleSelect({
          width: 200,
          placeholder: "Select User",
          filter: true,
          single: true,
          selectAll: false
   
        })
      }, 100);  





  }


  getDevmodel(ev){
    console.log(ev);
  }

  editDetails(){
    console.log(this.initialUser);
    this.dealerSelect = $('#dbselect').multipleSelect('getSelects','value'); 
    this.userSelect =  $('#dbselect_1').multipleSelect('getSelects','value'); 

  //   console.log('this.emailId',this.emailId);
  //   if(this.userSelect.length!=0){
  //      if(this.orignalEmail == this.emailId){
  //        var errormsg =   swal(
  //         'Change Email',
  //         'Please change email before changing user !!!',
  //         'error'
  //       )  
  //        return errormsg;
  //      }
  //  }
    var devObj = {
      'Device_Name' : this.devName,  
      'contact_number' :this.phNum,    
      'created_on' : this.createdOn?(new Date(this.createdOn).toISOString()):"",
      'expiration_date' : this.expOn?(new Date(this.expOn).toISOString()):"",
      // 'iconType' : this.iconType,
      'Email_ID' :this.emailId,
      'sim_number': this.simNum,
      'today_odo':this.todayODO,
      'total_odo' : this.totalODO,
      '_id':this.deviceID,
      'last_device_time':this.lastDeviceTime?(new Date(this.lastDeviceTime).toISOString()):"",  
      'last_ping_on': this.lastPingOn?(new Date( this.lastPingOn).toISOString()):"",  
    }
  
    if(this.userSelect.length!=0){
      devObj['user'] = this.userSelect[0];    
    }
    


    if(this.dealerSelect.length!=0){
       devObj['created_by'] = this.dealerSelect[0];
       devObj['Dealer'] = this.dealerSelect[0];
      //  dealerId
    }
    // else{
    //   devObj['Dealer'] = this.useridd;
    // }
    
    console.log("deviceObject=>",devObj);

    this.contactService.editDevMaster(devObj)
      .subscribe(res=>{
        console.log(res);
        if(res){
          this.dialogRef.close("success");
        }

      },err=>{
        console.log(err);
      })
  
   


  }

  cancelEdit(){
    this.dummyuserData=[];
    this.dialogRef.close();
  }
  dummyuserData=[];
  defaultCustomer:any=''
  getUser() {
    this.contactService.getContactsbyUser(this.useridd)
      .subscribe(res => {  
        this.costumers = res;
        console.log('this.costumers',this.costumers);

        setTimeout(() => {
          $('#dbselect_1').multipleSelect({
            width: 200,
            placeholder: "Select User",
            filter: true,
            single: true,
            selectAll: false
     
          })
        }, 100);  

   
      },err=>{
        console.log(err);
      })
  }


  deleteDetails(){
    console.log("Deleted");

  }

  userSelect=[];
  // filteruserStates(usr) {
  //   console.log("userObj=>",usr);
  //   if (usr) {
 
  //     const filterdealerValue:any = usr;
  //     this.userSelect=[];
  //      this.userSelect = this.dummyuserData.filter(function(p){
  //       var t = p.user_type.toLocaleLowerCase().indexOf(filterdealerValue.toLocaleLowerCase());
  //     //  this.option = this.options[i];
  //       return t > -1;    
  //     });
  //       console.log("selectedUser=>",this.userSelect);
  //       this.emailId = this.userSelect[0].email;
  //       return this.userSelect;
  //   }
  
  // }

  dealers_info=[];

dealerDetail(){ 
  var getDealerPayload = (this.superAdmin===true)?this.useridd:this.isDealer ; 
  this.contactService.dealer_Info_dealer_list_copy(getDealerPayload).subscribe(res=>{
    this.dealers_info = res;
    console.log(this.dealers_info);
    setTimeout(() => {
      $('#dbselect').multipleSelect({
        width: 200, 
        placeholder: "Select Dealer",
        filter: true,
        single: true,
        selectAll: false
 
      })
    }, 100);
  },err=>{
    console.log(err);
  })

}

dealerSelect:any=[];
dealerName:any;
// filterDealerStates(dlr) {
//   console.log(dlr);
//   if (dlr) {
//     const filterdealerValue:any = dlr;
//     this.dealerSelect=[];
//      this.dealerSelect = this.dealers_info.filter(function(p){
//       var t = p.dealer_firstname.toLocaleLowerCase().indexOf(filterdealerValue.toLocaleLowerCase());
//     //  this.option = this.options[i];
//       return t > -1;    
//     });
//       console.log(this.dealerSelect);
//       return this.dealerSelect;
//   }

// }


filterDistStates(dst){
  console.log(dst);
  if (dst) {
    const filterdealerValue:any = dst;
    this.distSelect=[];
     this.distSelect = this.dealers_info.filter(function(p){
      var t = p.dealer_firstname.toLocaleLowerCase().indexOf(filterdealerValue.toLocaleLowerCase());
    //  this.option = this.options[i];
      return t > -1;    
    });
      console.log(this.distSelect);
      return this.distSelect;
  }
}


 

  filterModelStates(devmdl){
    console.log(devmdl)

  }

  exportAsPdf() {
    var that=this
    console.log(this.imgURL);
    var doc = new jsPDF();
    var specialElementHandlers = {
      '#editor': function (element: any, renderer: any) {
        return true;
      }
    };

    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()
      
          
          doc.addImage(this.imgURL,'JPEG', 140, 12,40,40);
          
        }  
        if(data.row.index ===3){    
         
        }

        if((data.row.index ===2) || (data.row.index ===4) || (data.row.index ===6) ||(data.row.index ===8) ||(data.row.index ===10) || (data.row.index ===12)){
          doc.setFontStyle('bold');         
          
        }
        if(data.row.index ===12){
          data.row.height = 25;    
          // 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';
        }
       
   
      }
      
    });
   

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

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

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

    if(that.deviceImage.length==0){
       doc.save('sample-file.pdf');
    }

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

function f3(){
 myImage2.onload = function(){
           console.log("3");
        
        doc.addImage(myImage2 , 'png', 80, 180, 30, 20);
          doc.save('sample-file.pdf');
        
        
      };
}

function f2() {
  return new Promise((resolve, reject) => {
    myImage1.onload = function(){
        console.log("2");
        doc.addImage(myImage1 , 'png', 60, 180, 30, 20);
        if(that.deviceImage.length==2){
        doc.save('sample-file.pdf');
      }
      };
       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();
    }

  ngAfterViewInit(){
    if(this.data.deviceInfo['actionId']=="exportPdf"){
      console.log("after ngOninit");
       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();
    
  
  
  }

  // + "Email " +this.orignalEmail +"IMEI " + this.deviceID + "Device User " + this.userName + "Dealer Name " + this.dealerName; last_device_time,last_ping_on
  

}





// this.companyName 
// this.companyAddress
