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';
import { TenderCategoryDto } from 'src/app/_dto/category.dto';
import { ThemePalette } from '@angular/material/core';
@Component({
  selector: 'app-tender-category',
  templateUrl: './tender-category.component.html',
  styleUrls: ['./tender-category.component.scss']
})
export class TenderCategoryComponent 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;


  seculevel: string = ''

  dataSource: MatTableDataSource<TenderCategoryDto>;

  displayedColumns :any =  ['actions','slno','tenderCategory','status'];

  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;

  categoryData :TenderCategoryDto[];

  selectedCategory:TenderCategoryDto;

  color: ThemePalette = 'primary';

  isEdit: 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
  ) { 
    // 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();
    
  }


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

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

  async ngOnInit() {
    
    this.enableDownload = true;
    this.categoryData = []
    this.getData();

  }



  getData(){

    this._masterService.getMasterData(apiUrl.tenderCategory).then((res) =>{
      this.categoryData = res;
      this.dataCopy = res;
      this.pageLength = this.categoryData.length;
      this.dataSource = new MatTableDataSource(this.categoryData);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
      this.noData = (this.categoryData && this.categoryData.length == 0) ? true : false;
      this.loading = false;
    },err=>{
      console.error(err)
    })
  


    
  }



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

  getCategoryById(id){
    this._masterService.getMasterDatabyId(apiUrl.tenderCategory,id).then(res=>{
      this.selectedCategory = res
    },err=>{
      console.log(err);
      
    })
  }

  editCategoryDialog(templateRef,id){
    this.selectedCategory = new TenderCategoryDto();
    this.isEdit = true;
    this.dialogRef = this.dialog.open(templateRef, {
      width: '500px',
      disableClose: false
    });
    this.getCategoryById(id);
  }

  openCategoryDialog(templateRef){
    this.isEdit = false;
    this.selectedCategory = new TenderCategoryDto();
    this.dialogRef = this.dialog.open(templateRef, {
      width: '500px',
      disableClose: false
    });
    this.selectedCategory.active = true
  }
  closeDialog(){
    this.dialogRef.close();
  }

  sortData(sort: Sort) {
    const data = this.categoryData.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 'tenderCategory':
          return compare(a.tenderCategory, b.tenderCategory, isAsc);
          case 'status':
            return compare(a.active, b.active, isAsc);
        default:
          return 0;
      }
    });
  }

  search(){
    this.categoryData = 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.categoryData = this.categoryData.filter(res => {
      let includedIntenderCategory = (res.tenderCategory) ? res.tenderCategory.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;

      if (includedIntenderCategory)
        return true;
      else
        return false;
    });
    this.noData = (this.categoryData && this.categoryData.length == 0) ? true : false;
    this.pageLength = this.categoryData.length;
    this.dataSource = new MatTableDataSource(this.categoryData);
    this.loading = false;
  }

  reset(){
    this.searchTerm = "";
    this.getData();
  }


  goToDashboard(){
    this.navigateTo(`admin/dashboard`)
  }
  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']);
  }

 


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



  saveCategory(){
    if(!this.selectedCategory.tenderCategory || this.selectedCategory.tenderCategory == ''){
      this._ui.toastMessage(this.errorService.translate('categoryNameCannotBeBlank'));
      return ;
    }
        this._masterService.saveMasterData(apiUrl.tenderCategory,this.selectedCategory).then(res=>{
          this._ui.toastMessage(this.errorService.translate('categorySaved'));
          this.closeDialog();
          this.getData();
          this.selectedCategory = new TenderCategoryDto();
        })
      
      
    
  }
  editCategory(){
    if(!this.selectedCategory.tenderCategory || this.selectedCategory.tenderCategory == ''){
      this._ui.toastMessage(this.errorService.translate('categoryNameCannotBeBlank'));
      return ;
    }
        this._masterService.updateMasterData(apiUrl.tenderCategory,this.selectedCategory,this.selectedCategory.id).then(res=>{
          this._ui.toastMessage(this.errorService.translate('categorySaved'));
          this.closeDialog();
          this.getData();
          this.selectedCategory = new TenderCategoryDto();
          this.isEdit = false;
        },err=>{
          console.log(err);
          
        })
  }


  deleteCategory(){
    this._masterService.deleteMasterData(apiUrl.tenderCategory,this.selectedCategory.id).then(res=>{
      this._ui.toastMessage(this.errorService.translate('deleteSuccess'));
      this.closeDialog();
      this.getData();
      this.selectedCategory = new TenderCategoryDto();
    },err=>{
      console.log(err);
      
    })
  }
}
function compare(a: any, b: any, isAsc: boolean): number {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
