import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { PurchaseDto } from 'src/app/_dto/purchase.dto';
import { TenderDetailDto } from 'src/app/_dto/tender-detail.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 { TransactionService } from 'src/app/_providers/_services/transaction.service';
import { UiService } from 'src/app/_providers/_services/ui.service';
import { environment } from 'src/environments/environment.prod';
import Swal from 'sweetalert2';

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

  tenderId: number;

  tenderData: any;

  nitItemDocuments: any[] = [];

  workItemDocuments: any[] = [];

  drawingsDocuments: any[] = [];

  tenderDocuments: any;

  paymentDetails: PurchaseDto;

  tempID: any;

  newPaymentRow: any;

  currentDate = new Date();

  enableDownload: boolean = true

  paymentStatus: string;

  userId: string;

  amountPaid: boolean = false;

  seculevel: string;

  displayedColumns: string[] = ['field', 'value'];
  OnlinePayment: boolean;
  showDownloadButton: boolean;

  // ------digital signature--------//

  showPopup:boolean = false;
  fileSelected: boolean;
  fileSelected2:boolean;
  Secretary:any;
  President:any;
  selectedSecretaryFile: any;
  selectedPresidentFile: any;
  SecretarySigned: boolean;
  PresidentSigned: boolean;
  activeYn: any;
  dialogRef: any;
  newStatus: string;
  CancelTenderButtons: boolean;
  spinnerLoading: boolean =false;

  // -------------- ---------------//


  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private _masterService: MasterService,
    private _transactionService: TransactionService,
    private errorService:ErrorTranslateService,
    private _ui: UiService,
    private _errorTranslateService: ErrorTranslateService,
    private dialog: MatDialog
  ) {
    this.seculevel = localStorage.getItem('seculevel')
    this.tenderId = +this.route.snapshot.paramMap.get('id');
    this.paymentStatus = this.route.snapshot.paramMap.get('pay');
    this.getData()

  }
  ngOnInit(): void {
    this.tenderData = new TenderDetailDto()
    this.userId = localStorage.getItem('userId')
    this.seculevel = localStorage.getItem('seculevel')

    // console.log("this.seculevel", this.seculevel);
    this.enableDownload = true;
    this.getData();
    this.getPaymentData();

    this.fileSelected = false
    this.fileSelected2 = false
  }








  getData() {

    let newDate = new Date();

    this._masterService.getMasterDatabyId(apiUrl.AllTenderData, this.tenderId).then((res) => {
      this.tenderData = res
      if (res.tenderFeeExemption !== null && res.tenderFeeExemption !== undefined) {
        this.tenderData.tenderFeeExemption = res.tenderFeeExemption.trim();
      }
      
      this.tenderDocuments = this.tenderData['tenderDoc']

      this.activeYn = this.tenderData['activeYn']; 
      if(this.activeYn == 'N'){
        this.CancelTenderButtons = true
      }else if(this.activeYn == 'Y'){
        this.CancelTenderButtons = false
      }

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

      const saleStartDate = new Date(this.tenderData.saleStartDate);
      const saleEndDate = new Date(this.tenderData.saleEndDate);

      if (this.currentDate >= saleStartDate && this.currentDate <= saleEndDate) {
        this.showDownloadButton  = true; // Enable the button
      } else {
        this.showDownloadButton  = false; // Disable the button
      }



      this.filterDataByCategory();
    })
  }


  getPaymentData() {

    // if(this.OnlinePayment){
      // console.log("this.online");   
    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
      }})

    //}

  }
  getUniqueSubCategories() {
    if (!this.tenderData || !this.tenderData.subCategoryMaster) {
      return [];
    }
    const uniqueSubCategories = [];
    const subCategoryIds = new Set(); // To keep track of already added subcategory IDs
    for (const subCategory of this.tenderData.subCategoryMaster) {
      const subCategoryId = subCategory.tendersubCategoryD.tenderSubCategory;
      if (!subCategoryIds.has(subCategoryId)) {
        uniqueSubCategories.push(subCategory);
        subCategoryIds.add(subCategoryId);
      }
    }
    return uniqueSubCategories;
  }

  print(): void {
    window.print();
  }

  filterDataByCategory() {


    this.drawingsDocuments = this.tenderDocuments.filter(doc => doc.documentCategory === 'D');
    this.workItemDocuments = this.tenderDocuments.filter(doc => doc.documentCategory === 'WID');
    this.nitItemDocuments = this.tenderDocuments.filter(doc => doc.documentCategory === 'NIT');
  }
  navigateTo(destination: any) {
    this.router.navigate([destination])
  }

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

  goToDashboard(){
    this.navigateTo(`admin/dashboard`)
  }

  DownloadDrawingsZIP() {
    if (!this.amountPaid && this.seculevel == 'U' && this.OnlinePayment) {
        // Scroll to the "Pay" button
        var payButton = document.getElementById("headingBreak");
        if (payButton) {
            payButton.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
        this._ui.toastMessage(this._errorTranslateService.translate('pleasePayTheAmountForDoc'), 3000);
    } else {
        this.spinnerLoading = true;
        const id = this.tenderId;
        this._masterService.getMasterDatabyId(apiUrl.drawingsDownloadDocs, id).then((res) => {
            // Download logic
            window.location.href = `${environment.apiUrl}/${apiUrl.drawingsDownloadDocs}/${id}`;
        }, err => {
           
            if (err.status == 200) {
               
                window.location.href = `${environment.apiUrl}/${apiUrl.drawingsDownloadDocs}/${id}`;
            }
            if (err.status == 404) {
                alert('No Bank Document Found for the selected Tender.');
            }
            if (err.status == 500) {
                alert(`${err.message}`);
            } else {
                // Handle other errors
            }
        }).finally(() => {
            this.spinnerLoading = false; // Set spinnerLoading to false after download completes or fails
        });
    }
}

  // DownloadDrawingsZIP() {
  //   // Your code to download the ZIP file goes here

  //   // Scroll to the "Pay" button
  //   var payButton = document.getElementById("headingBreak");
  //   if (payButton) {
  //     payButton.scrollIntoView({ behavior: 'smooth', block: 'start' });
  //   }
  // }
  DownloadNIT(index: number) {
    const id = this.tenderId;
    // console.log(index);
    // console.log(this.nitItemDocuments[index].docName);
    
    
    this._masterService.getMasterDatabyId(apiUrl.noticeDownlaod, `${this.tenderId}/${this.nitItemDocuments[index].docName}`).then((res) => {

     } , err => {
      //  console.log('res===>', err);
        if (err.status == 200) {
        //  console.log('start >>>');
          // window.open(`${environment.apiUrl}/${apiUrl.bankDocs}/${id}`);
          let newWindow = window.open(`${environment.apiUrl}/${apiUrl.noticeDownlaod}/${this.tenderId}/${this.nitItemDocuments[index].docName}`);
          // setTimeout(() => {
          //   newWindow.close();
          // }, 10000);
        }
        if (err.status == 404) {
          alert('No Notice Document Found for the selected Tender.');
        }
        if (err.status == 500) {
          alert(`${err.message}`);
        }
        else {
          //alert(`An error Occured`);
          // let newWindow =  window.open(`${environment.apiUrl}/${apiUrl.noticeDownlaod}/${id}`);
          // setTimeout(() => {
          //   newWindow.close();
          // }, 100);
        }
  
      })
  }


  downloadWITZip() {

    if (!this.amountPaid && this.seculevel == 'U' && this.OnlinePayment) {
      // Scroll to the "Pay" button
      var payButton = document.getElementById("headingBreak");
      if (payButton) {
        payButton.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
      this._ui.toastMessage(this._errorTranslateService.translate('pleasePayTheAmountForDoc'), 3000);

    }
    else {
   // console.log('clicked');
    const id = this.tenderId;
    // let newWindow =  window.open(`${environment.apiUrl}/${apiUrl.bankDocs}/${id}`);
    //   setTimeout(() => {
    //     newWindow.close();
    //   }, 10);

    this._masterService.getMasterDatabyId(apiUrl.bankDocs, id).then(res => {

    }, err => { 
      if (err.status == 200) { 
        // window.open(`${environment.apiUrl}/${apiUrl.bankDocs}/${id}`);
        let newWindow = window.open(`${environment.apiUrl}/${apiUrl.bankDocs}/${id}`);
        setTimeout(() => {
          newWindow.close();
        }, 1000);
      }
      if (err.status == 404) {
        alert('No Bank Document Found for the selected Tender.');
      }
      if (err.status == 500) {
        alert(`${err.message}`);
      }
      else {
        //alert(`An error Occured`);
        // let newWindow =  window.open(`${environment.apiUrl}/${apiUrl.bankDocs}/${id}`);
        // setTimeout(() => {
        //   newWindow.close();
        // }, 100);
      }

    })
    // window.open('http://192.168.1.112:3500/api/v1/file-upload/Bank-Documents-Arc/'+id);
  }
  }


  async paymentGateway() {
    // this.paymentDetails = new PurchaseDto();
    // this.paymentDetails.application = this.tenderId;
    // this.paymentDetails.mobile = localStorage.getItem('mobile')
    // this.paymentDetails.email = "accuratesoftware2022@gmail.com";
    // this.paymentDetails.amount = this.tenderData.tenderFee;
    // this.paymentDetails.type = "I"


    // this._transactionService.createPayment(this.paymentDetails).then(
    //   res => {
    //     this.onSuccessPayment(res);
    //   },
    //   err => {
    //     this.onFailurePayment(err);
    //   }
    // );


    this.router.navigate([`qr-payment/${this.tenderId}`])

  }

  onSuccessPayment(response) {
    if (response.url) {
      // Render PayUmoney payment gateway page
      window.location.href = response.url;
    }
  }

  onFailurePayment(err) {
  //  console.log('Failure Payment : ' + err);
    this._ui.toastMessage(err.message ? err.message : this._errorTranslateService.translate('errInSave'), 3000);

  }

  // -------------------------------------------------------------------------------------------

  


  CancelTender(id){
    this.showPopup = true;
     
     this.showPopup = true;
  }
  closePopup() {
    this.showPopup = false;
    this.Secretary =''
    this.President = ''
  }
  
  async UploadsecretaryFiles(event,SecretaryFile){
  
    const allowedExtensions = ['cer'];
  
    this.selectedSecretaryFile = event.target.files[0];
    if (this.selectedSecretaryFile) {
  
      const fileExtension = this.selectedSecretaryFile.name.split('.').pop();
  
      if (!allowedExtensions.includes(fileExtension)) {
        this._ui.toastMessage(this.errorService.translate('invalidFileFormat'), 3000);
        return; 
      }
  
      this.Secretary = this.selectedSecretaryFile.name;
     
      
    const formData = new FormData();
    formData.append('adminUser', '2');
    formData.append('certificate', this.selectedSecretaryFile);
  
     
    
  
   await this._masterService.saveMasterData(apiUrl.digitalSignature,formData).then((res) =>{
   
      if(res.message = "Authentication Successfully Completed"){
       
        
        this._ui.toastMessage(this.errorService.translate('AuthenticationSuccessfullyCompleted'), 3000);
        this.SecretarySigned = true
  
      }else{
        this.SecretarySigned = false
      }
      
      
    },(err) => {
      if(err.status === 201){
        this._ui.toastMessage(this.errorService.translate('AuthenticationSuccessfullyCompleted'), 3000);
        this.SecretarySigned = true
      }
     
      if (err.status === 500) {
        this._ui.toastMessage(this.errorService.translate('invalidFileFormat'), 3000);
  
      }
      if(err.status === 400){
        this._ui.toastMessage(this.errorService.translate('KeyNotMatchingPleaseTryAgain'), 3000);
        this.SecretarySigned = false
        this.Secretary =''
      }
      if(err.status === 401){
        this._ui.toastMessage(this.errorService.translate('Digital Signature Expired'), 3000);
        this.SecretarySigned = false
        this.Secretary =''
      }
  
  
  
    })
  }
    
  
  }
  deleteSecretaryInput(){
  
  }
  
  async UploadPresidentFiles(event,President){
  
  const allowedExtensions = ['cer'];
  
    this.selectedPresidentFile = event.target.files[0];
    if (this.selectedPresidentFile) {
  
      const fileExtension = this.selectedPresidentFile.name.split('.').pop();
  
      if (!allowedExtensions.includes(fileExtension)) {
        this._ui.toastMessage(this.errorService.translate('invalidFileFormat'), 3000);
        return; 
      }
  
      this.President = this.selectedPresidentFile.name;
  
      const formData = new FormData();
      formData.append('adminUser', '1');
      formData.append('certificate', this.selectedPresidentFile);
  
      
      
  
     await this._masterService.saveMasterData(apiUrl.digitalSignature,formData).then((res) =>{
     
        if(res.message = "Authentication Successfully Completed"){
          
          
          this._ui.toastMessage(this.errorService.translate('AuthenticationSuccessfullyCompleted'), 3000);
          this.PresidentSigned = true
  
        }else{
          this.PresidentSigned = false
        }
        
        
      },(err) => {
        if(err.status === 201){
          this._ui.toastMessage(this.errorService.translate('AuthenticationSuccessfullyCompleted'), 3000);
          this.PresidentSigned = true
        }
       
        if (err.status === 500) {
          this._ui.toastMessage(this.errorService.translate('invalidFileFormat'), 3000);
  
        }
        if(err.status === 400){
          this._ui.toastMessage(this.errorService.translate('KeyNotMatchingPleaseTryAgain'), 3000);
          this.PresidentSigned = false
          this.President = ''
        }
        if(err.status === 401){
          this._ui.toastMessage(this.errorService.translate('Digital Signature Expired'), 3000);
          this.PresidentSigned = false
          this.President = ''
        }
  
  
  
      })
    }
      
  
    }
  
  deletePresidentInput(){
  
  }

  
  TenderCancelToggle(event){
    this.showPopup = true;  
   
  }
  
  VerifySignature(){

    const id = this.tenderId;
    this.showPopup = true;
    if(this.Secretary == null || this.Secretary == '' || this.Secretary == undefined){
      this._ui.toastMessage(this.errorService.translate('secretarySignatureCantBeBlank'), 3000);
      return false
      
    }else if(this.President == null || this.President == '' || this.President == undefined){
      this._ui.toastMessage(this.errorService.translate('PresidentSignatureCantBeBlank'), 3000);
      return false
    }else if(!this.SecretarySigned && !this.PresidentSigned){
      Swal.fire({
        icon: 'error',
        title: 'Oops...',
        text: 'Something went wrong!',
        // footer: '<a href="">Why do I have this issue?</a>'
      })
      return false
      //this._ui.toastMessage(this.errorService.translate('verificationFailed'), 3000);
     }else if(this.SecretarySigned && this.PresidentSigned){


       

      this.activeYn = this.activeYn === 'N' ? 'Y' : 'N';
       

      let body ={
        activeYn:  this.activeYn
      }
      this._masterService.postMasterData(apiUrl.TenderStatus,body,id).then((res) =>{
 
          if(this.activeYn == 'N'){
           this.activeYn == 'N'
          }else if(this.activeYn == 'Y'){
            this.activeYn == 'Y'
          }


          this._ui.toastMessage(res.data, 3000); 


          if(res.data == 'Digital Signature Expired'){
            this.activeYn == 'N'
        }
          this.closePopup()
        },
        (err) => {
          console.error(err);
          this._ui.toastMessage(err.error.message, 3000);
        }
      );
     
      this.showPopup = false;
     }
  }



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

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




}
