import { Component, OnInit, ViewChild } from '@angular/core';
import { Location } from '@angular/common';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { AuthenticationService } from 'src/app/hmg-common/services/authentication/authentication.service';
import { MenuResponse } from 'src/app/hmg-common/services/menu/models/menu-response';
import { MyTeamService } from '../service/my-team.service';
import { ModalController, IonInfiniteScroll } from '@ionic/angular';
import { DetailsComponent } from '../details/details.component';
import { Body } from '@angular/http/src/body';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  @ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;

  public pageNum = 1;
  public pageLimit = 50;
  public empSubordinate = [];
  public employee: any;
  public isReachEnd = false;
  public searchKey: any;
  public isSearch = false;
  public searchKeySelect = 'Name';
  public getEmployeeSubordinatesRequestObject: any;
  public selMenu: any;
  public selEmpNo: any;
  public totalEmployees = 0;
  public pageFirstVisit = false;
  myColor: string = 'secondary';
  public EmpTotal = [];
  public EmployeeTotal: any;
  public direction:any;

  public options = {
    cutoutPercentage: 80,
    tooltips: { enabled: false },
    legend: { display: false }
  };
  public data = {
    datasets: [
        {
            data: [100],
            backgroundColor: [
              '#269DB8'
            ],
            borderWidth: 5
        }]
  };
  // public filters = [
  //   {
  //     value: 0,
  //     name: 'All',
  //     active: true,
  //     color: '#124375'
  //   },
  //   {
  //     value: 0,
  //     name: 'Present',
  //     active: false,
  //     color: '#18a169'
  //   },
  //   {
  //     value: 0,
  //     name: 'Absent',
  //     active: false,
  //     color: '#38c9b3'
  //   },
  //   {
  //     value: 0,
  //     name: 'Late',
  //     active: false,
  //     color: '#114475'
  //   }
  // ];

  public slideOptsOne = {
    slidesPerView: 4,
    spaceBetween: 10
  };

  public previousActiveIndex = 0;
  public currentActiveIndex = 0;
  public searchNameOrUserName = '';
  public searchUserName = '';
  public searchEmail = '';
  public showEmailInput = false;
  public showUserNameOrNameInput = true;
  public showUserNameInput = false;
  arrList: any[];

  constructor(
    public ts: TranslatorService,
    public authService: AuthenticationService,
    public common: CommonService,
    public myTeamService: MyTeamService,
    public modalController: ModalController,
    private location: Location
  ) {

    this.direction = TranslatorService.getCurrentLanguageName();
  }

  ngOnInit() {
    this.common.sharedService.setSharedData( [], DetailsComponent.opendEmployeesARR);
    this.setIntitial();
   
    // this.getSuborinatesAttStatus();
  }
  toggleColor() {
    this.myColor = 'secondary';
    // this.myColor = '#269DB8'
}

  // activeFilter(index: number) {
  //   this.previousActiveIndex = this.currentActiveIndex;
  //   this.currentActiveIndex = index;
  //   this.filters[this.previousActiveIndex].active = false;
  //   this.filters[this.currentActiveIndex].active = true;
  // }

  goback() {
    this.location.back();
  }

  setIntitial() {
    this.selMenu = this.common.sharedService.getSharedData(MenuResponse.SHARED_DATA, false);
    this.selEmpNo = this.selMenu.userid;
    this.isSearch = this.selMenu.search ? this.selMenu.search : this.isSearch;
    if (!this.isSearch) {
      this.getEmpSubordinate();
    }
  }

  searchEmployee(event) {
    // this.isSearch = true;
    // this.empSubordinate = [];
    // this.getEmpSubordinate();
    const val = event.target.value;
    console.log(this.searchKeySelect)
    if (val === '') {
      this.empSubordinate = this.arrList;
      this.isSearch = false;
    }
    if(this.searchKeySelect === 'Name'){
      this.empSubordinate = this.arrList.filter((item) => {
        this.isSearch = true;
        return (item.EMPLOYEE_NAME.toLowerCase().indexOf(val.toLowerCase()) > -1);
      });
    } else if(this.searchKeySelect === 'User Name'){
      this.empSubordinate = this.arrList.filter((item) => {
        this.isSearch = true;
        return (item.EMPLOYEE_NUMBER.toLowerCase().indexOf(val.toLowerCase()) > -1);
      });
    } else if(this.searchKeySelect === 'Email'){
      this.empSubordinate = this.arrList.filter((item) => {
        this.isSearch = true;
        return (item.EMPLOYEE_EMAIL_ADDRESS.toLowerCase().indexOf(val.toLowerCase()) > -1);
      });
    }
    
  }

  getEmpSubordinate() {
    this.pageNum = 1;
    this.isReachEnd = false;
    const searchEmpNum = (this.searchKeySelect === 'User Name') ? this.searchUserName : '';
    const searchEmpName = (this.searchKeySelect === 'Name') ? this.searchNameOrUserName : '';
    const searchEmpEmail = (this.searchKeySelect === 'Email') ? this.searchEmail : '';

    if (this.isSearch) {
      this.selEmpNo = null;
    } else {
      this.selEmpNo = this.selMenu.userid;
    }

    const body = {
      P_SELECTED_EMPLOYEE_NUMBER: this.selEmpNo,
      P_SEARCH_EMPLOYEE_NUMBER: searchEmpNum,
      P_SEARCH_EMPLOYEE_DISPLAY_NAME: searchEmpName,
      P_SEARCH_EMAIL_ADDRESS: searchEmpEmail,
      P_PAGE_NUM: this.pageNum,
      P_PAGE_LIMIT: this.pageLimit
    };
    this.getEmployeeSubordinatesRequestObject = body;
    this.myTeamService.getEmployeeSubordinates(body).subscribe((result: any) => {
        if (this.common.validResponse(result)) {
          if (!this.pageFirstVisit) {
            this.pageFirstVisit = true;
            this.totalEmployees = result.P_NUM_OF_SUBORDINATES;
          }
          this.handleEmpResult(result.GetEmployeeSubordinatesList);
        }
    });
  }

  handleEmpResult(result) {
    this.EmployeeTotal  = result.length;
      const lastItemIndex = result.length - 1;
      const lastItem = result[lastItemIndex];
      if (lastItem) {
        if (lastItem.NO_OF_ROWS === lastItem.ROW_NUM) {
          this.isReachEnd = true;
          if (this.infiniteScroll) {
            this.infiniteScroll.complete();
          }
        } else {
          this.isReachEnd = false;
          if (this.infiniteScroll) {
            this.infiniteScroll.complete();
          }
        }
      }
      if (this.common.hasData(result)) {
        this.getEmployeeSubordinatesRequestObject.P_PAGE_NUM++;
        if (this.empSubordinate.length === 0) {
          this.empSubordinate = result;
        } else {
          this.empSubordinate = this.empSubordinate.concat(result);
        }
      } else {
        this.empSubordinate = [];
      }
      this.arrList = this.empSubordinate;
  }

  doInfinite(infiniteScroll) {
    if (!this.isReachEnd) {
      this.myTeamService.getEmployeeSubordinates(this.getEmployeeSubordinatesRequestObject).subscribe((result: any) => {
          if (this.common.validResponse(result)) {
            this.handleEmpResult(result.GetEmployeeSubordinatesList);
          }
          this.infiniteScroll.complete();
        });
    } else {
      if (this.infiniteScroll) {
       this.infiniteScroll.complete();
      }
    }
  }

  clearSearch() {
    this.isSearch = false;
    this.empSubordinate = this.arrList;
    this.searchNameOrUserName = '';
    this.searchUserName = '';
    this.searchEmail = '';
    // this.isSearch = false;
    // this.getEmployeeSubordinatesRequestObject.P_PAGE_NUM = 1;
    // this.empSubordinate = [];
    // this.isReachEnd = false;
    // this.searchNameOrUserName = '';
    // this.searchUserName = '';
    // this.searchEmail = '';
    // this.getEmpSubordinate();
  }

  getDetails(index) {
    this.common.sharedService.setSharedData(this.empSubordinate[index], MyTeamService.EMPLOYEE_SHARED_DATA);
    this.common.sharedService.setSharedData(this.selMenu, MenuResponse.SHARED_DATA);
    this.common.openMyTeamDetails();
  }

  goToSubordinate() {
    // this.presentModal();
  }

  showSelectedField(value: any) {
    if (this.searchKeySelect === 'Name') {
      this.showEmailInput = false;
      this.showUserNameInput = false;
      this.showUserNameOrNameInput = true;
    } else if (this.searchKeySelect === 'Email') {
      this.showUserNameOrNameInput = false;
      this.showUserNameInput = false;
      this.showEmailInput = true;
    } else if (this.searchKeySelect === 'User Name') {
      this.showUserNameOrNameInput = false;
      this.showEmailInput = false;
      this.showUserNameInput = true;
    }
  }

 

  // getSuborinatesAttStatus(){
  //   const request = {
  //     // SearchMonth:"January",
  //     SearchYear:Number,

  //   };
  //   // this.myTeamService.getSuborinatesAttStatus().subscribe((result: any) =>
  //   this.myTeamService.getSuborinatesAttStatus(request, ()=> {} , this.ts.trPK('general', 'retry')).subscribe((result)=>
  //    {   
  //     this.handleRespondSuborinatesAttStatusResult(result);  
            
  //      })
  //     }

  //     handleRespondSuborinatesAttStatusResult(result){
  //       // this.EmpTotal  = result.GetSubordinatesAttdStatusList.length;
  //       this.EmpTotal  = result.GetSubordinatesAttdStatusList[0].NUMBER_OF_EMPLOYEES;
  //       console.log("total no "+this.EmpTotal)
  //     }
  filterList(event) {
    const val = event.target.value;
    if (val === '') {
      this.arrList = this.empSubordinate;
    }
    this.arrList = this.empSubordinate.filter((item) => {
      return (item.title_EN.toLowerCase().indexOf(val.toLowerCase()) > -1);
    });
  }
}
