import { Component ,OnInit ,ViewChild} from '@angular/core';
import { MatMenuTrigger } from '@angular/material/menu';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort, Sort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
import { apiUrl } from 'src/app/_providers/_resources/api-url.properties';
import { ErrorTranslateService } from 'src/app/_providers/_services/error-translate.service';
import { MasterService } from 'src/app/_providers/_services/master.service';
import { UiService } from 'src/app/_providers/_services/ui.service';
import {Location} from '@angular/common'


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

  dataSource: MatTableDataSource<unknown>;

  displaycolumns: string[] = ['selectUser','slNo', 'name', 'mobileNumber', 'email'];
  
  tableData: any;
  
  tenderId:any;

  allCheck:boolean=false;

  selectedUsers: any[];

  userLov: any;
 
  selectAllChecked: boolean = false;
  data: any[];
  userDataCopy: any;
  searchTerm: any;
  loading:boolean=false;

  
  @ViewChild('paginator') paginator: MatPaginator;

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

  @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
  noData: boolean;
  pageLength: any;
  seculevel: string;
  selected: boolean;
  noOfQuotes: number;


  constructor( private _masterService:MasterService,
               private route:ActivatedRoute,
               private _ui:UiService,
               private router:Router,
               private _location:Location,
               private errorTranslateService:ErrorTranslateService ){
    this.tenderId = +this.route.snapshot.paramMap.get('id');
    this.seculevel = localStorage.getItem('seculevel')

  }
  
  ngOnInit(): void {

    this.getData()

    this.selectedUsers=[]
  }

  getData(){

    this._masterService.getMasterDatabyId(apiUrl.revisedTenderUsers,this.tenderId).then(res => {
            this.userLov=res;
            this.noOfQuotes =parseInt(this.userLov[0].requotedOrder)+1;
            // this.tableData = res.report.filter(element => element.status == 'S' && element.finalBidAmt);
            // this.userDataCopy =res.report.filter(element => element.status == 'S' && element.finalBidAmt);
            // this.userLov = res.report.filter(element => element.status == 'S' && element.finalBidAmt);
            this.tableData = res
            this.userDataCopy =res
            this.userLov = res
            
            let boqCount =0;
            this.tableData.forEach(element => {
              if(element.boqUser&& element.boqUser!=''){
                element.selected = true;
                boqCount=boqCount+1;

                
                 
              }
              
          });
           
          if(boqCount==this.tableData.length){
            this.allCheck=true;
          }
           
            this.dataSource = new MatTableDataSource(this.tableData);
            this.noData = (this.tableData && this.tableData.length == 0) ? true : false;
            this.pageLength = this.tableData.length;
            this.dataSource.sort = this.sort;
          })
        }


        backButton() {
          // this.navigateTo('/dashboard')
          // this.backClick.emit()
          this._location.back();
        } 

        selectAllUser(event) {
          
          if (event.checked) {
            this.selectedUsers=[];
        
            this.userLov.forEach(user => {
              let temp ={}
              temp = {tenderId:this.tenderId,userId:user.userId,email:user.email}
        
              this.selectedUsers.push(temp)
            });
            this.userLov.forEach(element => {
              element.selected = true
            });
            this.allCheck = true;
          } else {
            this.userLov.forEach(element => {
              element.selected = false
            });
            this.selectedUsers=[];
            this.allCheck = false;
          }
        
          this.selectAllChecked = event.checked;  // Update the state of the "Select All" checkbox
        
        }
        
        
        selectUser(event,element,index) {
 
        
           
          let userId =element.userId;
          let email = element.email;
          if (event.checked) {
            let temp = {}
            temp = {tenderId:this.tenderId,userId:userId,email:email}
       

            this.selectedUsers.push(temp);
      
        
            if(this.selectedUsers.length >0 && this.selectedUsers.length == this.userLov.length){
          this.allCheck = true;
            }
          } else {
            this.allCheck = false;
        
           for (let i = 0; i < this.selectedUsers.length; i++) {
            if( this.selectedUsers[i].userId == userId){
              this.selectedUsers.splice(i,1);
            }
            
           } 
          }
        
          
         
        }



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

        search() {
          this.userLov = [...this.userDataCopy];
          this.data = [...this.userLov];
      
          if (!this.searchTerm || this.searchTerm.trim() === "") {
              this._ui.toastMessage(this.errorTranslateService.translate('enterSearchTerm'), 3000);
              this.getData();
              return;
          }
      
          this.userLov = this.data.filter(res => {
      
              let includedInUser = (res.userName) ? res.userName.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
              let includedInUserId = (res.userId) ? res.userId.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
              let includedInUserEmail = (res.email) ? res.email.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
              let includedInUserPhno = (res.mobileNumber) ? res.mobileNumber.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
      
              if (includedInUser || includedInUserId || includedInUserEmail || includedInUserPhno) {
                  return true;
              }
      
              else
              return false;
          });
      
          this.noData = (this.userLov.length === 0);
          this.pageLength = this.userLov.length;
          this.dataSource = new MatTableDataSource(this.userLov);
      }
      


        reviseTender(){
         

          if(this.selectedUsers.length<=0 ){
            this._ui.toastMessage('Please select any User ')
            
            return true ;
          }
          this.selectedUsers.forEach(element => {
            element.requotedOrder =  this.noOfQuotes;
            
          });
          this._masterService.saveMasterData(apiUrl.revisedTender,this.selectedUsers).then(res=>{
           
            this._ui.toastMessage('Users selected successfully');
             
            if(this.seculevel =='SuperAdmin'){
              // this.navigateTo(`/${this.seculevel}/dashboard`)
              this.navigateTo('sadmin/dashboard')
            }
            else if(this.seculevel =='Admin'){
              this.navigateTo('admin/dashboard')
            }
          })
        }



        reset(){
          this.searchTerm = "";
          this.getData();
          this.allCheck = false;

        }


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

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