import { Component, OnInit } from '@angular/core';
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';

@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;


  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private _masterService: MasterService,
    private _transactionService: TransactionService,
    private _ui: UiService,
    private _errorTranslateService: ErrorTranslateService
  ) {
    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();
  }








  getData() {

    let newDate = new Date();

    this._masterService.getMasterDatabyId(apiUrl.AllTenderData, this.tenderId).then((res) => {
      this.tenderData = res
      this.tenderDocuments = this.tenderData['tenderDoc']

      
      // console.log("paymentModeD",res.paymentModeD.paymentMode);
      

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

    //}

  }


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

  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 {
      const id = this.tenderId;
      this._masterService.getMasterDatabyId(apiUrl.drawingsDownloadDocs, id).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.drawingsDownloadDocs}/${id}`);
          setTimeout(() => {
            newWindow.close();
          }, 100);
        }
        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);
        }

      })
    }
  }

  // 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 => {
      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.bankDocs}/${id}`);
        setTimeout(() => {
          newWindow.close();
        }, 100);
      }
      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() {
    // if(this.seculevel != 'B'){
    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.paymentDetails.email=this.issueApplicationData.motherEmail
    // console.log('this.newPaymentRow.paymentMethod ====',this.newPaymentRow);

    //  let paymentMethod =  this.paymentMethodLovData.find(x=> x.id==this.newPaymentRow.paymentMethod)

   // console.log('this.paymentDetails===', this.paymentDetails);

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

  }

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

  }
}
