import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatSort, Sort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
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';
import Swal from 'sweetalert2';
import * as XLSX from 'xlsx';
@Component({
  selector: 'app-bid-final-report',
  templateUrl: './bid-final-report.component.html',
  styleUrls: ['./bid-final-report.component.scss']
})
export class BidFinalReportComponent implements OnInit {

  printSize = [{ name: "landscape" }, { name: "portrait" }]

  printType: any;

  title = 'Bid Final Report';

  today: Date = new Date();

  @ViewChild('table', { static: false }) table: ElementRef;

  @ViewChild(MatSort, { static: false }) sort: MatSort;

  displaycolumns: string[] = ['slNo', 'name', 'mobileNumber', 'email', 'finalBidAmt', 'aadharNo'];

  dataSource: MatTableDataSource<unknown>;

  tenderId: number;

  headerData: any;

  tableData: any;

  tenderInputId: any;

  dialogRef: any;

  captchaText: string;

  userCaptchaInput: string;

  captchaMatching: boolean = true;

  fileSelected: boolean;

  fileSelected2:boolean;
  showPopup:boolean = false;
  Secretary:any;
  President:any;
  selectedSecretaryFile: any;
  selectedPresidentFile: any;
  SecretarySigned: boolean;
  PresidentSigned: boolean;

  userDocId: any;
  isIconRotating: boolean;

  constructor(
    private route: ActivatedRoute,
    private _router: Router,
    private _masterService: MasterService,
    private dialog: MatDialog,
    private _ui:UiService,
    private _errorService:ErrorTranslateService
  ) {

    this.tenderId = +this.route.snapshot.paramMap.get('id');
  }

  ngOnInit(): void {
    this.getHeaderData(this.tenderId);
    this.getTableData(this.tenderId);
    this.printType = 'portrait';
    this.showPopup = true;
    this.fileSelected = false
    this.fileSelected2 = false
  }

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

closePopup() {
  this.navigateTo('/dashboard')
  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);

  // console.log("s",formData);
  

 await this._masterService.saveMasterData(apiUrl.digitalSignature,formData).then((res) =>{
    // console.log(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
    }
   
    else if(err.status === 500) {
      this._ui.toastMessage(this._errorService.translate('invalidFileFormat'), 3000);

    }
    else if(err.status === 400){
      this._ui.toastMessage(this._errorService.translate('KeyNotMatchingPleaseTryAgain'), 3000);
      this.SecretarySigned = false
      this.Secretary =''
    }
    else 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; 
    }
    else{

    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) =>{
      console.log(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
      }
     
      else if (err.status === 500) {
        this._ui.toastMessage(this._errorService.translate('invalidFileFormat'), 3000);

      }
      else if(err.status === 400){
        this._ui.toastMessage(this._errorService.translate('KeyNotMatchingPleaseTryAgain'), 3000);
        this.PresidentSigned = false
        this.President = ''
      }
      else if(err.status === 401){
        this._ui.toastMessage(this._errorService.translate('Digital Signature Expired'), 3000);
        this.PresidentSigned = false
        this.President = ''
      }


    })
  }
  }
    

  }

VerifySignature(){


  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

    console.log();
    


  }else if(!this.SecretarySigned && !this.PresidentSigned){
    Swal.fire({
      icon: 'error',
      title: 'Oops...',
      text: 'Something went wrong!',
    })
    return false 
   }
   

   else if(this.SecretarySigned && this.PresidentSigned){

    Swal.fire({
      icon: 'success',
      title: 'Verified Successfully',
      showConfirmButton: false,
      timer: 1500
    })
    
    this.showPopup = false;
   }
}


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

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






  navigateTo(destination) {
    this._router.navigate([destination])
  }

  backButton() {
    this.navigateTo('/dashboard')
    // this.backClick.emit()
  }

  getHeaderData(id) {
    this._masterService.getMasterDatabyId(apiUrl.getTender, id).then(res => {
      this.headerData = res;
      this.tenderInputId = res.tenderId
    })
  }

  getTableData(id) {
    this._masterService.getMasterDatabyId(apiUrl.bidReport, id).then(res => {
      this.tableData = res.report.filter(element => element.status == 'S' && element.finalBidAmt);
      this.dataSource = new MatTableDataSource(this.tableData);
      this.dataSource.sort = this.sort;
    })
  }

  printScreen() {

    if (this.printType.trim() == 'landscape') {
      var css = `@page { size: ${this.printType}; }`,
        head = document.head || document.getElementsByTagName('head')[0],
        style = document.createElement('style');
      style.type = 'text/css';
      style.media = 'print';
      style.appendChild(document.createTextNode(css));
      head.appendChild(style);
    }
    // this._menuService.isShowSidebar = false
    setTimeout(() => {
      window.print();
    }, 1000);
  }



  excelDownload() {
    const ws: XLSX.WorkSheet = XLSX.utils.table_to_sheet(this.table.nativeElement);
    const merge = [
      { s: { r: 0, c: 4 }, e: { r: 0, c: 7 } }
    ];
    ws["!merges"] = merge;
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    XLSX.writeFile(wb, 'Bid-final-Report.xlsx');
  }


  sortData(sort: Sort) {

    // console.log('sorting...');

    // const data = this.tableData.slice();
    // if (!sort.active || sort.direction === '') {
    //   this.dataSource.data = data;

    //   return;
    // }

    // this.dataSource.data = data.sort((a, b) => {
    //   const isAsc = sort.direction === 'asc';
    //   switch (sort.active) {
    //     case 'title':
    //       return compare(a.title, b.title, isAsc);
    //     case 'publishedDate':
    //       return compare(a.publishDate, b.publishDate, isAsc);
    //       case 'bidOpenDate':
    //       return compare(a.bidOpenDate, b.bidOpenDate, isAsc);
    //     default:
    //       return 0;
    //   }
    // });
  }

  downloadUserDocs(userId) {
    let newWindow = window.location.href = `${environment.apiUrl}/${apiUrl.userBidDoc}/${this.tenderId}/${userId}`
  }

  openDialogBox(templateRef,userId) {
    this.userDocId = userId
    this.dialogRef = this.dialog.open(templateRef, {
      disableClose: false,
      width: '400px'
    });

    this.generateRandomText();
    this.captchaMatching = true
    this.userCaptchaInput = ''
  }


  generateRandomText() {
    this.isIconRotating = true;
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let randomText = '';

    for (let i = 0; i < 6; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length);
      randomText += characters[randomIndex];
    }

    this.captchaText = randomText;

    setTimeout(() => {
      this.isIconRotating = false;
    }, 1000);
    

  }

  captchaCheck(){
    if(this.captchaText == this.userCaptchaInput){
      this.dialogRef.close();
      this.downloadUserDocs(this.userDocId)
      
    }
    else{
      this.captchaMatching = false
      setTimeout(() => {
        this.captchaMatching = true
      }, 2000);
    }

  }

  sendMail(){
    this._masterService.getMasterDatabyId(apiUrl.emailReport,this.tenderId).then(res=>{
      this._ui.toastMessage(this._errorService.translate("emailSentSuccessfully"));
      this.getHeaderData(this.tenderId)
    },err=>{
      this._ui.toastMessage(err.error.message);
      this.getHeaderData(this.tenderId)

    })
  }
}
function compare(a: any, b: any, isAsc: boolean): number {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}