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 { DatePipe, Location } from '@angular/common'
import * as XLSX from 'xlsx';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';

import { filter, map } from 'rxjs/operators';
import { emailDto } from 'src/app/_dto/email.dto';

@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[] = []

  dataSource: MatTableDataSource<unknown>;

  tenderId: number;

  headerData: any;

  tableData: any;

  tenderInputId: any;

  dialogRef: any;

  sndMaildialogRef: 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;

  seculevel: string;

  form: FormGroup;

  email: string;

  disabled = true;

  items = [];

  inputText = 'text';

  itemsAsObjects = [{ id: 0, name: 'Angular', readonly: true }, { id: 1, name: 'React' }];

  autocompleteItems = ['Item1', 'item2', 'item3'];

  autocompleteItemsAsObjects = [
    { value: 'Item1', id: 0, extra: 0 },
    { value: 'item2', id: 1, extra: 1 },
    'item3'
  ];

  subject: any

  emailData: emailDto;

  PayStatus: any;

  payType: string;

  boqStatus: any;

  loading: boolean = false;

  headerButtonVisible: boolean;


  constructor(
    private route: ActivatedRoute,
    private _router: Router,
    private _masterService: MasterService,
    private dialog: MatDialog,
    private _ui: UiService,
    private _errorService: ErrorTranslateService,
    public _location: Location,
    private datePipe: DatePipe,
    private http: HttpClient
  ) {

    this.tenderId = +this.route.snapshot.paramMap.get('id');
    this.seculevel = localStorage.getItem('seculevel')


    this.form = new FormBuilder().group({
      chips: [['chip'], []]
    });
  }


  ngOnInit(): void {
    this.getHeaderData(this.tenderId);
    this.getTableData(this.tenderId);



    this.printType = 'portrait';
    this.showPopup = true;
    this.fileSelected = false
    this.fileSelected2 = false
    this.seculevel = localStorage.getItem('seculevel')

    this.items = this.tableData?.email;
    this.emailData = new emailDto();
  }



  closePopup() {
    this.navigateTo('/dashboard')
    this.showPopup = false;
    this.Secretary = ''
    this.President = ''
  }


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

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






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

  backButton() {
    this._location.back();
  }

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

      let currentDate = new Date();
      let bidOpenDate = new Date(this.headerData.bidOpenDate);


      if (currentDate >= bidOpenDate) {

        this.headerButtonVisible = true;
      } else {
        this.headerButtonVisible = false;
      }


      if (this.headerButtonVisible) {
        this.displaycolumns = ['slNo', 'name', 'mobileNumber', 'email', 'finalBidAmt', 'ddDocuments', 'aadharNo'];
      }
      else {
        this.displaycolumns = ['slNo', 'name', 'mobileNumber', 'email'];

      }
    });

  }

  getTableData(id) {
    this.loading = true;
    this._masterService.getMasterDatabyId(apiUrl.bidReport, id).then(res => {
      this.loading = false;
      //  this.PayStatus=res.emdFeeStatus;
      // if(res.emdFeeType==null){
      //   this.payType ='not paid'
      // }else {
      //   this.payType = res.emdFeeType
      // }


      // this.tableData = res.report.filter(element => element.status == 'S' && element.finalBidAmt);
      this.tableData = res.report;
      this.tableData.forEach(element => {
        if (element.boqDocument != null && element.boqUser != null) {
          this.boqStatus = 'Uploaded'


        } else if (element.boqDocument == null && element.boqUser == null) {
          this.boqStatus = 'not applicable'


        } else if (element.boqDocument == null && element.boqUser != null) {
          this.boqStatus = 'not uploaded'


        }
        element.boqStatus = this.boqStatus;
      });


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

    // 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}`
  }
  downloadDDdocs(docName) {
    // let newWindow = window.location.href = `${environment.apiUrl}/${apiUrl.ddUpload}/${this.tenderId}/${userId}`
    this._masterService.downloadFileWithAuth(apiUrl.ddUpload, docName).then(res => {



    })
  }

  downloadBoqdocs(docName) {
    this._masterService.downloadFileWithAuth(apiUrl.quotedTender, docName).then(res => {



    })
  }

  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)

  //   })
  // }

  goToReportQouting() {
    this.navigateTo(`report-quoting/${this.tenderId}`)
  }

  gotoRequotedReport() {
    this.navigateTo(`requoted-report/${this.tenderId}`)

  }



  close() {
    this.sndMaildialogRef.close();
  }

  sendReportMail(templateRef) {
    this.items = []
    this.sndMaildialogRef = this.dialog.open(templateRef, {
      disableClose: false,
      width: '600px'
    });
  }

  sendReportViaMail() {

    if (!this.items || this.items.length < 1) {
      this._ui.toastMessage('Add Email IDs. (if you have already entered the mail id, then press enter or tab on the column)', 5000);
      return
    }
    this.emailData.toMail = []
    this.items.forEach(element => {
      this.emailData.toMail.push(element.value)
    });



    this._masterService.saveMasterData(apiUrl.report + `/${this.tenderId}`, this.emailData).then(res => {
      this.emailData.toMail = []
      this.close();
      this._ui.toastMessage('Bid Report sent successfully')
    },err=>{
      this._ui.toastMessage('Something went wrong!')
      this.close();


    })
  }

  sendEmailMsg(templateRef) {
    this.items = []
    this.emailData = new emailDto();
    this.dialogRef = this.dialog.open(templateRef, {
      disableClose: false,
      width: '600px'
    });

  }

  cancelEmailDialog() {
    this.closeDialog();
  }


  emailSubmit() {

    if (!this.items || this.items.length < 1) {
      this._ui.toastMessage('Add Email IDs. (if you have already entered the mail id, then press enter or tab on the column)', 5000);
      return
    }
    if (!this.emailData.subject || this.emailData.subject == null || this.emailData.subject == '') {
      this._ui.toastMessage('Add Subject');
      return
    }
    if (!this.emailData.content || this.emailData.content == null || this.emailData.content == '') {
      this._ui.toastMessage('Add Content');
      return
    }

    this.emailData.toMail = []
    this.items.forEach(element => {
      this.emailData.toMail.push(element.value)
    }); 



    this._masterService.saveMasterData(apiUrl.email, this.emailData).then(res => {
      this._ui.toastMessage(this._errorService.translate("emailSentSuccessfully"));
      this.closeDialog();
    }, err => {
      this._ui.toastMessage(err.error.message);
      this.closeDialog();

    })
  }
  ///////////////////////////////////////////

  private emailValid(control: FormControl) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(control.value) === false) {
      return {
        'emailValid@': true
      };
    }

    return null;
  }

  public requestAutocompleteItems = (text: string) => {
    const url = `https://api.github.com/search/repositories?q=${text}`;
    return this.http
      .get(url)
      .pipe(
        map((data: any) => data.items.map(item => item.full_name))
      );
  };

  public requestAutocompleteItemsFake = (text: string): Observable<string[]> => {
    return of([
      'item1', 'item2', 'item3'
    ]);
  };

  public options = {
    readonly: undefined,
    placeholder: '+ Tag'
  };

  public onAdd(item) {

  }

  public onRemove(item) {

  }

  public onSelect(item) {

  }

  public onFocus(item) {

  }

  public onTextChange(text) {

  }

  public onBlur(item) {

  }

  public async onTagEdited(item) {


  }

  public onValidationError(item) {

  }

  public transform(value: string): Observable<object> {
    const item = { display: `@${value}`, value: `@${value}` };
    return of(item);
  }

  private startsWithAt(control: FormControl) {
    if (control.value.charAt(0) !== '@') {
      return {
        'startsWithAt@': true
      };
    }

    return null;
  }

  private endsWith$(control: FormControl) {
    if (control.value.charAt(control.value.length - 1) !== '$') {
      return {
        'endsWith$': true
      };
    }

    return null;
  }

  private validateAsync(control: FormControl): Promise<any> {
    return new Promise(resolve => {
      const value = control.value;
      const result: any = isNaN(value) ? {
        isNan: true
      } : null;

      setTimeout(() => {
        resolve(result);
      }, 1);
    });
  }

  public asyncErrorMessages = {
    isNan: 'Please only add numbers'
  };

  public validators = [this.emailValid];

  public asyncValidators = [this.validateAsync];

  public errorMessages = {
    'emailValid@': 'Invalid email'
  };

  public onAdding(tag): Observable<any> {
    const confirm = window.confirm('Do you really want to add this tag?');
    return of(tag).pipe(filter(() => confirm));
  }

  public onRemoving(tag): Observable<any> {
    const confirm = window.confirm('Do you really want to remove this tag?');
    return of(tag).pipe(filter(() => confirm));
  }

  public asyncOnAdding(tag): Observable<any> {
    const confirm = window.confirm('Do you really want to add this tag?');
    return of(tag).pipe(filter(() => confirm));
  }


}



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