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

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent 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;

  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,
  ) { 
    // this.user$ = this.getUser();
    this.seculevel = localStorage.getItem('seculevel')
    // console.log('=====level====',this.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'){
      this.displayedColumns = ['actions','title','publishedDate','bidOpenDate','status','view','report'];
    }
    else{
      this.displayedColumns = ['slno','title','publishedDate','bidOpenDate','view','upload'];
    }
  }


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

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

  async ngOnInit() {
    this.enableDownload = true;
    
    this.getData();
    this.paymentCheck()

    // await this._ui.userValidation()
    // this.loading = true;
    // this.getMenuData();

  }



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

  // let currentDate = this.datePipe.transform(newDate, 'yyyy-MM-ddTHH:mm:ss') 
    if(this.seculevel != 'B')
    this._masterService.getMasterData(apiUrl.getTender + '?order[id]=DESC').then((res) =>{
     // console.log("tenderData=1=",res);
      this.tenderData = res;


      
      for(let element of res){

        const bidSubStartDate: Date = new Date(element.bidSubStartDate);
        const bidSubEndDate: Date = new Date(element.bidSubEndDate);
      
        if(newDate >= bidSubStartDate && newDate <= bidSubEndDate){
          // console.log('1111111   ',element.bidSubStartDate);
          // console.log('2222222   ',element.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){

        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){
          // console.log('1111111   ',element.bidSubStartDate);
          // console.log('2222222   ',element.bidSubEndDate);
          
        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;
     // console.log("tenderData=2=",res);

    },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
    //   console.log("enabled");
    // } else {
    //   this.enableDownload = true; // Disable the button
    //   console.log("disabled");
    // }
  }

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

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


  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) => {
  //       console.log("===err====", 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;
  // }


  public openMenu(): void {
    this.isMenuOpened = !this.isMenuOpened;

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

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

  paymentCheck(){
    // console.log("this.userId");
    // console.log("this.tenderId");
    this._masterService.getMasterDatabyId(apiUrl.paymentCheck, `${this.userId}/${this.tenderId}`).then(res => {
     // console.log('pay res=>', 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(['/tender-view',tenderId]);
  }

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

  goToUpload(tenderId){
   
    
this._masterService.getMasterDatabyId(apiUrl.UserUploadCheck,`${this.userId}/${tenderId}`).then((res)=> {
//  console.log("UPLOAD DATA", res);

  if (res && res.length > 0) {
   // console.log("Data already uploaded.");
    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}`)
 
  }




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