import { Component, OnInit, EventEmitter, Input, Output,ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { IgenMenuDto } from 'src/app/_dto/igenMenu.dto';
import { MenuFormatDto } from 'src/app/_dto/menu-format.dto';
import { apiUrl } from 'src/app/_providers/_resources/api-url.properties';
import { AuthService } from 'src/app/_providers/_services/auth.service';
import { MenuService } from 'src/app/_providers/_services/menu.service';
import { UiService } from 'src/app/_providers/_services/ui.service';
import { EmailService } from 'src/app/pages/auth/services';
import { Observable, of } from 'rxjs';
import { Email, User } from 'src/app/pages/auth/models';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort, Sort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { routes } from 'src/app/consts';
import { MasterService } from 'src/app/_providers/_services/master.service';
import { TenderDetailDto } from 'src/app/_dto/tender-detail.dto';
import { ErrorTranslateService } from 'src/app/_providers/_services/error-translate.service';
import { DatePipe } from '@angular/common';
import { MatDialog } from '@angular/material/dialog';
import { CommonDto } from 'src/app/_dto/common.dto';
import { error } from 'console';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-preview-approval',
  templateUrl: './preview-approval.component.html', 
  styleUrls: ['./preview-approval.component.scss']
})
export class PreviewApprovalComponent implements OnInit{

  @Input() isMenuOpened: boolean;

  @Output() isShowSidebar = new EventEmitter<boolean>();

  public user$: Observable<User>

  public emails$: Observable<Email[]>

  public routers: typeof routes = routes;

  schoolLogoPath: string;

  tenderData: any;

  seculevel: string = ''

  dataSource: MatTableDataSource<TenderDetailDto>;

  displayedColumns :any;

  dataCopy: any;

  pageLength: any;

  searchTerm:any;

  newDate = new Date();

  enableDownload: boolean = true

  amountPaid: boolean = false;

  @ViewChild('paginator') paginator: MatPaginator;

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

  noData: boolean;

  userId: string;

  tenderId: number;

  countStatusP: any;

  dialogRef: any;

  commonData:CommonDto

  showPopup: boolean = false;
 
  toggleEvent:any;

  id:string;

  activeYn: any;
  
  reject: boolean = false;

  verify:boolean = false;
  btnBadgeNumber: any;
  // ------digital signature--------//

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

  // -----------------------------//

  constructor(
    private _menuService: MenuService,
    private router: Router,
    private _ui: UiService,
    private emailService: EmailService,
    private authenticationService: AuthService,
    private _masterService: MasterService,
    private errorService:ErrorTranslateService,
    private datePipe: DatePipe,
    private route: ActivatedRoute,
    private dialog: MatDialog
  ) { 
    // this.user$ = this.getUser();
    this.seculevel = localStorage.getItem('seculevel')
    this.userId = localStorage.getItem('userId');
    this.tenderId = +this.route.snapshot.paramMap.get('id');
    
    // this.emails$ = this.emailService.loadEmails();
    // this.getSchoolLogo();
    // if(this.seculevel == 'B'){
    // }
    // else{
    //   this.displayedColumns = ['slno','title','publishedDate','bidOpenDate','userPayments','view','upload'];
    // }

       this.displayedColumns = ['slno','title','publishedDate','bidOpenDate','view','action'];

  }


  // displayedColumns: string[] = ['no', 'name','download'];
  

  loading: boolean = true;
  menuData: any;
  model: any;
  

  async ngOnInit() {
    
    this.enableDownload = true;
    this.commonData = new CommonDto()
    this.getData();
    this.paymentCheck()
    // this.fileSelected = false
    // this.fileSelected2 = false
    
    // await this._ui.userValidation()
    // this.loading = true;
    // this.getMenuData();

  }

  gotoVerify(element) {
    this.verify=true;
      this.id =element.id
      this.showPopup = true;
     
  }
  
  closePopup() {
    this.showPopup = false;
    this.verify=false;
    this.reject=false;
                
  }

  goToDashboard(){
    this.navigateTo(`sadmin/dashboard`)
  }


  verifyTender(){
    
  
    this.activeYn='Y';
    let body ={
      activeYn:  this.activeYn
    }
    
    this._masterService.postMasterData(apiUrl.TenderStatus,body,this.id).then(res=> {
     
      this.getData();

      this.showPopup=false;
      this.verify=false;
      this.reject=false;
      setTimeout(() => {
        this.getData();
          
        }, 2000);
      Swal.fire(
        'Verified',
        'Tender Verified Successfully',
        'success'
      )

    },err=>{
      // console.error(err) 
      this._ui.toastMessage(err.error.message,3000,true)
    })

  }
  

  gotoReject(element){
    this.reject=true;
    this.id =element.id
    this.showPopup = true;
   
  }


  rejectTender(){
    
    this.activeYn='N';
    let body ={
      activeYn:  this.activeYn
    }
    
    this._masterService.postMasterData(apiUrl.TenderStatus,body,this.id).then(res=> {
      this.showPopup=false;
      this.verify=false;
      this.reject=false;
      this.getData();
      setTimeout(() => {
      this.getData();
        
      }, 2000);

      Swal.fire(
        'Rejected',
        'Tender rejected Successfully',
        'success'
      )

    },err=>{
      // console.error(err) 
      this._ui.toastMessage(err.error.message,3000,true)
    })

  }

  getData(){
 let newDate = new Date();

  // let currentDate = this.datePipe.transform(newDate, 'yyyy-MM-ddTHH:mm:ss') 
    // if(this.seculevel != 'B')
    this.tenderData =[]
    
    this._masterService.getMasterData(`${apiUrl.adminTenderView}?where[activeYn]=S` ).then((res) =>{
      this.tenderData = res;

      this.btnBadgeNumber=this.tenderData.length ;
      
      for(let element of res){

        if(element.id == '56'){
          element.hide56 = 'true'
        }else
        element.hide56= 'false'

        const bidSubStartDate: Date = new Date(element.bidSubStartDate);
        const bidSubEndDate: Date = new Date(element.bidSubEndDate);
      
        if(newDate >= bidSubStartDate && newDate <= bidSubEndDate){
         
         
         
        element.hide = 'Active'
        }
        else
        element.hide = 'Closed'

      }
      this.dataCopy = res;
      this.pageLength = this.tenderData.length;
      this.dataSource = new MatTableDataSource(this.tenderData);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
      this.noData = (this.tenderData && this.tenderData.length == 0) ? true : false;
      this.loading = false;
    },err=>{
      console.error(err)
    })
    // else
    // this._masterService.getMasterData(apiUrl.adminTenderView +'?order[id]=DESC').then((res) =>{
    //   this.tenderData = res;
     

    //   for(let element of res){
    //     this._masterService.getMasterDatabyId(apiUrl.bidReport, element.id).then(result => {
    //       element.countStatusP = result.countStatusP; 
          
    //     })

    //     const publishDate: Date = new Date(element.publishDate);
    //     const bidSubEndDate: Date = new Date(element.bidSubEndDate);
    //     let bidOpenDate: Date = new Date(element.bidOpenDate);
        
    //     bidOpenDate.setMinutes(bidOpenDate.getMinutes() - 30);
    //     if(newDate >= bidOpenDate){
    //       element.reportHide = 'false'
    //     }
    //     if(newDate > publishDate){
    //       element.HideEdit = true
    //     }else {
    //       element.HideEdit = false
    //     }
      
    //     if(newDate >= publishDate && newDate <= bidOpenDate){
   
   
          
    //     element.hide = 'Active'
    //     }
    //     else if(newDate < publishDate){
    //     element.hide = 'Await'
    //     }
    //     else
    //     element.hide = 'Closed'

    //   }
    //   this.dataCopy = res;
    //   this.pageLength = this.tenderData.length;
    //   this.dataSource = new MatTableDataSource(this.tenderData);
    //   this.dataSource.sort = this.sort;
    //   this.dataSource.paginator = this.paginator;
    //   this.noData = (this.tenderData && this.tenderData.length == 0) ? true : false;
    //   this.loading = false;

    // },err=>{
    //   console.error(err)
    // })



    // const bidSubStartDate = new Date(this.tenderData.bidSubStartDate);
    // const bidSubEndDate = new Date(this.tenderData.bidSubEndDate);

    // if (this.currentDate >= bidSubStartDate && this.currentDate <= bidSubEndDate) {
    //   this.enableDownload = false; // Enable the button
    // } else {
    //   this.enableDownload = true; // Disable the button
    // }

    
  }

  getMarqueeData(){
    this.commonData.marquee = '';
    this._masterService.getMasterData(apiUrl.common).then(res=>{

      if(res && res.length > 0 && res[0].marquee && res[0].marquee != '' ){
        this.commonData.marquee = res[0].marquee;
        this.commonData.id = res[0].id
      }
      
    })
  }

  convertDateFormat(dateString: string): string {
    const date = new Date(dateString);
    return this.datePipe.transform(date, 'yyyy-MM-ddTHH:mm');
  }

  addNewTender(){
    this.navigateTo('/admin/add-tenders')
  }

  openNotificationDialog(templateRef){
    this.dialogRef = this.dialog.open(templateRef, {
      width: '500px',
      disableClose: false
    });
    this.getMarqueeData();
  }

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

  saveNotificationText(){
    if(!this.commonData.marquee || this.commonData.marquee == ''){
      this._ui.toastMessage(this.errorService.translate('notificationTextCannotBeBlank'));
      return ;
    }
    else{
      if(this.commonData.id){
        this._masterService.updateMasterData(apiUrl.common,this.commonData,this.commonData.id).then(res=>{
          this._ui.toastMessage(this.errorService.translate('notificationTextSaved'));
          this.closeDialog();
        })
      }
      
    }
  }
  sortData(sort: Sort) {
    const data = this.tenderData.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);
          case 'status':
          return compare(a.hide, b.hide, isAsc);
        default:
          return 0;
      }
    });
  }

  search(){
    this.tenderData = this.dataCopy;
    this.loading = true;
    if (!this.searchTerm || this.searchTerm == null || this.searchTerm == undefined || this.searchTerm == "") {
      this._ui.toastMessage(this.errorService.translate('enterSearchTerm'), 3000);
      this.getData();
      return;
    }
    this.tenderData = this.tenderData.filter(res => {
      let includedInTitle = (res.title) ? res.title.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
      let includedInPublishDate = (res.publishDate) ? res.publishDate.includes(this.searchTerm.toLowerCase()) : false;
      
      let includedInbidOpenDate = (res.bidOpenDate) ? res.bidOpenDate.includes(this.searchTerm.toLowerCase()) : false;

      if (includedInTitle)
        return true;
      if (includedInPublishDate)
        return true;
        if (includedInbidOpenDate)
        return true;
      else
        return false;
    });
    this.noData = (this.tenderData && this.tenderData.length == 0) ? true : false;
    this.pageLength = this.tenderData.length;
    this.dataSource = new MatTableDataSource(this.tenderData);
    this.loading = false;
  }

  reset(){
    this.searchTerm = "";
    this.getData();
  }
  // navigateTo(destination) {
  //   this.router.navigate([destination]);
  // }

  // async getMenuData() {
  //   this.menuData = []
  //   await this._menuService.getJsonData("sales-menu").then((res) => {
  //     res.forEach(element => {
  //       if (element.menuEnabled == "Y")
  //         this.menuData.push(element)
  //     });
  //     // this.menuData = res;
  //     this.loading = false;
  //     this.model = this.getMenuCompact(this.menuData, "root");
  //   },
  //     (err) => {
  //     });

  // }
  // getMenuCompact(menuList: IgenMenuDto[], parentMenuId: string, menuCompactData?: MenuFormatDto[]) {
  //   if (!parentMenuId)
  //     return [];
  //   if (!menuCompactData)
  //     menuCompactData = [];
  //   for (let menu of menuList) {
  //     if (menu.parentMenuId == parentMenuId && menu.menuEnabled == "Y") {
  //       let format: MenuFormatDto = { menuId: menu.menuId, icon: menu.icon, label: menu.description, langaugeLabelCode: menu.languageLabelCode, data: { description: menu.description, langaugeLabelCode: menu.languageLabelCode, menuId: menu.menuId, rightsGiven: menu.rightsGiven } };
  //       if (menu["isMegaMenu"]) format["isExpanded"] = true; else format["isExpanded"] = false;
  //       if (menu["isSideMenu"]) format["isSideMenu"] = true; else format["isSideMenu"] = false;
  //       if (menu["routerLink"]) format["routerLink"] = menu["routerLink"];
  //       // if (menu.menuType == "1") format["isExpanded"] = true;
  //       // if (menu.menuType != "1") format["isExpanded"] = false;
  //       // if (menu["routerLink"] === this.router.url) this.service.selectedMenu = format;
  //       if (menu["menuType"]) format["menuType"] = menu["menuType"];
  //       if (menu.menuType == "1") format["items"] = this.getMenuCompact(menuList, menu.menuId)
  //       if (menu["role"]) format["role"] = menu["role"];
  //       if (menu["project"]) format["project"] = menu["project"];
  //       if (this.seculevel == 'admin')
  //         menuCompactData.push(format);
  //       else {
  //         if (menu.role != 'admin') {
  //           menuCompactData.push(format);
  //         }
  //       }
  //     }
  //   }

  //   return menuCompactData;
  // }

  goToPayment(id){
    this.navigateTo(`admin/qr-payment/${id}`)
  }
  public openMenu(): void {
    this.isMenuOpened = !this.isMenuOpened;

    this.isShowSidebar.emit(this.isMenuOpened);
  }

  public signOut(): void {
 
    this.authenticationService.logOut();
    
  }

  paymentCheck(){
    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
      }

    })
  }

  signIn(){
    this.router.navigate(['/login']);
  }

  goToHome(){
    window.location.href = 'https://www.thrickodithanamscb.in/index.html#hero';
  }
  goToContactUs(){
    window.location.href = 'https://www.thrickodithanamscb.in/index.html#contact';
  }
  
  goToView(tenderId) {
   
    this.router.navigate(['sadmin/tender-view',tenderId]);
  }

  goToPaymentDetails(tenderId){
    this.router.navigate(['admin/payment-details',tenderId])
  }

  goToAddTenders(){
    this.router.navigate(['admin/add-tenders']);
  }

  goToUpload(tenderId){
   
    
this._masterService.getMasterDatabyId(apiUrl.UserUploadCheck,`${this.userId}/${tenderId}`).then((res)=> {

  if (res && res.length > 0) {
    this._ui.toastMessage(this.errorService.translate('DocumentsAlreadyUploaded'), 3000);

  } else {
    this.router.navigate(['/tender-upload',tenderId]);
  }
}).catch((error) => {
  console.error("Error fetching upload data:", error);
});
  
    


    //  
  }
  goToEdit(tenderId){
    this.router.navigate(['/add-tenders',tenderId]);
  }
  Cancel(){
    
  }

  

  // public getUser(): Observable<User> {
    // return of({
    //    email: localStorage.getItem('username'),
    //    name: localStorage.getItem('username'),

    // });
  // }

  navigateTo(destination: any) {
    this.router.navigate([destination])
  }


  goToReport(id){
    this.navigateTo(`bid-final-report/${id}`)

 
  }
 

  // CancelTender(id){
  //   this.showPopup = true;
  //    this.showPopup = true;
  // }
  // closePopup() {
  //   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);
  
    
  
  //  await this._masterService.saveMasterData(apiUrl.digitalSignature,formData).then((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
  //     }
     
  //     if (err.status === 500) {
  //       this._ui.toastMessage(this.errorService.translate('invalidFileFormat'), 3000);
  
  //     }
  //     if(err.status === 400){
  //       this._ui.toastMessage(this.errorService.translate('KeyNotMatchingPleaseTryAgain'), 3000);
  //       this.SecretarySigned = false
  //     }
  
  
  
  //   })
  // }
    
  
  // }
  // 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; 
  //     }
  
  //     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) =>{
  //       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
  //       }
       
  //       if (err.status === 500) {
  //         this._ui.toastMessage(this.errorService.translate('invalidFileFormat'), 3000);
  
  //       }
  //       if(err.status === 400){
  //         this._ui.toastMessage(this.errorService.translate('KeyNotMatchingPleaseTryAgain'), 3000);
  //         this.SecretarySigned = false
  //       }
  
  
  
  //     })
  //   }
      
  
  //   }
  
  // deletePresidentInput(){
  
  // }
  
  // 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
  //   }else if(!this.SecretarySigned && !this.PresidentSigned){
  //     Swal.fire({
  //       icon: 'error',
  //       title: 'Oops...',
  //       text: 'Something went wrong!',
  //       // footer: '<a href="">Why do I have this issue?</a>'
  //     })
  //     return false
  //     //this._ui.toastMessage(this.errorService.translate('verificationFailed'), 3000);
  //    }else if(this.SecretarySigned && this.PresidentSigned){
  //     Swal.fire({
  //       icon: 'success',
  //       title: 'Cancellation Successfully',
  //       showConfirmButton: false,
  //       timer: 1500
  //     })
  //     this.showPopup = false;
  //    }
  // }
  
  
  // openHelpDialog(templateRef) {
  //   this.dialogRef = this.dialog.open(templateRef, {
  //     width: '700px',
  //     disableClose: false
  //   });
  // }
  


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

