import { Component, OnInit,ViewChild,ElementRef,AfterViewInit, } from '@angular/core';
import { UntypedFormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { log } from 'console';
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 Swal from 'sweetalert2'
import { DialogComponent } from '../dialog/dialog.component';
import { DatePipe } from '@angular/common';
import { ThisReceiver } from '@angular/compiler';
@Component({
  selector: 'app-home-upload',
  templateUrl: './home-upload.component.html',
  styleUrls: ['./home-upload.component.scss']
})

export class HomeUploadComponent implements OnInit {

  phoneInvalid: boolean = false;

  secuLevel: any;

  formData: any = {};

  myForm: UntypedFormGroup;

  loading: boolean = true

  selected: boolean

  tenderId: number;

  bidAmount:number;

  agreeToTerms1: boolean = false;

  agreeToTerms2: boolean = false;

  showError: boolean = false;

  tenderData: any;

  selectedFiles: any;

  userId: string;

  agreeToTerms: boolean = false;

  fileSelected: boolean[]

  DEFAULT_COVER_COUNT: any;

  initialSelectionStatus: any;

  UploadedFile: TenderDocumentDto[];

  fileFormat: any[]

  userEmail: string;

  emailBody: any;

  username: string;

  paymentMethodLov=[{ label:"PhonePe",value:"phonepay" },
                    { label:"DD", value:"dd" }]

  paymentMethod : any;

  @ViewChild('bidAmountInput') bidAmountInput: ElementRef;

  @ViewChild('emdFeeInput') emdFeeInput : ElementRef ;

  amountPaid: boolean = false;

  OnlinePayment: boolean;

  dialogRef: any;

  emdFee: any;

  screen:any

  emdFeeStatus: string;

  paymentId: any;

  emdFeeApplicable: any;
  tenderFee: boolean;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private _ui: UiService,
    private _errorTranslate: ErrorTranslateService,
    private _masterService: MasterService,
    public dialog: MatDialog,
    private datePipe: DatePipe
  ) {

    
    // this.generateUPIQRCode('atlejs47@oksbi', '100');

    this.secuLevel = localStorage.getItem('seculevel');
    this.userId = localStorage.getItem('userId');
    this.tenderId = +this.route.snapshot.paramMap.get('id'); 
    this.userEmail =  localStorage.getItem('emailId');
    this.username =  localStorage.getItem('username');
    this.screen =this.route.snapshot.paramMap.get('screen')
      

  }


  ngOnInit(): void {
    this.loading = true;
    this.agreeToTerms = false;

    // this.screen='E'
    this.getData();
    this.getFileFormatLov();
    this.paymentCheck();
    this.emdPaymentCheck();
  }

  




  openDialog() {
    const dialogRef = this.dialog.open(DialogComponent, {
      width: '500px',
      data: {
        details: [
          'I hereby declare that I have read and understood the tendered documents, terms and conditions, drawings and specifications. The rates quoted are based on all the necessary understanding of the site conditions and challenges to carry out the work. The rates are the best I could offer and are inclusive of all taxes and levies.',
        ]
      }
    });

    dialogRef.afterClosed().subscribe((result) => {
      // Handle any logic after the dialog is closed (if needed)
      // For example, you can update the agreeToTerms variable based on the user's choice.
    });
  }

  openQrImage(templateRef) {
    this.dialogRef = this.dialog.open(templateRef, {
      width: '400px',
      disableClose: false
    });
    // this.verifiedOtp = true
  }

  paymentCheck(){
    this._masterService.getMasterDatabyId(apiUrl.paymentCheck, `${this.userId}/${this.tenderId}`).then(res => {

      if (res.length >0 && res[0].transId && res[0].transId != null && res[0].transId != undefined) {
        this.amountPaid = true
      }

    })
  }

  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'
        }
        if (res[0].emdFeeStatus == 'PAYMENT_ERROR') {
          this.emdFeeStatus = 'Payment Failed'
        }
        if (res[0].emdFeeStatus == 'PAYMENT_PENDING') {
          this.emdFeeStatus = 'Payment Pending'
        }
        if (res[0].emdFeeStatus == 'PAYMENT_DECLINED') {
          this.emdFeeStatus = 'Payment Declined'
        }
         
        this.paymentId = res[0].id
      }

    }, err => {
      if (err.error.message.trim() == "User Payment Not Found") {
        this.emdFeeStatus = 'Payment Not Started'
        // this.transactionData.status = 'P'
      }
    })
  }

  getData() {
    this._masterService.getMasterDatabyId(apiUrl.AllTenderData, this.tenderId).then((res) => {
      

    this.loading = false;

      this.tenderData = res;
      this.emdFee = this.tenderData.emdAmt;
      this.emdFeeApplicable = this.tenderData.emdFeeApplied

      if(this.tenderData.paymentModeD.paymentMode == 'Online'){
        this.OnlinePayment = true
      }else {
        this.OnlinePayment = false;
      }


      this.DEFAULT_COVER_COUNT = this.tenderData?.covers.length; // Replace with the actual number of rows
      this.initialSelectionStatus = new Array(this.DEFAULT_COVER_COUNT).fill(false);
      this.fileSelected = [...this.initialSelectionStatus];
       this.UploadedFile = [];
      for(let i=0;i<this.tenderData?.covers.length;i++){
        this.UploadedFile.push(new TenderDocumentDto());

      }
      
      const dateObj =  new Date(this.tenderData.bidOpenDate);
      const bidOpenDate =  this.datePipe.transform(dateObj, 'MMM d, y, h:mm:ss a');
      this.emailBody = {
        custName:this.username,
        tenderName:this.tenderData.title,
        bidOpenDate:bidOpenDate,
        email:this.userEmail
      }

      
    })
  }

  getFileFormatLov() {
    this._masterService.getMasterData(apiUrl.fileFormat).then((res) => {
      this.fileFormat = res

    })
  }

  UploadFiles(event, i) {
    const newFilename = `${this.tenderData.covers[i].Description.replace(/ /g, '')}${this.tenderData.covers[i].fileFormatD.fileFormat}`

    
  
    let fileFormatId = this.fileFormat.filter(element => element.fileFormat == this.tenderData.covers[i].fileFormatD.fileFormat);
  
    this.selectedFiles = event.target.files;
    let file = event.target.files[0]
    const fd = new FormData();
  
    // Create a new File object with the updated filename
    const updatedFile = new File([file], newFilename, { type: file.type });
    // const fd = new FormData();
    fd.append('file', updatedFile);
    if (file && this.tenderId) {
      this._masterService.postMasterData(apiUrl.userDocUpload + '/' + this.tenderId, fd, this.userId).then(res => {
        this.tenderData.covers[i].file = res.fileName;
        this.fileSelected[i] = true;
        this.UploadedFile[i].docName = res.fileName
        this.UploadedFile[i].description = this.tenderData.covers[i].Description;
        this.UploadedFile[i].docType = fileFormatId[0].id;
        this.UploadedFile[i].documentSize = res.fileSizeKB;
        this.UploadedFile[i].documentCategory = 'USERD';
        this.UploadedFile[i].tenderId = this.tenderId;
        this.UploadedFile[i].userId = this.userId;
        
      })
    }

  }

  navigateTo(destination: any) {
    this.router.navigate([destination])
  }
  updateTerms(event: any) {
    this.agreeToTerms = event.checked;
  }
  


  goToHome() {
    window.location.href = 'https://www.thrickodithanamscb.in/index.html#hero';
  }
  goToContactUs() {
    window.location.href = 'https://www.thrickodithanamscb.in/index.html#contact';
  }
  preSave() {

    if(this.bidAmount == 0 || this.bidAmount == null || this.bidAmount == undefined){
      this._ui.toastMessage(this._errorTranslate.translate("pleaseEnterBidFinalAmount"),2000,true); 
      return false;
    }
    for (let element of this.UploadedFile) {
      if (!element.docName) {
      this._ui.toastMessage(this._errorTranslate.translate("pleaseAddfiles"),2000,true); 

        return false; 
      }
    }

    if (!this.agreeToTerms) {
      this._ui.toastMessage(this._errorTranslate.translate("pleaseAgreeToTheTermsandCondition"), 2000, true);
      return false;
    }
  
  
    return true;
  }



  

  // openDialog(): void {
  //   this.showDialog = true;
  // }

  // closeDialog(): void {
  //   this.showDialog = false;
  // }

  


  submit() { 

    if(this.emdFeeApplicable){
  
     if(!this.amountPaid && this.OnlinePayment ){
       this._ui.toastMessage(this._errorTranslate.translate("pleasePayTheAmountForUpload"), 2000);
       return
     }
    }

    if(!this.preSave())
    return

    // if(this.paymentMethod=='phonepay'  ){
    //   this.router.navigate([`qr-payment/${ this.tenderId}/${this.screen}`])
   

    // }
   

   let id ={
    tenderId : this.tenderId,
    userId : this.userId,
   
    } 

    
   
    let type 

    if(this.emdFeeApplicable){
      type = "DD"
    }else{
       type = null;
    }

    if(!this.emdFeeApplicable && !this.OnlinePayment ){
        
      this.tenderFee =  false;

    }else  if(this.emdFeeApplicable) {
      this.tenderFee = false;
    }else{
      this.tenderFee = true;
    }

    let body= {
      bidAmount:this.bidAmount,
      type:type,
      tenderFee:this.tenderFee
    }
   
    
    // this._masterService.postMasterData(apiUrl.UploadBidAmount,body,`${this.userId}/${this.tenderId}`).then((res)=>{
    //   const body={email:this.userEmail}
    //   this._masterService.saveMasterData(apiUrl.UploadBidAmount,this.emailBody).then(res=>{
    //   },err=>{
    //     console.error(err);
    //   })
    // },err=>{
    //   console.error(err);
    // }) 


  //   if(this.emdFeeApplicable){

  //   if(this.screen !=='dd' && this.emdFeeStatus!=='Payment success'){
  //     Swal.fire({
  //       icon: 'error',
  //       title: 'Oops...',
  //       text: 'Please pay the Emd Fee !',
        
  //     })
  //   }
  // }

// [this.screen=='dd'] removed from this checking
//else--- case 
  // if(  this.screen=='dd' || this.emdFeeStatus=='Payment success' || !this.emdFeeApplicable ){
    
    Swal.fire({
      title: 'Are you sure you want to submit?',
      text: "Once submitted, document cannot be uploaded again",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, save it!'
    }).then((result) => {
      
if (result.isConfirmed ) {
  this._masterService.postMasterData(apiUrl.UploadBidAmount,body,`${this.userId}/${this.tenderId}`).then((res)=>{
    const body={email:this.userEmail}
    this._masterService.saveMasterData(apiUrl.emailUserSubmit,this.emailBody).then(res=>{

      this._masterService.saveAllMasterData(apiUrl.tenderDoc, this.UploadedFile).then(res => {
         Swal.fire(
           'Success',
           'Documents submitted successfully',
           'success'
         )
         this.router.navigate(['dashboard']);
       },err=>{
         Swal.fire({
           icon: 'error',
           title: 'Oops...',
           text: 'Something went wrong!',
           
         })
       })
    });
 
  },err=>{
    Swal.fire({
      icon: 'error',
      title: 'Oops...',
      text: err.error.message
      
    })
  }
  );

      }
    })
  // } 
    
  }

  deleteInput(i) {
    // const inputField = document.getElementById(inputFieldId) as HTMLInputElement;
    // if (inputField) {
    //   inputField.value = '';
    // }
    this._masterService.deleteMasterData(apiUrl.fileDelete + '/' + this.tenderId + '/' + this.userId, this.tenderData.covers[i].file).then(res => {
      this.tenderData.covers[i].file = '';
      this.fileSelected[i] = false;
      this.UploadedFile[i].docName = null
        this.UploadedFile[i].description = null;
        this.UploadedFile[i].docType = null;
        this.UploadedFile[i].documentSize = null;
        this.UploadedFile[i].documentCategory = null;
        this.UploadedFile[i].tenderId = null;
        this.UploadedFile[i].userId = null;
    })

  }


  
}
