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

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

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