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 { paymentDto } from 'src/app/_dto/payment.dto';
import { TenderDocumentDto } from 'src/app/_dto/tender-documents.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 = 0;

  dialogRef: any;

  paymentStatus: any;

  EmdpaymentStatus: any;

  paymentId: any;

  @ViewChild(MatTabGroup) tabGroup: MatTabGroup;

  paymentGtwy:any = '';

  gatewayLov=[];
  mobileNo: any;

  paymentData:paymentDto;
  url: any;
  screen: any;
  paymentFor:any;
  emdFeeStatus:any
  payStatus: string =  '';
  PaymentMethodDD:any;

  phonepay:any

  ddFile ={fileName:"",filePath:""}
  docSize: any;


  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.mobileNo = localStorage.getItem('mobile')
    this.tenderId = +this.route.snapshot.paramMap.get('id');
    this.screen = this.route.snapshot.paramMap.get('screen'); 
  }

  qrImage: boolean = false;

  transId: any

  ddDocuments:TenderDocumentDto;

  emdFeePayment:boolean=false;

  ngOnInit(): void {

    this.ddDocuments = new TenderDocumentDto();

    // this.paymentGtwy='phonepay';
   this.paymentCheck();
   this.emdPaymentCheck();
   if(this.screen=='T'){
    this.paymentFor='Tender Fee'
    this.gatewayLov=[{label:"PhonePe",value:"phonepay"}]
             
   }
   else if (this.screen =='E'){
    this.emdFeePayment=true;
    this.paymentFor='Emd Fee'
    this.gatewayLov=[
      // {label:"PhonePay",value:"phonepay"},
              {label:"DD",value:"dd"}]
   }
    this.transactionData = new PaymentInfoDto()
    this.paymentData = new paymentDto();
    this.getData();

    setTimeout(() => {
      // this.getData()
      this.paymentCheck();
      this.emdPaymentCheck();
   
    }, 500);
  }


  // ngAfterViewInit(): void {

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

  getData() {
    this._masterService.getMasterDatabyId(apiUrl.getTender, this.tenderId).then(res => {
      
      if(this.screen=='T'){
        this.amountReq = res.tenderFee;

      }
      else   if(this.screen=='E'){
        this.amountReq = res.emdAmt; 
        
      }

      // this.generateUPIQRCode(environment.upiId, this.amountReq);

    })
    this.paymentCheck();

    // this._masterService.getMasterData(apiUrl.userData).then(res => {
    //     this.mobileNo =res.mobileNo;
    	 
    // })
  }

  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'
      }
    })
  }


  emdPaymentCheck() {
    this._masterService.getMasterDatabyId(apiUrl.paymentUserCheck + `/${this.userId}`, this.tenderId).then(res => { 
      if (res && res[0].status) {
        if (res[0].emdFeeStatus == 'PAYMENT_SUCCESS') {
          this.emdFeeStatus = 'Payment success';
          this.payStatus =  'Paid';                                   

          }
        if (res[0].emdFeeStatus == 'PAYMENT_ERROR') {
          this.emdFeeStatus = 'Payment Failed'
          this.payStatus =  `Pay ₹${this.amountReq} `;                                   
        }
        if (res[0].emdFeeStatus == 'PAYMENT_PENDING') {
          this.emdFeeStatus = 'Payment Pending';
          this.payStatus =  `Pay ₹${this.amountReq} `;                                   
        }
        if (res[0].emdFeeStatus == 'PAYMENT_DECLINED') {
          this.emdFeeStatus = 'Payment Declined';
          this.payStatus =  `Pay ₹${this.amountReq} `;                                   
        }
        if (res[0].emdFeeStatus == 'PAYMENT_DECLINED') {
          this.emdFeeStatus = 'Payment Declined';
          this.payStatus =  `Pay ₹${this.amountReq} `;                                   
        }if (res[0].emdFeeType == 'DD'){

          this.payStatus =  `Paid`;                                   
 
          this.emdFeeStatus = 'Selected payment method DD'; 
          this.PaymentMethodDD='DD'; 
          
        }if(res[0].emdFeeStatus == null && res[0].emdFeeType == null   ){
          
          this.payStatus =  `Pay ₹${this.amountReq} `;                                   
          this.emdFeeStatus = 'Payment Not Started';

        }
         
        this.paymentId = res[0].id;
      }

    }, err => {
      if (err.error.message.trim() == "User Payment Not Found") {
        this.emdFeeStatus = 'Payment Not Started';
        this.payStatus =  `Pay ₹${this.amountReq} `;                                   
        // 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() {
    if(this.emdFeePayment){
      this.goBack();
    }else{
      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;
    }
  }
  goTofileUpload(){
    this.router.navigate([`/tender-upload/${this.tenderId}`])
  }

openDDdialog(tempRef){ 
  
  this.dialogRef = this.dialog.open(tempRef, {
    width: '500px',
    disableClose: false
  });
}


  payment(tempRef?){ 


    if(this.payStatus != 'Paid'&& !this.paymentGtwy || this.paymentGtwy == '' || this.paymentGtwy == null || this.paymentGtwy == undefined){
      this._ui.toastMessage('Select Payment Method');
      return
    }
    if(this.paymentGtwy=='dd'){

      this.openDDdialog(tempRef)
    // this.router.navigate([`tender-upload/${ this.tenderId}/${this.paymentGtwy}`])
    //   return
    }else if(this.paymentGtwy=='phonepay'){

    
    this.paymentData.amount = this.amountReq;
    this.paymentData.mobile = this.mobileNo;
    this.paymentData.name = this.userId;
    this.paymentData.type = this.screen;
    this.paymentData.tenderId =this.tenderId ;
    this.paymentData.emdFeeType = this.paymentGtwy ;

    

    this._masterService.saveMasterData(apiUrl.phonepePaymentGtwy,this.paymentData).then(res=>{
   
      this.url=res.data.instrumentResponse.redirectInfo.url; 
      window.location.href = this.url;
      // window.open(this.url)
       
    })
    

  }
}
    

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

  uploadDDFiles(event){ 
    let file: File | undefined = event.target.files[0];
    if (!file) {
      return;
    }

    const fd = new FormData();
  fd.append('file', file );
    this._masterService.getMasterDatabyId(apiUrl.tenderDDdoc +`/${this.userId}`,this.tenderId).then(res=>{
let length =res.length; 

if(res.length<=0){
  this._masterService.saveMasterData(apiUrl.ddUpload,fd).then(res=>{
    this.ddFile.fileName = res.fileName;
    this.ddFile.filePath = res.filePath;
    this.docSize = res.fileSizeKB;
  
  })
}else{
  this._ui.toastMessage('Document already uploaded ')
}

    })


  }
  removeDDfile(){
    this._masterService.deleteMasterData(apiUrl.ddUpload,this.ddFile.fileName).then(res=>{
    this.ddFile.fileName = null
    this.ddFile.filePath = null
    })
  }

  goBack(){
    this.router.navigate(['/dashboard'])
  }


  saveDDdoc(){
    this.ddDocuments.docName = this.ddFile.fileName;
    this.ddDocuments.tenderId =this.tenderId;
    this.ddDocuments.documentSize =  this.docSize;
    this.ddDocuments.documentCategory ='DD';
    this.ddDocuments.userId = this.userId;
 
    this._masterService.saveMasterData(apiUrl.tenderDoc,this.ddDocuments).then(res=>{ 
    this.router.navigate([`tender-upload/${ this.tenderId}/${this.paymentGtwy}`])
    this.dialogRef.close()

    },err =>{
      this._ui.toastMessage(err.error.message);

    })
  }
}
