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

  displayedColumns: any = ['actions', 'slno', 'userName', 'email','category','maxAmount','active'];

  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;

  userData: UserDto[];

  selectedUser: UserDto;

  color: ThemePalette = 'primary';

  isEdit: boolean = false;
  tenderSubCategory: any[];
  spinnerLoading: boolean;
  PrCompSpinnerLoading: 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')
    // 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.userData = []
    this.getData();


  }




  getData() {

    this._masterService.getMasterData(apiUrl.userData).then((res) => {
      this.userData = res;
      this.dataCopy = res;
      this.pageLength = this.userData.length;
      this.dataSource = new MatTableDataSource(this.userData);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
      this.noData = (this.userData && this.userData.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');
  }

  getUserById(id) {
    this._masterService.getMasterDatabyId(apiUrl.userData, id).then(res => {
      this.selectedUser = res
    }, err => {
      console.log(err);

    })
  }

  editUserDialog(templateRef, id) {
    this.selectedUser = new UserDto();
    this.isEdit = true;
    this.dialogRef = this.dialog.open(templateRef, {
      width: '500px',
      disableClose: false,
      maxHeight:'500px'
    });
    this.getUserById(id);
  }

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


  viewCategory(templateRef,element){
    this.tenderSubCategory =[]
    this.dialogRef = this.dialog.open(templateRef, {
      width: '500px',
      disableClose: false,
      // maxHeight:'400px'
    });

     
   

    this.tenderSubCategory = []; // Assuming this is where you want to store the results

    element.userSubcategoryMaster.forEach(element => {
        let subCategory = element.tenderSubCategoryD.tenderSubCategory;
    
        if (element.tenderSubCategoryD.tenderCategory === element.categoryD.id) {
            let category = element.categoryD.tenderCategory;
    
             
            let existingCategory = this.tenderSubCategory.find(item => item.category === category);
     
            if (!existingCategory) {
                let categoryBody = {
                    category: category,
                    subCategory: [{ subCategory: subCategory }]
                };
                this.tenderSubCategory.push(categoryBody);
            } else {
                 
                existingCategory.subCategory.push({ subCategory: subCategory });
            }
        }
    });
    
    

  }

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

  search() {
    this.userData = 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.userData = this.userData.filter(res => {
      let includedInUserName = (res.userName) ? res.userName.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
      let includedInEmail = (res.email) ? res.email.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
      let includedInSecuLevel = (res.secuLevel) ? res.secuLevel.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
   

      let includedInCategory = res.userSubcategoryMaster && res.userSubcategoryMaster.some(cat => {
        return cat.categoryD && cat.categoryD.tenderCategory && cat.categoryD.tenderCategory.toLowerCase().includes(this.searchTerm.toLowerCase());
      });
    
      let includedInSubCategory = res.userSubcategoryMaster && res.userSubcategoryMaster.some(cat => {
        return cat.tenderSubCategoryD && cat.tenderSubCategoryD.tenderSubCategory && cat.tenderSubCategoryD.tenderSubCategory.toLowerCase().includes(this.searchTerm.toLowerCase());
      });



      if (includedInUserName || includedInEmail || includedInSecuLevel || includedInCategory || includedInSubCategory )
        return true;
      else
        return false;
    });
    this.noData = (this.userData && this.userData.length == 0) ? true : false;
    this.pageLength = this.userData.length;
    this.dataSource = new MatTableDataSource(this.userData);
    this.loading = false;
  }

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


  downloadProjCompFile(docName){
    this.PrCompSpinnerLoading =true;

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

       
      this.PrCompSpinnerLoading =false;

    },err=>{
      this._ui.toastMessage('File not found')

      this.PrCompSpinnerLoading =false;

    })
  }

  downloadCompPrFile(docName){
    this.spinnerLoading =true;
    this._masterService.downloadFileWithAuth(apiUrl.cmpPrFileUpload,docName).then(res=>{

       
      this.spinnerLoading =false;

    },err=>{
      this._ui.toastMessage('File not found')
      this.spinnerLoading =false;

    })
  }

  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])
  }



  saveUser() {
    if (!this.selectedUser.category || this.selectedUser.category == '') {
      this._ui.toastMessage(this.errorService.translate('categoryNameCannotBeBlank'));
      return;
    }
    this._masterService.saveMasterData(apiUrl.userData, this.selectedUser).then(res => {
      this._ui.toastMessage(this.errorService.translate('categorySaved'));
      this.closeDialog();
      this.getData();
      this.selectedUser = new UserDto();
    })



  }
  editUser() {

    this._masterService.updateMasterData(apiUrl.userData, this.selectedUser, this.selectedUser.userId).then(res => {
      this._ui.toastMessage(this.errorService.translate('updateSuccess'));
      this.closeDialog();
      this.getData();
      this.selectedUser = new UserDto();
      this.isEdit = false;
    }, err => {
      console.log(err);

    })
  }


  deleteUser() {
    this._masterService.deleteMasterData(apiUrl.userData, this.selectedUser.userId).then(res => {
      this._ui.toastMessage(this.errorService.translate('deleteSuccess'));
      this.closeDialog();
      this.getData();
      this.selectedUser = new UserDto();
    }, err => {
      console.log(err);

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