import { isPlatformBrowser } from '@angular/common';
import { Component, Inject, OnInit, PLATFORM_ID } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Meta, Title } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth'
import 'firebase/compat/firestore'
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { Cities } from '../../entities/cities';
import { Leads } from '../../entities/leads';
import { CommonService } from '../../shared/services/common/common.service';
import { GlobalService } from '../../shared/services/common/global.service';
import { LinkService } from '../../shared/services/link.service';
import { LeadService } from '../../shared/services/loanService/lead.service';
import { environment } from '../../../../environments/environment';
declare let $: any;
import Swal from 'sweetalert2';
import { DocumentMasters } from '../../entities/documentMasters';

@Component({
  selector: 'app-business-loan',
  templateUrl: './business-loan.component.html',
  styleUrls: ['./business-loan.component.scss']
})
export class BusinessLoanComponent implements OnInit {
  // public isVerifyOtp: boolean = true;
  // // public isShow: boolean = true;
  // public isDetailForm: boolean = false;
  // public isPersonalDetailForm: boolean = false;
  // public mobileNumber: number = 0;
  // public isOtpInput: boolean = false;
  // public mobileNo: number = 0;
  // public amount: number = 0;
  // public interest_rate: number
  // public payment: string = "0.00";
  // public months: number = 0;
  // public interest: string = "0.00";
  // public amountPayable: string = "0.00";
  // public displayAmount: string = "0.00";
  // public test: any;
  // public contactForm: FormGroup;
  // public basicDetailForm: FormGroup;
  // public detailForms: FormGroup;
  // public reCaptchaVerifier: any;
  // public otp: any;
  // public verify: any;
  // public isAgreed: boolean = false;
  // public agreedmsg: string = '';
  // public selectedTab: string = "Overview"
  // public faqs = [
  //   {
  //     que: "What are the different types of business loans for startups that I can avail?",
  //     ans: "There are two kinds of business loans offered by lenders for you to select from term loans and capital loans.These loans can be utilized to expand your companies, for  purchasing equipment or launching new projects.They can be borrowed over a time period of one year to 10 years.The working capital loan, however other on the other hand, are short- term loans that need to be paid back within one year.They are employed to settle rent and salaries of employees and stock up inventory, and more.",
  //     isCollapsed: false
  //   },
  //   {
  //     que: " What is the highest amount I can get as a start-up business loan?",
  //     ans: "Amount of loans that you can avail is contingent on the lender as well as other factors like the annual turnover of the business and your credit score, etc. For instance with the Mudra Loan that can be availed as much as Rs.10 lakh could be accessed in a business startup loan.",
  //     isCollapsed: true
  //   },
  //   {
  //     que: "Does a business plan have to be completed to get a startup loan?",
  //     ans: "Yes. A majority of lenders will require you for a business proposal when you apply for a start- up business loan.Be sure your business plan is concise and precise with the company's goals and goals clearly stated. The business plan must also specify how the loan is to be utilized.",
  //     isCollapsed: true
  //   },
  //   {
  //     que: "Does a business plan have to be completed to get a startup loan?",
  //     ans: "Yes. A majority of lenders will require you for a business proposal when you apply for a start- up business loan.Be sure your business plan is concise and precise with the company's goals and goals clearly stated. The business plan must also specify how the loan is to be utilized.",
  //     isCollapsed: true
  //   },
  //   {
  //     que: "Which banks can provide business loans for new businesses in India?",
  //     ans: "A number of lenders in India offer business startup loans and some of them are such as HDFC Bank, Kotak Mahindra, TATA Capital, etc.",
  //     isCollapsed: true
  //   },
  //   {
  //     que: "Do you have a government-issued loan to help start-up businesses?",
  //     ans: "Sure, you can get federal loans that you could avail for your start-up business. The types of government loans that you can get include: <p class='mb-0'><i class='fa fa-list'></i> Mudra Loan Scheme</p><p class='mb-0' > <i class='fa fa-list' > </i> MSME Business Loans in 59 Minutes</p > <p class='mb-0' > <i class='fa fa-list' > </i> CGS is the Credit Guarantee Scheme (CGS)</p > <p class='mb-0' > <i class='fa fa-list' > </i> Stand Up India Scheme</p >  <p class='mb-0' > <i class='fa fa-list' > </i> Coir Udyami Yojana</p ><p class='mb-0' > <i class='fa fa-list' > </i> National Bank for Agriculture and Rural Development(NABARD) </p> <p class='mb-0'> <i class='fa fa-list'> </i> Credit Link Capital Subsidy Scheme</p > <p class='mb-0' > <i class='fa fa-list' > </i> National Small Industries Corporation Subsidy</p >",
  //     isCollapsed: true
  //   },
  //   {
  //     que: "How can I increase my chances of obtaining a business credit?",
  //     ans: "A few of the points to keep in mind when making a request for a business loan are: <p class='mb-0'><i class='fa fa-list'></i> You must increase the credit rating of your</p><p class='mb-0' > <i class='fa fa-list' > </i> Choose carefully the lender you would like to obtain the loan for your business.</p > <p class='mb-0' > <i class='fa fa-list' > </i> Do not apply for more than one loans. If you have loans in the past ensure that you pay the EMIs prior to applying for an unsecured business loan.</p > <p class='mb-0' > <i class='fa fa-list' > </i> You can apply for a loan that you know you can pay back in time.</p >  <p class='mb-0' > <i class='fa fa-list' > </i> Keep an audited log of the financial statement you have filed. </p ><p class='mb-0' > <i class='fa fa-list' > </i> Check your credit score regularly</p>",
  //     isCollapsed: true
  //   },
  //   //  {
  //   //   que: "How can I increase my chances of obtaining a business credit?",
  //   //   ans: "There are two kinds of business loans offered by lenders for you to select from term loans and capital loans.These loans can be utilized to expand your companies, for  purchasing equipment or launching new projects.They can be borrowed over a time period of one year to 10 years.The working capital loan, however other on the other hand, are short- term loans that need to be paid back within one year.They are employed to settle rent and salaries of employees and stock up inventory, and more.",
  //   //   isCollapsed: false
  //   // }
  // ]
  // // public cities: any = [
  // //   {
  // //     name: "Bardoli"
  // //   },
  // //   {
  // //     name: "Surat"
  // //   },
  // //   {
  // //     name: "Kamrej"
  // //   },
  // //   {
  // //     name: "Ahmedabad"
  // //   }

  // // ];
  // public cities: Cities[] = new Array<Cities>();
  // public selectedCity: any :any = [] :any = [];
  // public serviceId: number = 0;
  // public leads = new Leads();
  // public step: number = 0;
  // public isCollapsed: boolean = true
  // public city: string = "";
  // public _title: string = '';

  public leads = new Leads();
  public basicDetailForm: FormGroup;
  public selectedCity: any;
  public cities: Cities[] = [];
  public serviceId: number = 0;
  public city: string = "";
  public _title: string = '';
  public payment: string = "0.00";
  public interest: string = "0.00";
  public amountPayable: string = "0.00";
  public displayAmount: string = "0.00";
  public test: any
  public emiCalculatorForm: FormGroup;
  public documentMasters: DocumentMasters[] = new Array<DocumentMasters>();
  public customFieldForm!: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    private commonService: CommonService,
    private toastrService: ToastrService,
    private leadService: LeadService,
    private globalService: GlobalService,
    private meta: Meta,
    private route: ActivatedRoute,
    private title: Title,
    @Inject(PLATFORM_ID) public platformId: object,
    private spinnerService: NgxSpinnerService,
    private linkService: LinkService
  ) {
    this.linkService.createLinkForCanonicalURL();
    let sub = this.route.params.subscribe(async (params) => {
      this.city = params['city'] ? params['city'] : '';
      if (this.city) {
        if (isPlatformBrowser(this.platformId))
          sessionStorage.setItem("selectedCity", this.city);
      }
    });
    // let cityList;
    // if (isPlatformBrowser(this.platformId)) {
    //   cityList = sessionStorage.getItem("cityList");
    // }
    // let isCityAvailable = false;
    // if (cityList) {
    //   let cityArray = JSON.parse(cityList) as string[];
    //   isCityAvailable = cityArray.findIndex(c => c == this.city.toLowerCase()) > -1;
    // }

    //if (isCityAvailable) {
    this._title = `Personalized business Loan solutions for self employed professionals in ` + this.city;
    this.route.snapshot.data['title'] = this._title;
    this.title.setTitle(this.route.snapshot.data['title']);
    // this.meta.updateTag({
    //   name: 'title', content: `Personalized business Loan solutions for self employed professionals in `+this.city
    // });
    this.meta.updateTag({
      name: 'description', content: 'Avail loan for small business at attractive interest rates, and expand your business in ' + this.city + ' or apply startup business loans with easy documentation.'
    });
    this.meta.updateTag({
      name: 'author', content: `CreditWeb`
    });
    this.meta.updateTag({
      name: 'og:locale', property: "og:locale", content: `en_US`
    });
    this.meta.updateTag({
      name: 'og:title', property: "og:title", content: `Personalized business Loan solutions for self employed professionals in ` + this.city
    });
    this.meta.updateTag({
      name: 'og:description', property: "og:description", content: 'Avail loan for small business at attractive interest rates, and expand your business in ' + this.city + ' or apply startup business loans with easy documentation.'
    });
    this.meta.updateTag({
      name: 'og:url', property: "og:url", content: `https://credit.nsserver.in`
    });
    this.meta.updateTag({
      name: 'og:site_name', property: "og:site_name", content: `CreditWeb`
    });
    this.meta.updateTag({
      name: 'og:type', property: "og:type", content: `Website`
    });
    this.meta.updateTag({
      name: 'og:image', property: "og:image", content: `https://credit.nsserver.in/assets/img/logo/logo.webp`
    });
    this.meta.updateTag({
      'http-equiv': "X-UA-Compatible", content: "IE=edge"
    });
    this.meta.updateTag({
      name: 'copyright', content: `Copyright 2022, CreditWeb`
    });
    this.meta.updateTag({
      name: 'robots', content: `index, follow`
    });
    this.meta.updateTag({
      name: 'Googlebot', content: `Index, Follow`
    });
    this.meta.updateTag({
      name: 'rating', content: `Safe For Kids`
    });
    this.meta.updateTag({
      name: 'tweeter:card', content: `compare & apply for business loan`
    });
    this.meta.updateTag({
      name: 'tweeter:title', content: `compare & apply for business loan`
    });
    this.meta.updateTag({
      name: 'tweeter:description', content: 'Avail loan for small business at attractive interest rates, and expand your business in ' + this.city + ' or apply startup business loans with easy documentation.'
    });
    this.meta.updateTag({
      name: 'tweeter:site', content: `CreditWeb`
    });
    this.meta.updateTag({
      name: 'tweeter:image', content: `https://credit.nsserver.in/assets/img/logo/logo.webp`
    });

    this.basicDetailForm = formBuilder.group({
      'contactNo': [null, [Validators.minLength(10)]],
      'loanAmount': [null, [Validators.required]],
      'customerFullName': [null, [Validators.required]],
      'pincode': [null, [Validators.required, Validators.minLength(6)]],
      'cityName': [null, [Validators.required]],
      'annualIncome': [null, [Validators.required]],
      // 'panCardNo': [null, [Validators.required, Validators.pattern('[A-Z]{5}[0-9]{4}[A-Z]{1}')]],
      //'email': [null, [Validators.required, Validators.pattern("[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$")]],
    })
    this.emiCalculatorForm = formBuilder.group({
      'amount': [null, [Validators.required]],
      'interest_rate': [null, [Validators.required]],
      'months': [null, [Validators.required]],
    })
    // this.contactForm = formBuilder.group({
    //   'contactNo': [null, [Validators.required, Validators.minLength(10)]],
    // });
    // this.detailForms = formBuilder.group({

    //   'annualIncome': [null, [Validators.required]],
    //   'aadhaarCardNo': [null, [Validators.required, Validators.pattern('^[2-9]{1}[0-9]{3}[0-9]{4}[0-9]{4}$')]],
    //   'panCardNo': [null, [Validators.required, Validators.pattern('[A-Z]{5}[0-9]{4}[A-Z]{1}')]],
    // })
  }

  async ngOnInit() {
    //firebase.initializeApp(environment.firebase)
    // setTimeout(() => {
    //   this.isShow = false;
    // }, 1000);

    // this.cities = await this.commonService.getCitites();
    this.serviceId = this.commonService.getServiceId("Business Loan");
    await this.getDocumentMaster();
    if (this.documentMasters && this.documentMasters.length > 0) {
      this.customFieldForm = this.formBuilder.group({})
      for (let index = 0; index < this.documentMasters.length; index++) {
        if (this.documentMasters[index].allowDocumentField) {
          this.customFieldForm.addControl(this.documentMasters[index].documentFieldName, this.formBuilder.control(''));
        }
      }
    }
    //this.selectedCity = [...this.cities];
    //this.setStep(0, 'initital');
  }

  public async getDocumentMaster() {
    try {
      let res = await this.globalService.getDocumentMaster();
      if (res && res.status == 200) {
        this.documentMasters = res.recordList;
      }
    } catch (error: any) {
      this.toastrService.error(error)
    }
  }
  // public verifyOtp() {
  //   this.isOtpInput = true;
  //   this.basicDetailForm.controls['contactNo'].setValue(this.contactForm.value.contactNo);
  // }

  // public async detailForm(isNext?: boolean) {
  //   if (isNext) {
  //     this.isDetailForm = true;
  //     this.isPersonalDetailForm = false;
  //     try {
  //       if (this.leads.id) {
  //         //this.isShow = true;
  //         let id = this.leads.id
  //         this.leads = this.basicDetailForm.value;
  //         this.leads.serviceId = this.serviceId;
  //         this.leads.cityId = this.basicDetailForm.value.cityName.id;
  //         this.leads.id = id;
  //         this.leads.countryCode = "+91";
  //         let res = await this.leadService.updateLeads(this.leads);
  //         if (res && res.status == 200) {
  //         }
  //       }
  //       else {
  //         this.leads = this.basicDetailForm.value;
  //         this.leads.serviceId = this.serviceId;
  //         this.leads.cityId = this.basicDetailForm.value.cityName.id;
  //         this.leads.countryCode = "+91";
  //         let res = await this.leadService.insertLeads(this.leads);
  //         if (res && res.status == 200) {
  //           if (res.recordList && res.recordList.length > 0) {
  //             this.leads.id = res.recordList[0].id
  //           }
  //         }
  //       }
  //       //this.isShow = false;
  //       this.isDetailForm = true;
  //       this.isPersonalDetailForm = false;
  //     } catch (error: any) {
  //       //this.isShow = false;
  //       let err = error;
  //       if (error && error.error && error.error.message) {
  //         err = error.error.message
  //       }
  //       this.toastrService.error(err, "Error");
  //     }
  //   }
  //   else if (isNext == false) {
  //     this.isDetailForm = false;
  //     this.isPersonalDetailForm = true;
  //   }
  //   else {
  //     if (this.isAgreed) {
  //       if (this.leads.id) {
  //         try {
  //           //this.isShow = true
  //           let id = this.leads.id
  //           this.leads = this.basicDetailForm.value;
  //           this.leads.annualIncome = this.detailForms.value.annualIncome
  //           this.leads.aadhaarCardNo = this.detailForms.value.aadhaarCardNo
  //           this.leads.panCardNo = this.detailForms.value.panCardNo
  //           this.leads.serviceId = this.serviceId;
  //           this.leads.cityId = this.basicDetailForm.value.cityName.id;
  //           this.leads.id = id;
  //           this.leads.countryCode = "+91";
  //           let res = await this.leadService.updateLeads(this.leads);
  //           if (res && res.status == 200) {
  //             this.sucessReponse();
  //           }
  //           //this.isShow = false;
  //         } catch (error: any) {
  //           //this.isShow = false;
  //           let err = error;
  //           if (error && error.error && error.error.message) {
  //             err = error.error.message
  //           }
  //           this.toastrService.error(err, "Error");
  //         }
  //       }
  //     }
  //     else {
  //       this.agreedmsg = "Please agree to our terms & Condition";
  //     }
  //   }
  // }
  // public calculateLoan() {
  //   if (this.amount && this.interest_rate && this.months) {
  //     let rate = this.interest_rate / (12 * 100);
  //     let rate1 = (Math.pow(1 + rate, this.months))
  //     let payment = this.amount * rate * (rate1 / (rate1 - 1));
  //     this.payment = payment.toFixed(2);
  //     this.amountPayable = (parseFloat(this.payment) * this.months).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  //     this.interest = (parseFloat(this.payment) * this.months - this.amount).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  //     this.displayAmount = this.amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  //   }
  // }

  // //#region getOtp
  // public getOtp() {
  //   // this.isVerifyOtp = false;
  //   // this.isPersonalDetailForm = true;
  //   // this.basicDetailForm.controls['contactNo'].setValue(this.contactForm.value.contactNo);
  //   this.isOtpInput = true;
  //   this.spinnerService.show();
  //   // this.verify = JSON.parse(JSON.stringify(confirmationResult.verificationId));
  //   this.reCaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', { size: 'invisible' })
  //   firebase.auth().signInWithPhoneNumber('+91' + this.contactForm.value.contactNo, this.reCaptchaVerifier).then((confirmationResult) => {
  //     if (confirmationResult && confirmationResult.verificationId) {
  //       this.verify = JSON.parse(JSON.stringify(confirmationResult.verificationId));
  //       this.isOtpInput = true;
  //       this.spinnerService.hide();
  //     }
  //   }).catch((error) => {
  //     this.spinnerService.hide();
  //     setTimeout(() => {
  //       window.location.reload();
  //     }, 5000);
  //   });
  // }

  // public onOtpChange(otpCode: any) {
  //   this.otp = otpCode;
  // }

  // public handleClick() {
  //   // this.getLeadsByContactNo();
  //   // this.isVerifyOtp = false;
  //   // this.isPersonalDetailForm = true;
  //   // this.basicDetailForm.controls['contactNo'].setValue(this.contactForm.value.contactNo);
  //   this.spinnerService.show();
  //   var credential = firebase.auth.PhoneAuthProvider.credential(this.verify, this.otp);
  //   firebase.auth().signInWithCredential(credential)
  //     .then((response) => {
  //       this.isVerifyOtp = false;
  //       this.spinnerService.hide();
  //       this.basicDetailForm.controls['contactNo'].setValue(this.contactForm.value.contactNo);
  //       //this.isShow = true;
  //       this.getLeadsByContactNo();
  //       //this.isShow = false;
  //       this.isPersonalDetailForm = true;
  //     }).catch((error) => {
  //       this.spinnerService.hide();
  //       this.commonService.showWarning();
  //     });
  // }
  // //#endregion

  // public onKey(value) {
  //   this.selectedCity = this.search(value);
  // }

  // public search(value: string) {
  //   let filter = this.cities.filter(item =>
  //     item.name.toLowerCase().includes(value.toLowerCase())
  //   );
  //   return [...filter];
  // }

  // public async getLeadsByContactNo() {
  //   try {
  //     //this.isShow = true;
  //     let res = await this.globalService.getLeadsByContactNo(this.contactForm.value.contactNo, this.serviceId);
  //     if (res && res.status == 200) {
  //       if (res.recordList && res.recordList.length > 0) {
  //         this.leads = res.recordList[0];
  //         if (res.recordList[0].pincode) {
  //           let data = await this.getCityByPincode(res.recordList[0].pincode);
  //         }
  //         this.basicDetailForm.setValue(
  //           {
  //             "contactNo": this.leads.contactNo ? this.leads.contactNo : '',
  //             "loanAmount": this.leads.loanAmount ? this.leads.loanAmount : null,
  //             "customerFullName": this.leads.customerFullName ? this.leads.customerFullName : null,
  //             "pincode": this.leads.pincode ? this.leads.pincode : null,
  //             "cityName": this.cities.find((c:any) => c.id == this.leads.cityId),
  //             "email": this.leads.email ? this.leads.email : null
  //           }
  //         )
  //         this.detailForms.setValue(
  //           {
  //             "aadhaarCardNo": this.leads.aadhaarCardNo ? this.leads.aadhaarCardNo : null,
  //             "panCardNo": this.leads.panCardNo ? this.leads.panCardNo : null,
  //             "annualIncome": this.leads.annualIncome ? this.leads.annualIncome : null
  //           }
  //         )
  //       }
  //     }
  //     //this.isShow = false;
  //   } catch (error: any) {
  //     //this.isShow = false;
  //     let err = error;
  //     if (error && error.error && error.error.message) {
  //       err = error.error.message
  //     }
  //     this.toastrService.error(err, "Error");
  //   }
  // }
  // public setStep(n: any, initial?: string) {
  //   if (initial) {
  //     this.faqs[0].isCollapsed = false;
  //   }
  //   else {
  //     if (this.faqs[n].isCollapsed == false) {
  //       this.faqs[n].isCollapsed = true;
  //     }
  //     else {
  //       for (let index = 0; index < this.faqs.length; index++) {
  //         if (this.faqs[index].isCollapsed == false) {
  //           this.faqs[index].isCollapsed = true;
  //         }
  //       }
  //       this.faqs[n].isCollapsed = false;
  //     }
  //   }
  // }

  public async detailForm() {
    if (this.basicDetailForm.valid) {
      try {
        this.spinnerService.show();
        this.leads = this.basicDetailForm.value;
        this.leads.serviceId = this.serviceId;
        this.leads.cityId = this.basicDetailForm.value.cityName.id;
        this.leads.countryCode = "+91";

        // this.leads.employmentTypeId = this.basicDetailForm.value.employmentTypeId.id;
        // if (this.basicDetailForm.value.employmentTypeId == "Self Employee") {
        //   this.leads.employmentTypeId = 2;
        //   this.leads.annualIncome = this.basicDetailForm.value.income
        // }
        // else if (this.basicDetailForm.value.employmentTypeId == "Salaried") {
        //   this.leads.monthlyIncome = this.basicDetailForm.value.income
        //   this.leads.employmentTypeId = 1;
        // }
        if (this.documentMasters && this.documentMasters.length > 0) {
          for (let index = 0; index < this.documentMasters.length; index++) {
            if (this.documentMasters[index].allowDocumentField)
              this.documentMasters[index].documentData = this.customFieldForm.get(this.documentMasters[index].documentFieldName)?.value
          }
          this.leads.customfields = this.documentMasters
        }
        let res = await this.leadService.insertLeads(this.leads);
        if (res && res.status == 200) {
          this.sucessReponse();
        }

        this.spinnerService.hide();
      } catch (error: any) {
        this.spinnerService.hide();
        let err = error;
        if (error && error.error && error.error.message) {
          err = error.error.message
        }
        this.toastrService.error(err, "Error");
      }
    }
    else {
      Object.keys(this.basicDetailForm.controls).forEach(key => {
        this.basicDetailForm.controls[key].markAsTouched();
      });
    }
  }

  public sucessReponse() {
    //this.commonService.showSuccess();
    Swal.fire({
      icon: 'success',
      text: 'Your Business loan inquiry is submitted successfully.',
      confirmButtonColor: '#0162e8'
    })
    // this.isDetailForm = false;
    // this.isVerifyOtp = true;
    // this.isOtpInput = false;
    this.leads = new Leads();
    this.basicDetailForm.reset();
    this.customFieldForm.reset();
  }

  public applyNow() {
    window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    })
  }

  public async getCityByPincode(event: KeyboardEvent) {
    this.cities = [];
    const value = (event.target as HTMLInputElement)!.value;
    if (value && value.length == 6) {
      try {
        let res = await this.globalService.getCityByPincode(value);
        if (res && res.recordList.length > 0) {
          this.cities = res.recordList;
          this.selectedCity = [...this.cities]
          if (this.selectedCity && this.selectedCity.length > 0)
            this.basicDetailForm.get('cityName')?.setValue(this.selectedCity[0])
        }
      } catch (error: any) {
        let err = '';
        if (error && error.error.message) {
          err = error.error.message
        }
        else if (error && error.message) {
          err = error.message
        }
        this.toastrService.error(error);
      }

    }
  }

  public calculateLoan() {

    if (this.emiCalculatorForm.value.amount && this.emiCalculatorForm.value.interest_rate && this.emiCalculatorForm.value.months) {
      let rate = this.emiCalculatorForm.value.interest_rate / (12 * 100);
      let rate1 = (Math.pow(1 + rate, this.emiCalculatorForm.value.months))
      let payment = this.emiCalculatorForm.value.amount * rate * (rate1 / (rate1 - 1));
      this.payment = payment.toFixed(2);
      this.amountPayable = (parseFloat(this.payment) * this.emiCalculatorForm.value.months).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      this.interest = (parseFloat(this.payment) * this.emiCalculatorForm.value.months - this.emiCalculatorForm.value.amount).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      this.displayAmount = this.emiCalculatorForm.value.amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

    }
  }

  public keyPressAlphanumeric(event: KeyboardEvent) {
    let inp = String.fromCharCode(event.keyCode);
    if (/[a-zA-Z0-9 ]/.test(inp)) {
      // only alphabet a-z A-Z
      return true;
    } else {
      event.preventDefault();
      return false;
    }
  }
}