import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../../services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import {Router} from '@angular/router';
import {NavigationService} from '../../../services/navigation/navigation.service'
import {WorkspaceService} from '../../../services/workspace.service';
import { NavBarService } from '../../pgm.service';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import {Subject} from "rxjs/Subject";
import _ from "lodash";
import {forEach} from "@angular/router/src/utils/collection";
import {CoachCandidateEvaluationService} from "../../../coach/shared/service/coach-candidate-evaluation.service";
// import { EmployeeNavBarService } from 'app/employee/employee-dashboard/employee-nav-bar.service';
import { environment } from '../../../../environments/environment.dev'; 

@Component({
  selector: 'app-pgm-employee-dash-board',
  templateUrl: './pgm-employee-dash-board.component.html',
  styleUrls: ['./../../../ta/ta-dashboard/ta-dashboard.component.css','./pgm-employee-dash-board.component.css',]
})
export class PgmEmployeeDashBoardComponent implements OnInit {

  private $destroyed = new Subject();
  userIcon='';
  calledclass = '';
  Id= 95;
  public registeredCandidates;
  public listCandidates =[];
  Location="Chennai";
  SkillId=1;
  filterActive = 'all';
  PGMEMPLANDING= false;
  name : string
  fullName : string
  isAssessment:any

  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any
  };

  courseFilter: any = { fullName: '' };

  courseEmployeLists: any = [];
  coaches : any = [];
  selectCoach : any = [];

  primarySkillCandidateCount = 0;
  techUseCaseCandidateCount = 0;
  bussUseCaseCandidateCount = 0;
  primarySkillEvalCandidates=[];
  techUseCaseEvalCandidate=[];
  bussUseCaseEvalCandidate=[];
  filterprimarySkillEvalCandidates=[];
  filtertechUseCaseEvalCandidate=[];
  filterbussUseCaseEvalCandidate=[];

  Skills = []
  recommendCourseEmployee = []
  reservedRecommendedCoursesEmployee = []

  primaryFilter= [
    {
      "id": "all",
      "name": "All"
    },
    {
      "id": "inProgress",
      "name": "In Progress"
    },
    {
      "id": "notScheduled",
      "name": "Schedule"
    },
    {
      "id": "evaluation",
      "name": "Evaluation"
    },
    {
      "id": "completed",
      "name": "Completed"
    }
  ];
  filter = [
    {
      "id": "all",
      "name": "All"
    },
    {
      "id": "inProgress",
      "name": "In Progress"
    },
    {
      "id": "evaluation",
      "name": "Evaluation"
    },
    {
      "id": "completed",
      "name": "Completed"
    }
  ];
  img_path = environment.imageUrl+'/assets/img/CFlanding/';
  ta_img_path = environment.imageUrl+'/assets/img/Taflow/';
  filterCol = false;
  recommendedCol = false;

  public levels;
  public city;
  public skills = [];
  // filters
  levelFilters = [];
  jobFilters = [];
  skillFilters = [];
  locationFilters = [];
  imageUrl: string = environment.imageUrl;
  constructor(protected localStorageService: LocalStorageService,
              private AuthService:AuthService,
              private router: Router,
              private navigate:NavigationService,
              private navBarService: NavBarService,
              private toastr: ToastsManager,
              private WorkspaceService:WorkspaceService,
              private CoachCandidateEvaluationService:CoachCandidateEvaluationService) {

    this.navBarService.setCurrentPage(0);
    this.CoachCandidateEvaluationService.setProperActiveTab(2);

    var empData
    empData = this.localStorageService.get('userInfo');
    this.empData = empData
    console.log(this.empData,"userInfo Detailssssss")
    if(window.location.origin == 'http://localhost:8080'){
      this.name = 'SABASH'
      this.fullName = 'SABASH LS'
      this.getAllRecommendedCourseEmployee(2,1,1);
      this.getCoachesforCandidate(1,1);
      // this.getRecommendedCourses();
      //this.getCoachCandidates(13,"Chennai", 1);
    }
    else {
      if (this.empData['firstName']) {
        this.name = this.empData['firstName'];
        this.fullName = this.empData['fullName'];
      }
      else {
        this.name = ''
        this.fullName = ''
      }
      this.getAllRecommendedCourseEmployee(this.empData.userInfoMstrId,this.empData.location, this.empData.skills[0]);
      this.getCoachesforCandidate(this.empData.location, this.empData.skills[0]);
    }
    this.resetFilters();
  }

  ngOnInit() {

  }



  searchCity(id) {
    this.toggleFilter(id, this.locationFilters);
    this.applyFilters();

  }

  skillFilter(skill) {
    this.toggleFilter(skill, this.skillFilters);
    this.applyFilters();
  }

  levelFilter(level) {
    this.toggleFilter(level, this.levelFilters);
    this.applyFilters();
  }

  jobTitleFilter(title) {
    this.toggleFilter(title, this.jobFilters);
    this.applyFilters();
  }

  private toggleFilter(filter: string, filterArray: string[]) {
    if (filterArray.includes(filter)) {
      let index = filterArray.indexOf(filter);
      filterArray.splice(index, 1);
    } else {
      filterArray.push(filter);
    }
  }


  private applyFilters() {
    console.group('filters');
    console.log('level', this.levelFilters);
    console.log('job', this.jobFilters);
    console.log('skill', this.skillFilters);
    console.log('locations', this.locationFilters);
    console.groupEnd();
    let that = this;

    this.recommendCourseEmployee = this.reservedRecommendedCoursesEmployee.filter(function (item, index, array){
      // return all the candidates in one of the selected levels or all the candidates if there is no selection done
      return that.levelFilters.length > 0 ? that.levelFilters.includes(item.filter.experienceLevel) : true;
    }).filter(function (item, index, array) {
      // return all the candidates in one of the selected jobs or all the candidates if there is no selection done
      return that.jobFilters.length > 0 ? that.jobFilters.includes(item.filter.jobId) : true;
    }).filter(function (item, index, array) {
      // return all the candidates in one of the selected skills or all the candidates if there is no selection done
      if (that.skillFilters.length > 0) {
        return _.intersection(that.skillFilters, item.filter.skillName).length > 0;
      } else {
        return true;
      }
    }).filter(function (item, index, array) {
      // return all the candidates in one of the selected skills or all the candidates if there is no selection done
      return that.locationFilters.length > 0 ? that.locationFilters.includes(item.userDetails.userInfoMstr.pgLocation.city) : true;
    });


    this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function (item, index, array){
      // return all the candidates in one of the selected levels or all the candidates if there is no selection done
      return that.levelFilters.length > 0 ? that.levelFilters.includes(item.filter.experienceLevel) : true;
    }).filter(function (item, index, array) {
      // return all the candidates in one of the selected jobs or all the candidates if there is no selection done
      return that.jobFilters.length > 0 ? that.jobFilters.includes(item.filter.jobId) : true;
    }).filter(function (item, index, array) {
      // return all the candidates in one of the selected skills or all the candidates if there is no selection done
      if (that.skillFilters.length > 0) {
        return _.intersection(that.skillFilters, item.filter.skillName).length > 0;
      } else {
        return true;
      }
    }).filter(function (item, index, array) {
      // return all the candidates in one of the selected skills or all the candidates if there is no selection done
      // return that.locationFilters.length > 0 ? that.locationFilters.includes(item.userDetails.userInfoMstr.pgLocation.city) : true;
    });

    this.techUseCaseEvalCandidate = this.filtertechUseCaseEvalCandidate.filter(function (item, index, array) {
      // return all the candidates in one of the selected levels or all the candidates if there is no selection done
      return that.levelFilters.length > 0 ? that.levelFilters.includes(item.filter.experienceLevel) : true;
    }).filter(function (item, index, array) {
      // return all the candidates in one of the selected jobs or all the candidates if there is no selection done
      return that.jobFilters.length > 0 ? that.jobFilters.includes(item.filter.jobId) : true;
    }).filter(function (item, index, array) {
      // return all the candidates in one of the selected skills or all the candidates if there is no selection done
      if (that.skillFilters.length > 0) {
        return _.intersection(that.skillFilters, item.filter.skillName).length > 0;
      } else {
        return true;
      }
    }).filter(function (item, index, array) {
      // return all the candidates in one of the selected skills or all the candidates if there is no selection done
      return that.locationFilters.length > 0 ? that.locationFilters.includes(item.userDetails.userInfoMstr.pgLocation.city) : true;
    });

    this.bussUseCaseEvalCandidate = this.filterbussUseCaseEvalCandidate.filter(function (item, index, array) {
      // return all the candidates in one of the selected levels or all the candidates if there is no selection done
      return that.levelFilters.length > 0 ? that.levelFilters.includes(item.filter.experienceLevel) : true;
    }).filter(function (item, index, array) {
      // return all the candidates in one of the selected jobs or all the candidates if there is no selection done
      return that.jobFilters.length > 0 ? that.jobFilters.includes(item.filter.jobId) : true;
    }).filter(function (item, index, array) {
      // return all the candidates in one of the selected skills or all the candidates if there is no selection done
      if (that.skillFilters.length > 0) {
        return _.intersection(that.skillFilters, item.filter.skillName).length > 0;
      } else {
        return true;
      }
    }).filter(function (item, index, array) {
      // return all the candidates in one of the selected skills or all the candidates if there is no selection done
      return that.locationFilters.length > 0 ? that.locationFilters.includes(item.userDetails.userInfoMstr.pgLocation.city) : true;
    });
  }
  getUserCurrentLocation() {
      var empData;
      empData = this.localStorageService.get('userInfo');
      if(empData){
        this.locationFilters.push(empData['locationName']);
      }
    // this.localStorageService.get('userInfo')
    // this.locationFilters.push(localStorage)
  }
  resetFilters() {
    this.levelFilters = [];
    this.jobFilters = [];
    this.skillFilters = [];
    this.locationFilters = [];
    this.getUserCurrentLocation();
    this.applyFilters();
    // this.filterCol =! this.filterCol;
  }

  closeFilter(){
    this.filterCol =! this.filterCol;
  }




  getCoachesforCandidate(Location,SkillId){
    this.coaches = []
    this.AuthService.getAllCoachesforCandidate({location:Location, skillId:SkillId}).then(responseData =>{
      console.log(responseData,'getAllCoaches')

      for(var value of responseData.userInfoDtls){
        console.log(value.userInfoMstr.fullName)
        if(value.userInfoMstr.fullName != null){
          this.coaches.push(value);
        }
      }

      console.log(this.coaches,'getAllCoachessss');
    }).catch(err=>{
      console.log(err)
    });
  }



  getAllEmployee(responseData){
      console.log(responseData,responseData.length);
      this.registeredCandidates = responseData;
      //this.PGMEMPLANDING = true;
     // this.listCandidates = this.registeredCandidates;

      this.primarySkillEvalCandidates = [];
      this.techUseCaseEvalCandidate = [];
      this.bussUseCaseEvalCandidate = [];

    //console.log(this.registeredCandidates);

    let AllCourses = []

    /* this.registeredCandidates.forEach(item =>{

      if (item.infoDetails.userInfoMstr.pgCourseEmployeeMapping.length != 0 ){

        console.log(item.infoDetails.userInfoMstr.pgCourseEmployeeMapping.length);

        if(!item.infoDetails.pgExperienceLevel){

          item.infoDetails.pgExperienceLevel = {experienceLevel:''}
        }
        if(!item.infoDetails.jobId){

          item.infoDetails.jobId = ''
        }

        item.infoDetails.userInfoMstr.pgCourseEmployeeMapping.forEach(course => {

          AllCourses.push(course)

        })
        this.listCandidates.push(item)
      }

    });*/



      for(var value of this.registeredCandidates){

        if(value.eventDetails.length != 0) {

          if ( value.courseStatus == 'METTL_SCHEDULED' ||
            value.courseStatus == 'COURSE_COMPLETED' ||
            value.courseStatus == 'METTL_REVIEW' ||
            value.courseStatus == 'METTL_APPROVED' ||
            value.courseStatus == 'METTL_REJECTED' ) {
            console.log('value.courseStatus',value.courseStatus)
            this.primarySkillEvalCandidates.push(value);

            this.primarySkillCandidateCount = this.primarySkillEvalCandidates.length;

          }
          else if ( value.courseStatus == 'COACH_ASSIGNED' ||
            value.courseStatus == 'MINI_PG_STARTED'  ||
            value.courseStatus == 'MINI_PG_COMPLETED' ||
            value.courseStatus == 'MINI_PG_COACH_APPROVED' ||
            value.courseStatus == 'MINI_PG_COACH_REJECTED' ) {

            this.techUseCaseEvalCandidate.push(value);
            this.techUseCaseCandidateCount = this.techUseCaseEvalCandidate.length

          }
          else if (value.courseStatus == 'MAIN_PG_COACH_ASSIGNED' ||
            value.courseStatus == 'MAIN_PG_MANAGER_APPROVED' ||
            value.courseStatus == 'MAIN_PG_COMPLETED' ||
            value.courseStatus == 'MAIN_PG_MANAGER_REJECTED' ||
            value.courseStatus == 'MAIN_PG_COACH_REVIEWED') {

            this.bussUseCaseEvalCandidate.push(value);
            this.bussUseCaseCandidateCount = this.bussUseCaseEvalCandidate.length

          } else {
            let noCandidatesRecord = "No Candidates Record found"
          }
        }

      }

      this.filterprimarySkillEvalCandidates = this.primarySkillEvalCandidates;
      this.filtertechUseCaseEvalCandidate = this.techUseCaseEvalCandidate;
      this.filterbussUseCaseEvalCandidate = this.bussUseCaseEvalCandidate;

    this.levels = _.uniqBy(this.registeredCandidates, 'filter.experienceLevel')
    this.city = _.uniqBy(this.registeredCandidates, 'userDetails.infoDetails.userInfoMstr.pgLocation.city');

    this.skills = _.uniq(_.flattenDeep(this.registeredCandidates.map(i =>
      i.filter.skills.map(j => j.pgSkillTrackDtls.skillTrackDtlsName)
    )));

    this.levels = this.levels.filter(function (item, index, array) {
      return item.filter.experienceLevel != null;
    });
    this.city = _.uniq(_.flattenDeep(this.city.map(i =>
      i.userDetails.infoDetails.userInfoMstr.pgLocation.city
    )));
    console.log(this.levels,'levelsss');
    console.log(this.skills,'skillsss');
    console.log(this.city,'city');
    console.log(this.registeredCandidates,'registeredCandidates');

    console.log(this.primarySkillEvalCandidates);
  }


  ngOnDestroy() {
    this.$destroyed.next();
    this.$destroyed.complete();
  }

  getAllRecommendedCourseEmployeeOld(userId,Location, SkillId){
    Promise.all([

      this.AuthService.getRecommendedCourses(userId,''),
      this.AuthService.getAllEmployee(userId,{location:Location, skillId:SkillId})]
    )
      .then(arr => {

        console.log(arr,'Array')
        console.log(arr[1],'All EMPLOYeee Deatailsssss')

        let courseRecommend = arr[0];
        let employeeList = arr[1];
        let listAllEmp = [];
        let recommendEmployee = [];

        let AllCourses = []
        let eventDetails = []
        let allRecommendedCoures = []

        //
        employeeList.forEach(item =>{

          if (item.infoDetails.userInfoMstr.pgCourseEmployeeMapping.length != 0 ){

            console.log(item.infoDetails.userInfoMstr.pgCourseEmployeeMapping.length);

            if(!item.infoDetails.pgExperienceLevel){

              item.infoDetails.pgExperienceLevel = {experienceLevel:''}
            }
            if(!item.infoDetails.jobId){

              item.infoDetails.jobId = ''
            }

            item.infoDetails.userInfoMstr.pgCourseEmployeeMapping.forEach(course => {

              AllCourses.push(course)

            })
            listAllEmp.push(item)
          }

        });

        console.log(AllCourses,"AllCourses");
        console.log(listAllEmp,"listAllEmp");
        console.log(courseRecommend,"courseRecommend");

        Object.keys(courseRecommend).forEach(function (key) {
          for(let emp of listAllEmp) {
            console.log(key.toString(),emp.infoDetails.userInfoMstr.userInfoMstrId.toString(),"recommendEmployee");
            if(key.toString() == emp.infoDetails.userInfoMstr.userInfoMstrId.toString()){
              emp.infoDetails.userInfoMstr.pgCourseDtls = courseRecommend[key]
              recommendEmployee.push(emp)
              console.log(key.toString(),emp.infoDetails.userInfoMstr.userInfoMstrId.toString(),"recommendEmployee");

              courseRecommend[key].forEach(course => {
                allRecommendedCoures.push(course)
              })

            }
             else {
            }
          }
        });


        AllCourses.forEach(allCourse => {

          var usr ;
          usr = listAllEmp.filter(function (item, index, array) {

              return (item.infoDetails.userInfoMstr.userInfoMstrId == allCourse.userInfoMstrId);

            }),
            console.log(allRecommendedCoures,":allRecommendedCoures")
            allCourse.courseDetails = allRecommendedCoures.filter(function (item, index, array) {

              return (item.pgCourseDetails.courseDetailsId == allCourse.courseId);

            })
          allCourse.eventDetails = listAllEmp.filter(function (item, index, array) {


            item.eventDetails.forEach(event => {

              return (item.eventDetails.courseId == allCourse.courseId);

            })
            })
            allCourse.userDetails = usr[0]


        })


        AllCourses.forEach(usr=>{

          usr.userDetails.eventDetails.forEach(evnt => {

          if(  usr.courseId == evnt.courseId){

            usr.eventDetails.push(evnt)
          }

          })

        })


        this.recommendCourseEmployee = _.reverse(_.sortBy(AllCourses, ['updatedDt']));
        this.reservedRecommendedCoursesEmployee = _.reverse(_.sortBy(AllCourses, ['updatedDt']))
        this.PGMEMPLANDING = true;


        console.log(this.recommendCourseEmployee,'this.recommendCourseEmployee')

      }).catch (err => {
        console.log("Error for this :",err)
    })

  }


  getAllRecommendedCourseEmployee(userId,Location, SkillId){
    Promise.all([

      this.AuthService.getRecommendedCourses(userId,''),
      this.AuthService.getAllEmployee(userId,{})]
    )
      .then(arr => {
        console.log(arr[0],'RecommendedCourses')
        console.log(arr[1],'All EMPLOYeee')
        this.employeeRecommendedCourses(arr)
        this.employeeAssessmentCourses(arr)

      }).catch (err => {
        console.log("Error for this :",err)
    })

  }



  /**
   * This is for Recommended Course For Particular Employee
   * **/

  employeeRecommendedCourses(arr){

    let courseRecommend = arr[0];
    let employeeList = arr[1];
    let listAllEmp = [];
    let recommendEmployee = [];

    let employeeRecommendCourse = []

    let AllCourses = []
    let eventDetails = []
    let allRecommendedCoures = []

    //
    employeeList.forEach(item =>{

      if (item.infoDetails.userInfoMstr.pgCourseEmployeeMapping.length != 0 ){

        if(!item.infoDetails.pgExperienceLevel){

          item.infoDetails.pgExperienceLevel = {experienceLevel:null}
        }
        if(!item.infoDetails.jobId){

          item.infoDetails.jobId = null
        }

        item.infoDetails.userInfoMstr.pgCourseEmployeeMapping.forEach(course => {

          AllCourses.push(course)

        })
        listAllEmp.push(item)
      }

    });

    console.log(AllCourses,"AllCourses");
    console.log(listAllEmp,"listAllEmp");
    console.log(courseRecommend,"courseRecommend");

    Object.keys(courseRecommend).forEach(function (key) {
      for(let emp of listAllEmp) {
        if(key.toString() == emp.infoDetails.userInfoMstr.userInfoMstrId.toString()){

          let rc =[]

          for(var courseStatus of courseRecommend[key]){

            for (var mapCourse of emp.infoDetails.userInfoMstr.pgCourseEmployeeMapping){

              if(mapCourse.courseId == courseStatus.pgCourseDetails.courseDetailsId){

                if(mapCourse.courseStatus == 'COURSE_ASSIGNED' || mapCourse.courseStatus == 'COURSE_COACH_ASSIGNED' || mapCourse.courseStatus == 'COURSE_STARTED' || mapCourse.courseStatus == 'COURSE_COMPLETED' ) {
                  mapCourse['type'] = 'course';
                  rc.push(Object.assign({}, courseStatus, mapCourse))
                }

              }

            }

          }

          for (var Assessment of emp.infoDetails.userInfoMstr.pgEmployeeAssessmentMapping){

            if(Assessment.assessmentStatus == 'ASSESSMENT_ASSIGNED'){
            Assessment['type'] = 'assessment'
              rc.push(Assessment);
           }

          }


          employeeRecommendCourse.push({userDetails:emp.infoDetails,recommendedCourse:rc,fullName:emp.infoDetails.fullName})

          recommendEmployee.push(emp)

          console.log(key.toString(),emp.infoDetails.userInfoMstr.userInfoMstrId.toString(),"recommendEmployee");

          courseRecommend[key].forEach(course => {
            allRecommendedCoures.push(course)
          })

        }
        else {
        }
      }
    });

    console.log(employeeRecommendCourse,"employeeRecommendCourse");

    this.recommendCourseEmployee = employeeRecommendCourse
    this.reservedRecommendedCoursesEmployee = employeeRecommendCourse;
    this.PGMEMPLANDING = true;


  }


  employeeAssessmentCourses(arr){

    let courseRecommend = arr[0];
    let employeeList = arr[1];
    let listAllEmp = [];
    let recommendEmployee = [];

    let AllCourses = []
    let eventDetails = []
    let allRecommendedCoures = []

    //
    employeeList.forEach(item =>{

      if (item.infoDetails.userInfoMstr.pgCourseEmployeeMapping.length != 0 ){

        console.log(item.infoDetails.userInfoMstr.pgCourseEmployeeMapping.length);

        if(!item.infoDetails.pgExperienceLevel){

          item.infoDetails.pgExperienceLevel = {experienceLevel:''}
        }
        if(!item.infoDetails.jobId){

          item.infoDetails.jobId = ''
        }

        item.infoDetails.userInfoMstr.pgCourseEmployeeMapping.forEach(course => {

          AllCourses.push(course)

        })
        listAllEmp.push(item)
      }

    });

    console.log(AllCourses,"AllCourses");
    console.log(listAllEmp,"listAllEmp");
    console.log(courseRecommend,"courseRecommend");

    Object.keys(courseRecommend).forEach(function (key) {
      for(let emp of listAllEmp) {
     //   console.log(key.toString(),emp.infoDetails.userInfoMstr.userInfoMstrId.toString(),"recommendEmployee");
        if(key.toString() == emp.infoDetails.userInfoMstr.userInfoMstrId.toString()){
          emp.infoDetails.userInfoMstr.pgCourseDtls = courseRecommend[key]
          recommendEmployee.push(emp)
        //  console.log(key.toString(),emp.infoDetails.userInfoMstr.userInfoMstrId.toString(),"recommendEmployee");

          courseRecommend[key].forEach(course => {
            allRecommendedCoures.push(course)
          })

        }
        else {
        }
      }
    });


    AllCourses.forEach(allCourse => {

      var usr ;
      usr = listAllEmp.filter(function (item, index, array) {

        return (item.infoDetails.userInfoMstr.userInfoMstrId == allCourse.userInfoMstrId);

      }),
      //  console.log(allRecommendedCoures,":allRecommendedCoures")
      allCourse.courseDetails = allRecommendedCoures.filter(function (item, index, array) {

        return (item.pgCourseDetails.courseDetailsId == allCourse.courseId);

      })
      allCourse.eventDetails = listAllEmp.filter(function (item, index, array) {


        item.eventDetails.forEach(event => {

          return (item.eventDetails.courseId == allCourse.courseId);

        })
      })
      allCourse.userDetails = usr[0]
      allCourse.fullName = usr[0].infoDetails.fullName
      allCourse.filter = {experienceLevel:usr[0].infoDetails.pgExperienceLevel.experienceLevel,
        jobId:usr[0].infoDetails.jobId,skills:usr[0].infoDetails.userInfoMstr.pgUserSkillMapping,
      skillName:_.uniq(_.flattenDeep(
        usr[0].infoDetails.userInfoMstr.pgUserSkillMapping.map(j => j.pgSkillTrackDtls.skillTrackDtlsName)

      ))}


    })


    AllCourses.forEach(usr=>{

      usr.userDetails.eventDetails.forEach(evnt => {

        if(  usr.courseId == evnt.courseId){

          usr.eventDetails.push(evnt)
        }

      })

    })


   var employeeRecommendCourse = _.reverse(_.sortBy(AllCourses, ['updatedDt']));



    console.log(employeeRecommendCourse,"employeeAssessmentCourses");

    this.getAllEmployee(employeeRecommendCourse)
  }






  goToCandidateDetails($event){
    console.log($event)

    this.navBarService.setCourse($event.course);
   // this.router.navigate(['pgm/employeeEventDetails',$event.userId,$event.courseId]);
    this.router.navigate(['pgm/employee',$event.userId]);
  }
  goToEventDetails($event){
    this.router.navigate(['pgm/employee',$event]);
  }

  goToassignCoach(evnt){

    console.log(evnt)
    this.router.navigate(['pgm/assignCoach', evnt.userId, evnt.courseId]);

  }

  course(userlist){

    this.recommendCourseEmployee = userlist
    this.reservedRecommendedCoursesEmployee = userlist;
    console.log(this.recommendCourseEmployee);
  }


  recommend() {

    this.recommendedCol = !this.recommendedCol;
  }
  redirect() {
    this.router.navigate(['pgm/exportEmployee']);
  }

  selectedRecommend(assess){

    this.isAssessment = assess;
    this.getAllSkills()
    document.getElementById('openSkillModal').click();

  }

  getAllSkills(){


    this.AuthService.getAllSkillTrackMstr().then(resp => {
      console.log(resp,'getAllSkills');
      this.Skills = resp.pgSkillTrackMstr
    }).catch(err => {
      console.log(err);
    })
  }

  skillSelect (skillVal){

    console.log(skillVal)
    document.getElementById('closeModal').click()
    if(this.isAssessment == 'Course') {
      this.router.navigate(['pgm/employee/recommendedCourse', skillVal])
    } else if(this.isAssessment == 'Assessment') {
      this.router.navigate(['pgm/employee/recommendedAssessment', skillVal])
    } else {

    }
  }


  callMe(){
    this.userIcon = 'logout';
    console.log('callme');

  }

  Initials(cString) {
    if(cString) {
      return cString.replace(/\W*(\w)\w*/g, '$1').toUpperCase()
    }
  }

  getSubstring(text){
    if(text) {
      return text.substring(0, 3);
    }
  }


  getTrim(text){

    return text.substring(6);

  }


  scheduleMettl($event){
    //this.router.navigate(['coach/candidateDetails',$event]);
    this.router.navigate(['pgm/employee',$event]);

  }



  All(){
    this.filterActive = 'all';

    this.registeredCandidates = this.listCandidates;
  }

  New(){
    this.filterActive = 'new';

    this.registeredCandidates = this.listCandidates.filter(function(item, index, array){

      return (item.infoDetails.userInfoMstr.status == 'COACH_ASSIGNED'
        || item.infoDetails.userInfoMstr.status == 'MINI_PG_COACH_ASSIGNED'
        || item.infoDetails.userInfoMstr.status == 'MAIN_PG_COACH_ASSIGNED'
        || item.infoDetails.userInfoMstr.status == 'METTL_APPROVED');

    });
  }

  inProgress(){
    this.filterActive = 'inProgress';

    this.registeredCandidates = this.listCandidates.filter(function(item, index, array){

      return (item.infoDetails.userInfoMstr.status == 'MINI_PG_STARTED'
        || item.infoDetails.userInfoMstr.status == 'MAIN_PG_STARTED'
        || item.infoDetails.userInfoMstr.status == 'COACH_ASSIGNED'
        || item.infoDetails.userInfoMstr.status == 'MINI_PG_COACH_ASSIGNED'
        || item.infoDetails.userInfoMstr.status == 'MAIN_PG_COACH_ASSIGNED' );

    });
  }

  coachEvaluation(){
    this.filterActive = 'coachEvaluation';

    this.registeredCandidates = this.listCandidates.filter(function(item, index, array){

      return (item.infoDetails.userInfoMstr.status == 'MINI_PG_COMPLETED'
        || item.infoDetails.userInfoMstr.status == 'MAIN_PG_COMPLETED'
        || item.infoDetails.userInfoMstr.status == 'MAIN_PG_COMPELTED' || item.infoDetails.userInfoMstr.status == 'MAIN_PG_COMPELTED');

    });

  }

  completedTestnEvaluation() {
    this.filterActive = 'completed';

    this.registeredCandidates = this.listCandidates.filter(function (item, index, array) {

      return (item.infoDetails.userInfoMstr.status == 'MINI_PG_COACH_APPROVED'
        || item.infoDetails.userInfoMstr.status == 'MAIN_PG_COACH_REVIEWED'
        || item.infoDetails.userInfoMstr.status == 'MAIN_PG_COMPLETED'
        || item.infoDetails.userInfoMstr.status == 'MAIN_PG_STARTED'
        || item.infoDetails.userInfoMstr.status == 'MAIN_PG_COACH_ASSIGNED'
        || item.infoDetails.userInfoMstr.status == 'MAIN_PG_MANAGER_APPROVED'
        || item.infoDetails.userInfoMstr.status == 'MAIN_PG_MANAGER_REJECTED');

    });
  }

  filterBusiness(filterId){
    console.log("filterbusiness",filterId);
    if(filterId == 'all' ){
      this.bussUseCaseEvalCandidate = this.filterbussUseCaseEvalCandidate;
    }
    else if(filterId == 'inProgress'){
      this.bussUseCaseEvalCandidate = this.filterbussUseCaseEvalCandidate.filter(function(item, index, array){
        return (item.infoDetails.userInfoMstr.status == 'MAIN_PG_STARTED' || item.infoDetails.userInfoMstr.status == 'MAIN_PG_COMPLETED');
      });
    }
    else if(filterId == 'evaluation'){
      this.bussUseCaseEvalCandidate = this.filterbussUseCaseEvalCandidate.filter(function(item, index, array){
        return (item.infoDetails.userInfoMstr.status == 'MAIN_PG_COMPLETED' || item.infoDetails.userInfoMstr.status == 'MAIN_PG_COACH_REVIEWED');
      });
    }
    else if(filterId == 'completed'){
      this.bussUseCaseEvalCandidate = this.filterbussUseCaseEvalCandidate.filter(function(item, index, array){
        return (item.infoDetails.userInfoMstr.status == 'MAIN_PG_MANAGER_APPROVED' || item.infoDetails.userInfoMstr.status == 'MAIN_PG_MANAGER_REJECTED');
      });
    }
  }

  filterTechnical(filterId){
    console.log("filterTechnical",filterId);
    if(filterId == 'all' ){
      this.techUseCaseEvalCandidate = this.filtertechUseCaseEvalCandidate;
    }
    else if(filterId == 'inProgress'){
      this.techUseCaseEvalCandidate = this.filtertechUseCaseEvalCandidate.filter(function(item, index, array){
        return (item.infoDetails.userInfoMstr.status == 'MINI_PG_STARTED' || item.infoDetails.userInfoMstr.status == 'MINI_PG_COMPLETED');
      });
    }
    else if(filterId == 'evaluation'){
      this.techUseCaseEvalCandidate = this.filtertechUseCaseEvalCandidate.filter(function(item, index, array){
        return (item.infoDetails.userInfoMstr.status == 'MINI_PG_COMPLETED');
      });
    }
    else if(filterId == 'completed'){
      this.techUseCaseEvalCandidate = this.filtertechUseCaseEvalCandidate.filter(function(item, index, array){
        return (item.infoDetails.userInfoMstr.status == 'MINI_PG_COACH_APPROVED' || item.infoDetails.userInfoMstr.status == 'MINI_PG_COACH_REJECTED');
      });
    }


  }

  filterPrimary(filterId){
    console.log("filterPrimary",filterId);
    if(filterId == 'all' ){
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates;
    }
    else if(filterId == 'notScheduled'){
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function(item, index, array){
        return (item.infoDetails.userInfoMstr.status == 'METTL_COACH_ASSIGNED' );
      });
    }
    else if(filterId == 'inProgress'){
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function(item, index, array){
        return (item.infoDetails.userInfoMstr.status == 'METTL_SCHEDULED' );
      });
    }
    else if(filterId == 'evaluation'){
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function(item, index, array){
        return (item.infoDetails.userInfoMstr.status == 'METTL_REVIEW' );
      });
    }
    else if(filterId == 'completed'){
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function(item, index, array){
        return (item.infoDetails.userInfoMstr.status == 'METTL_APPROVED' || item.infoDetails.userInfoMstr.status == 'METTL_REJECTED' );
      });
    }

  }

  updateCandidateStatus(status, id){

    console.log("updateCandidateStatus",status, id);
    this.AuthService.candidateStatusUpdate({candidateStatus:status,fromId:this.empData.userInfoMstrId,toId:id}).then( responseData => {
      console.log(responseData)
      var responseDataCheck = responseData
      // var resData = responseData['data']

      if(responseData['status'] == 'success'){

        if (status == 'METTL_APPROVED') {
          this.toastr.success("Candidate PRIMARY SKILL EVALUATION APPROVED ");

        }
        else if(status == 'METTL_REJECTED'){
          this.toastr.success("Candidate PRIMARY SKILL EVALUATION REJECTED");
        }

      }
      else {
        console.log(responseData,'Else case Canditates Approval ')
      }

    }).catch(err=>{
      console.log(err)
    });
  }

  logout(){
    console.log("logout");
    this.localStorageService.clearAll();
    localStorage.clear();
    this.router.navigate(['']);

  }

}
