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, log } from 'console';
import Swal from 'sweetalert2';
import { UntypedFormBuilder, UntypedFormControl, UntypedFormGroup } from '@angular/forms';
import { TenderCategoryDto } from 'src/app/_dto/category.dto';
import { MatOption } from '@angular/material/core';
import { tenderSubcategoryMasterDto } from 'src/app/_dto/tenderSubcategoryMaster.dto';
import { setTime } from 'ngx-bootstrap/chronos/utils/date-setters';

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

  countStatusP: any;

  dialogRef: any;

  commonData: CommonDto

  categoryConfigurationForm: UntypedFormGroup;

  categoryList: TenderCategoryDto[];

  subCategoryList: tenderSubcategoryMasterDto[];

  @ViewChild('allSelection') private allSelection: MatOption;
  userCategoryList: any;
  selected: boolean;
  selectedCategory: any[];
  selectedCategoryId: any;
  selectedCategoryIndex: any;
  subCatLength: any;
  spinnerLoading:boolean = false;


  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,
    private _fb: UntypedFormBuilder
  ) {
    // 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') {
      this.displayedColumns = ['actions', 'title', 'publishedDate', 'bidOpenDate', 'status', 'Paymentstatus', '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.categoryConfigurationForm = this._fb.group({
      selection: new UntypedFormControl(''),
      count: new UntypedFormControl(''),
    });
    this.commonData = new CommonDto()
    this.getData();
    this.paymentCheck();
    this.categoryList = []

  }



  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) =>{
    //   this.tenderData = res;



    //   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.tenderData = []
    this._masterService.getMasterData(apiUrl.userTender + '?order[id]=DESC').then((res) => {
      //  for (let i =0;i<res.length;i++){

      //   this.tenderData.push(res[i][0])
      //  }
      this.tenderData = res

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

        // })

        const publishDate: Date = new Date(element.publishDate);
        const bidSubStartDate: Date = new Date(element.bidSubStartDate)
        const bidSubEndDate: Date = new Date(element.bidSubEndDate);
        let bidOpenDate: Date = new Date(element.bidOpenDate);

        bidOpenDate.setMinutes(bidOpenDate.getMinutes() - 5);
        if (newDate >= bidOpenDate) {
          element.reportHide = 'false'
        }
        if (newDate > publishDate) {
          element.HideEdit = true
        } else {
          element.HideEdit = false
        }

        if (newDate >= bidSubStartDate && newDate <= 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;

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



  }
  getCategoryData() {


    this._masterService.getMasterData(apiUrl.category).then(res => {
      this.categoryList = res;
      if (res && res.length > 0) {
        this.selectedCategoryId = res[0].id
        this.selectedCategoryIndex = 0;
        this.categoryList[0].selected = true
      }
      // this.categoryList.forEach(element => {
      //   let body = {
      //     all: false,
      //     tenderSubCategory: `All ${element.tenderCategory} Category`,
      //     name: 'all',
      //     selected:false
      //   }
      //   element.tenderSubCategory.unshift(body)


      // });

     

    })
    // this.getSubcategory(this.selectedCategoryId,this.selectedCategoryIndex)
  }

  getSubcategory(id, i) {
    this.selectedCategoryId = id
    this.selectedCategoryIndex = i
    this.categoryList[i].selected = true

    //whether all sub categories are selected or not
    // let temp = 0;
    // this.categoryList[i].tenderSubCategory.forEach(element => {
    //   if (element.selected && element.name != 'all') {
    //     temp =temp + 1 ;
    //   } 
    // });
  
    // if(temp == (this.categoryList[i].tenderSubCategory.length -1)  ){
    //   this.categoryList[i].tenderSubCategory[0].selected =true;
    //    }
    //    else{
    //   this.categoryList[i].tenderSubCategory[0].selected =false;
    
    //    }
    
  }



  categoryChecked(event, subcategory, i) {

    if (subcategory.name && subcategory.name == 'all') {
      if (subcategory.selected) {
        for (let subCat of this.categoryList[i].tenderSubCategory) {
          subCat.selected = true;
        }
      }
      else {
        for (let subCat of this.categoryList[i].tenderSubCategory) {
          subCat.selected = false;
        }
      }


    }
    else {

      let temp = 0;

      this.categoryList[i].tenderSubCategory.forEach(subCat => {
       
        if (subCat.selected && subCat.name != 'all') {
          temp =temp + 1 ;
           
        } 
        })
       
        // if(temp == (this.categoryList[i].tenderSubCategory.length -1)  ){
        // this.categoryList[i].tenderSubCategory[0].selected =true;
     
      
        //  }
        //  else{
        // this.categoryList[i].tenderSubCategory[0].selected =false;
      
        //  }

  }
  }



  getUserCategories() {
    this._masterService.getMasterData(apiUrl.userCategory).then(res => {
      this.userCategoryList = res;
      let temp =0
      
       this.userCategoryList.forEach(element => {

         this.categoryList.forEach(cat => {

         for (let subCat of cat.tenderSubCategory) {

            if (element.subCategory == subCat.id) {
              subCat.selected = true;
              // temp =temp+1;
              temp++
            }
          }
          
          
          
          if(temp == ( cat.tenderSubCategory.length - 1 ) && cat.tenderSubCategory[0].name =='all'){
         
            cat.tenderSubCategory[0].selected = true;
          }
          else{
            // cat.tenderSubCategory[0].selected = false;

          }
        });
      });


    })

  
  }

  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: '800px',
      disableClose: false,
      maxHeight:'80vh'
    });
    this.categoryList=[]
    this.getMarqueeData();
    this.getCategoryData();
    this.getUserCategories()

    setTimeout(() => {
    this.getUserCategories()
      
    }, 500);
  }

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

  saveCategory() {
    this.spinnerLoading = true;
    let tempArray = []
    this.categoryList.forEach(cat => {

      for (let subCat of cat.tenderSubCategory) {
        if (subCat.selected && subCat.name != 'all') {
          let body = { Category: null, subCategory: null }
          body.Category = cat.id;
          body.subCategory = subCat.id
          tempArray.push(body)
        }
      }
    });

    this._masterService.saveMasterData(apiUrl.categoryEdit, tempArray).then(res => {
      this._ui.toastMessage(this.errorService.translate('updateSuccess'));
    this.spinnerLoading = false;
      this.closeDialog();
      this.getData();
       


    })

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


  goToPayment(id) {
    this.navigateTo(`/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(['/tender-view', tenderId]);
  }

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

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

  goToUpload(tenderId, tender) {
     

    if (tender.paymentModeD.paymentMode && tender.paymentModeD.paymentMode != 'Offline') {

      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._masterService.getMasterDatabyId(apiUrl.paymentUserCheck + `/${this.userId}`, tenderId).then(res => {
            if (res && res[0].status && res[0].status == 'S') {

              if (!tender.emdFeeApplied) { //If emdfeeapplicable is false, there is no requirement to pay the emd fee.

                
                this.router.navigate([`/tender-upload/${tenderId}`])


              } else {

                let screen = 'E'
                this.router.navigate([`qr-payment/${tenderId}/${screen}`])
              }


            }
            else {
              this._ui.toastMessage('You must to Pay Tender Fee Amount First');
              let screen = 'T'
              this.router.navigate([`tender-view/${tenderId}`])
            }

          }, err => {
            this._ui.toastMessage('You must to Pay Tender Fee Amount First');
            let screen = 'T'
            this.router.navigate([`tender-view/${tenderId}`])

          })




        }
      }).catch((error) => {
        console.error("Error fetching upload data:", error);
      });
    }
    else {

      //if payment mode is offline

      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._masterService.getMasterDatabyId(apiUrl.paymentUserCheck + `/${this.userId}`, tenderId).then(res => {
          //   if (res && res[0].status && res[0].status == 'S') {
          
          if (!tender.emdFeeApplied) { //If emdfeeapplicable is false, there is no requirement to pay the emd fee.

                
            this.router.navigate([`/tender-upload/${tenderId}`])


          } else{

            let screen = 'E'
            this.router.navigate([`qr-payment/${tenderId}/${screen}`])
          }

         
        // }else{
        //   this._ui.toastMessage('You must to Pay Tender Fee Amount First');
        //   let screen = 'T'
        //   this.router.navigate([`tender-view/${tenderId}`])
        // }

      // },err=>{
      //   this._ui.toastMessage('You must to Pay Tender Fee Amount First');
      //       let screen = 'T'
      //       this.router.navigate([`tender-view/${tenderId}`])
      // })
    }
    
      }).catch((error) => {
        console.error("Error fetching upload data:", error);
      });
    }

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

  }





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


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


  }




  // tosslePerOne(field) {

  //   if (field == "select") {
  //     if (this.allSelection.selected) {
  //       this.allSelection.deselect();
  //       return false;
  //     }
  //     if (this.categoryConfigurationForm.controls.selection.value.length == this.categoryList.length) {
  //       this.allSelection.select();
  //     }

  //   }

  // }

  // toggleAllSelection(field) {
  //   if (field == "select") {
  //     if (this.allSelection.selected) {
  //       this.categoryConfigurationForm.controls.selection
  //         .patchValue([...this.categoryList.map(item => item.id), 0]);

  //     } else {
  //       this.categoryConfigurationForm.controls.selection.patchValue([]);
  //     }
  //   }


  // }

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