import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { TenderDetailDto } from 'src/app/_dto/tender-detail.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-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.scss']
})
export class ViewComponent implements OnInit {

  tenderId: number;
  tenderData: any;
  nitItemDocuments: any ;
  workItemDocuments: any;
  drawingsDocuments: any;
  tenderDocuments: any;
  OnlinePayment: boolean;
  currentDate = new Date();
  showDownloadButton: boolean;
  activeYn: string;
  CancelTenderButtons: boolean;

  

  constructor(private router: Router,
           private route: ActivatedRoute,
           private _masterService: MasterService,
           private _ui:UiService,
           private _errorTranslate:ErrorTranslateService,
           private _errorTranslateService: ErrorTranslateService) { 
            this.nitItemDocuments = []
            this.workItemDocuments=[];
            this.drawingsDocuments =[];
    this.tenderId = +this.route.snapshot.paramMap.get('id');
  }
  ngOnInit(): void {
    this.tenderData = new TenderDetailDto()
   // console.log("this.tenderId",this.tenderId);
    this.getData()
  }
 


getData(){
  this._masterService.getMasterDatabyId(apiUrl.AllTenderData,this.tenderId).then((res) =>{
  //  console.log("tenderData",res);
    this.tenderData = res
    this.tenderDocuments = this.tenderData['tenderDoc']
    this.activeYn = this.tenderData['activeYn']; 
    if(this.tenderData.paymentModeD.paymentMode == 'Online'){
      this.OnlinePayment = true
    }else {
      this.OnlinePayment = false;
    }

    if(this.activeYn == 'N'){
      this.CancelTenderButtons = true
    }else if(this.activeYn == 'Y'){
      this.CancelTenderButtons = 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
      }
   // console.log("data",this.tenderDocuments);
    this.filterDataByCategory();
  })
}

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

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

  DownloadDrawingsZIP() {
    if ( 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);
      this.goToView()
    }
    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);
        }

      })
    }
  }
  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.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);
      this.goToView()
    }
    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);
  }
  }
  // downloadWITZip() {
  //   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);

  // }

  goToView(){
    
    this._ui.toastMessage(this._errorTranslate.translate('pleaseLogin'));
    localStorage.setItem('returnUrl',`tender-view/${this.tenderId}`)
    this.navigateTo('auth/login')
  
}
}
