import { DatePipe } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatTabGroup } from '@angular/material/tabs';
import { ActivatedRoute, Router } from '@angular/router';
import * as QRCode from 'qrcode';
import { PaymentInfoDto } from 'src/app/_dto/payment-info.dto';
import { apiUrl } from 'src/app/_providers/_resources/api-url.properties';
import { ErrorTranslateService } from 'src/app/_providers/_services/error-translate.service';
import { MasterService } from 'src/app/_providers/_services/master.service';
import { UiService } from 'src/app/_providers/_services/ui.service';
import { environment } from 'src/environments/environment.prod';

@Component({
  selector: 'app-qr-payment',
  templateUrl: './qr-payment.component.html',
  styleUrls: ['./qr-payment.component.scss']
})
export class QrPaymentComponent implements OnInit {

  secuLevel: string;

  userId: string;

  tenderId: number;

  transactionData: PaymentInfoDto;

  amountReq: any;

  dialogRef: any;

  paymentStatus: any;

  paymentId: any;

  @ViewChild(MatTabGroup) tabGroup: MatTabGroup;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private _ui: UiService,
    private _errorTranslate: ErrorTranslateService,
    private _masterService: MasterService,
    private dialog: MatDialog,
    private datePipe: DatePipe
  ) {
    this.secuLevel = localStorage.getItem('seculevel');
    this.userId = localStorage.getItem('userId');
    this.tenderId = +this.route.snapshot.paramMap.get('id');
  }

  qrImage: boolean = false;

  transId: any

  ngOnInit(): void {

    this.transactionData = new PaymentInfoDto()

    this.getData();
  }


  // ngAfterViewInit(): void {

  //   setTimeout(() => {
  //   }, 1000);
  // }

  getData() {
    this._masterService.getMasterDatabyId(apiUrl.getTender, this.tenderId).then(res => {
      this.amountReq = res.tenderFee;
      this.generateUPIQRCode(environment.upiId, this.amountReq);

    })
    this.paymentCheck();

  }

  paymentCheck() {
    this._masterService.getMasterDatabyId(apiUrl.paymentUserCheck + `/${this.userId}`, this.tenderId).then(res => {
     
      if (res && res[0].status) {
        if (res[0].status == 'P') {
          this.paymentStatus = 'Pending'
        }
        if (res[0].status == 'D') {
          this.paymentStatus = 'Declined'
        }
        if (res[0].status == 'S') {
          this.paymentStatus = 'Success'
        }
        this.paymentId = res[0].id
      }

    }, err => {
      if (err.error.message.trim() == "User Payment Not Found") {
        this.paymentStatus = 'Payment Not Started'
        this.transactionData.status = 'P'
      }
    })
  }
  generateUPIQRCode(upiID: string, amount: string): void {
    const upiLink = `upi://pay?pa=${upiID}&am=${amount}&tn=Tender%20Fee`;

    QRCode.toDataURL(upiLink, { errorCorrectionLevel: 'L' }, (err, qrDataURL) => {
      if (err) {
        console.error(err);
        return;
      }
    

      const qrImageElement = document.getElementById('qrImage') as HTMLImageElement;
      qrImageElement.src = qrDataURL;
      this.qrImage = true

    });
  }

  openHelpDialog(templateRef) {
    this.dialogRef = this.dialog.open(templateRef, {
      width: '700px',
      disableClose: false
    });
  }

  closeDialog() {
    this.dialogRef.close()
  }

  nextTab() { 
    const selectedIndex = this.tabGroup.selectedIndex;
    const tabCount = this.tabGroup._tabs.length;

    if (selectedIndex < tabCount - 1) {
      this.tabGroup.selectedIndex = selectedIndex + 1;
    }
  }
  prevTab() { 
    
    const selectedIndex = this.tabGroup.selectedIndex;

    if (selectedIndex > 0) {
      this.tabGroup.selectedIndex = selectedIndex - 1;
    }
  }

  preSave() {

    if (this.transactionData.transId == 0 || this.transactionData.transId == null || this.transactionData.transId == undefined) {
      this._ui.toastMessage(this._errorTranslate.translate("pleaseEnterTransId"), 2000, true);
      return false;
    }



    return true;
  }

  submit() {
    if (!this.preSave())
      return

    this.transactionData.userId = this.userId;
    this.transactionData.tenderId = this.tenderId;
 
    

    if(this.paymentId){
      this.transactionData.id = this.paymentId
      this._masterService.updateMasterData(apiUrl.paymentMaster, this.transactionData,this.paymentId).then(res=>{
        
        this.transactionData = new PaymentInfoDto()
        this.getData();
        
      })
    }
    else
    this._masterService.saveMasterData(apiUrl.paymentInfo, this.transactionData).then(res => {
      
      this.transactionData = new PaymentInfoDto()
      this.getData();
    })
  }
}
