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

declare var swal: any, _: any;
import { Observable, Observer } from "rxjs";
import { ContactService } from "../contact.service";
import { DatePipe } from "@angular/common";

@Component({
  selector: 'app-renewal-documents',
  templateUrl: './renewal-documents.component.html',
  styleUrls: ['./renewal-documents.component.scss'],
  providers:[DatePipe]
})
export class RenewalDocumentsComponent 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;
  dbexp:any={};
  renewal_details={
    vehicle_registration_dt:'',
    vts_expiry_dt:'',
    exim_expiry_dt:''
  };
  rc_pic: any='';
  constructor(
    private modalService: BsModalService,
    public dialogRef: MdDialogRef<RenewalDocumentsComponent>,
    public snackBar: MdSnackBar,
    private contactService: ContactService,
    private _flashMessagesService: FlashMessagesService,
    private datePipe:DatePipe,
    @Inject(MD_DIALOG_DATA) public data: any
  ) {
    console.log(data);
   this.dbexp=data.dealer_payload
  this.renewal_details.vehicle_registration_dt = data.dealer_payload.renew_details.vehicle_registration_dt ? this.datePipe.transform(data.dealer_payload.renew_details.vehicle_registration_dt, 'yyyy-MM-dd') : '';
  this.renewal_details.vts_expiry_dt = data.dealer_payload.esim_validity ? this.datePipe.transform(data.dealer_payload.esim_validity, 'yyyy-MM-dd') : '';
  this.renewal_details.exim_expiry_dt = data.dealer_payload.expiration_date ? this.datePipe.transform(data.dealer_payload.expiration_date, 'yyyy-MM-dd') : '';

  this.rc_pic=data.dealer_payload.renew_details.rc_copy_certificate? data.dealer_payload.renew_details.rc_copy_certificate : '';
    if (
      data.dealer_payload.kycStatus == "Approved" ||
      data.dealer_payload.kycStatus == "Reject"
    ) {
      this.disabled = true;
    }
    this.imageDoc = data.dealer_payload.imageDoc;

    this.imageDoc.push({
      doctype: "Device Photo",
      req: true,
      image: data.dealer_payload.deviceImage[0],
      phone: "",
      docdate: "",
      fill: true,
      isText: true,
      doctype_type: "Device Photo",
    });
  }
  ngOnInit() {
    this.bsConfig = Object.assign({}, { containerClass: "theme-dark-blue" });
  }
  hasPdfFile(url) {
    return url && url.indexOf(".pdf") != -1;
  }
  db_upload(ev, flag) {
    console.log(ev.target);
  }
closeModal(){
  this.dialogRef.close();
}
  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: any = {};
  statePic;
  vahanPic;
  renewPic;
  onFileChanged(event1, type) {
    debugger
    this.selectedFile[type] = <File>event1.target.files[0];

    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 if(type == 'vahan') {
      let reader = new FileReader();
      reader.onload = (event: any) => {
        this.vahanPic = event.target.result;
        reader.readAsDataURL(fileToUpload);
      };
    }
    else{
      let reader = new FileReader();
      reader.onload = (event: any) => {
        this.renewPic = 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();
    if (!(this.selectedFile[imgIndex] && this.selectedFile[imgIndex].name)) {
      swal(
        "Upload Error",
        "Please select document type before upload !!!",
        "error"
      );
    } else {
      fd.append(
        "photo",
        this.selectedFile[imgIndex],
        this.selectedFile[imgIndex].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 if(imgIndex == "state") {
            this.statePic = resImage;
          }
          else{
            this.renewPic = 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;
  renew_certificate_date;
  submit() {
    if (this.vahanPic && this.statePic && this.renewPic) {
      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,
        renewal_certificate:this.renewPic,
        vaahan_certifcate_date: new Date(),
        state_certifcate_date: new Date(),
        renewal_certifcate_date: new Date(),
        dealerdocumentupload: true,
      };

      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: any = [];
  value: any = [];
  titleForDoc;

  zoom(e: any): void {
    const zoomer = e.currentTarget as HTMLElement;
    let offsetX: number;
    let offsetY: number;

    if ("offsetX" in e) {
      offsetX = e.offsetX;
      offsetY = e.offsetY;
    } else {
      offsetX = e.touches[0].pageX;
      offsetY = e.touches[0].pageY;
    }

    const x = (offsetX / zoomer.offsetWidth) * 100;
    const y = (offsetY / zoomer.offsetHeight) * 100;
    zoomer.style.backgroundImage = `url('${zoomer.dataset.imgurl}')`;
    zoomer.style.backgroundPosition = `${x}% ${y}%`;
  }




  openModal(template: TemplateRef<any>, doc,allData) {
    debugger;
    
    this.titleForDoc    = doc.doctype;
    this.modalRef = this.modalService.show(template, {
      backdrop: "static",
      class: "modal-dialog-centered",
    });
    let fname =
    allData.dealer_payload.user && allData.dealer_payload.user.first_name
      ? allData.dealer_payload.user.first_name
      : "";
  let lName =
    allData.dealer_payload.user && allData.dealer_payload.user.last_name
      ? allData.dealer_payload.user.last_name
      : "";
   let db_name =   fname + " " + lName;

   //Individual == 'Customer ' | Firm == 'Custodian '
    if (doc.doctype == "ID proof") {
      let cname = allData.dealer_payload.customerType == "Individual" ? "Customer" : allData.dealer_payload.customerType == "Firm" ?"Custodian" :""
      this.key = [ cname+ " Name","ID proof No."];
      this.value = [db_name,doc.phone];
    } else  if (doc.doctype == "Address Proof") {
      this.key = [
        "Customer Name",
        "Address Proof No.",
        "Customer Address Complete",
        "State",
        "City",
        "Pin Code"
      ];
      this.value = [db_name,
        doc.phone,
        this.data.dealer_payload.user.address || '',
        this.data.dealer_payload.user.state || '',
        this.data.dealer_payload.user.city || '',
        this.data.dealer_payload.user.pin || '',
      ];
    } 
     else  if (doc.doctype == "Warrenty Card") {
      this.key = [
        "IMEI No.",
        "Customer Name",
        "Customer Address",
        "Customer Number",
        "Dealership Name (KYC owner Name)",
        "Chassis No."
      ];
      this.value = [this.data.dealer_payload.Device_ID || '',
        db_name,
        (this.data.dealer_payload.user.address || ''),
        this.data.dealer_payload.user.phone || '',
        this.data.dealer_payload.Dealer.first_name || '',
        this.data.dealer_payload.ChassisNo || '',];
    } 
     else  if (doc.doctype =="vehicle Photo") {
      this.key = [
        "Vehicle Manufactrer",
        "Vehicle Model",
    
      ];
      this.value =[
        this.data.dealer_payload.manufacturingCompany || '',
        this.data.dealer_payload.Model || ''
      ];
    } 
     else  if (doc.doctype =="Vehicle Ownership Proof") {
      this.key = [
        "Customer Name",
        "Chassis No",
        "Engine No.",
        "Vehicle Manufacturer",
        "Vehicle Model"
      ];
      this.value = [
        db_name,
        this.data.dealer_payload.ChassisNo || '',
        this.data.dealer_payload.engineNo || '',
       this.data.dealer_payload.manufacturingCompany || '',
        this.data.dealer_payload.Model || ''
      ];
    } 
     else  if (doc.doctype =="vehicle RC") {
      this.key = [
        "Customer Name",
        "Vehicle no.",
        "Chassis no.",
        "Manufacturing Year"
      ];
      this.value =  [
        db_name,
        "Vehicle no.",
        this.data.dealer_payload.ChassisNo || '',
        this.data.dealer_payload.manufacturingYear || ''
      ];
    } 
     else  if (doc.doctype =="Device Photo") {
      this.key = [
        "IMEI NO.",
        "ICCID No."
      ];
      this.value =  [
        this.data.dealer_payload.Device_ID || '',
        this.data.dealer_payload.IccidNo || ''
      ];

    } 
    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(),
          };
          if (
            this.data.dealer_payload.phone != undefined &&
            this.data.dealer_payload.phone != ""
          ) {
            request["dphone"] = this.data.dealer_payload.phone;
          }
          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(),
      };
      if (
        this.data.dealer_payload.phone != undefined &&
        this.data.dealer_payload.phone != ""
      ) {
        request["dphone"] = this.data.dealer_payload.phone;
      }
      this.contactService.editdevice(request).subscribe((res) => {
        swal({
          title: "KYC approved successfully",
        });
        this.dialogRef.close("yes");
      });
    }
  }

  base64Image;
  downloadImage(imageUrl, name) {
    if (!this.hasPdfFile(imageUrl)) {
      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();
      });
    } else {
      var link = document.createElement("a");

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

      link.setAttribute("href", imageUrl);
      link.setAttribute("download", name);

      link.setAttribute("target", "_blank");
      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,/, "");
  }

}
