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 _ from 'lodash';
import { CoachCandidateEvaluationService } from "../../../coach/shared/service/coach-candidate-evaluation.service";
import { environment } from '../../../../environments/environment.dev';
/*import any = jasmine.any;*/

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


  userIcon = '';
  calledclass = '';
  Id = 95;
  public registeredCandidates;
  public listCandidates;
  Location = "Chennai";
  allLocations = [];
  SkillId = 1;
  filterActive = 'all';
  PGMCANTILANDING = false;
  name: string;
  loactionId: any;
  fullName: string;
  skillFilterId: any;
  courseFilter: any = { infoDetails: { fullName: '' } };
  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any
  };

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

  primaryFilter = [
    {
      "id": "all",
      "name": "All"
    },
    {
      "id": "inProgress",
      "name": "In Progress"
    },
    {
      "id": "coachAssign",
      "name": "Coach Assign"
    },
    {
      "id": "notScheduled",
      "name": "Schedule"
    },
    {
      "id": "evaluation",
      "name": "Evaluation"
    },
    {
      "id": "completed",
      "name": "Completed"
    }
  ];
  filter = [
    {
      "id": "all",
      "name": "All"
    },
    {
      "id": "inProgress",
      "name": "In Progress"
    },
    {
      "id": "coachAssign",
      "name": "Coach Assign"
    },
    {
      "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;

  public levels;
  public city;
  public jobId;
  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(0);
    var empData;
    this.loactionId = [];
    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.getAllCandidate(1, [1, 2]);
      //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.getAllLocation();
      this.loactionId.push(this.empData.location);
      this.skillFilterId = [...this.empData.skills];
      this.getAllCandidate(this.loactionId, this.skillFilterId);
    }
  }

  ngOnInit() { }

  newList(){
    this.router.navigate(['pgm/candidateList'])
  }

  getAllLocation() {
    this.AuthService.getAllLocations().then(resp => {
      this.allLocations = resp.pgLocationList;
      this.allLocations.forEach(element => {
        element.selectedCity = false;
      });
      this.checkBoxCheked(this.empData.location);
    }).catch(err => {
      console.log(err);
    });
  }
  checkBoxCheked(id) {
    if (this.allLocations) {
      this.allLocations.forEach(element => {
        if (element.locationId === id && element.selectedCity === false) {
          element.selectedCity = true;
        } else if (element.locationId === id && element.selectedCity === true) {
          element.selectedCity = false;
        }
      });
    }
  }
  searchCity(id, event) {
    this.checkBoxCheked(id);
    // this.loactionId.push(id);
    this.allLocations.forEach(element => {
      if (element.locationId === id && element.selectedCity === true) {
        this.loactionId.push(id);
        console.log(this.loactionId);
      } else if (element.locationId === id && element.selectedCity === false) {
        const index = this.loactionId.indexOf(id);
        if (index !== -1) {
          this.loactionId.splice(index, 1);
          console.log(this.loactionId);
        }
      }
    });
    // const selectedCity = [];
    // this.locationFilters.forEach((element, i) => {
    //   const cityData = { city: element };
    //   selectedCity.push(cityData);
    // });
    // const result1 = this.allLocations;
    // const result2 = selectedCity;

    // const result3 = _.differenceWith(result1, result2, function (o1, o2) {
    //   return o1['city'] !== o2['city'];
    // });
    // console.log(result3);
    this.getAllCandidate(this.loactionId, this.skillFilterId);
    this.toggleFilter(id, this.locationFilters);
  }

  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;

    /*Filter On Primary Evaluation*/
    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.infoDetails.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.infoDetails.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.infoDetails.pgUserSkillDtlsName).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.infoDetails.city) : true;
    // });

    /*Filter on Technical Evaluation*/
    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.infoDetails.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.infoDetails.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.infoDetails.pgUserSkillDtlsName).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.infoDetails.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.infoDetails.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.infoDetails.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.infoDetails.pgUserSkillDtlsName).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.infoDetails.city) : true;
    // });
  }
  getUserCurrentLocation() {
    let 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.getAllCandidate([this.empData.location], this.empData.skills);
    if (this.allLocations.length > 0) {
      this.allLocations.forEach(element => {
        element.selectedCity = false;
      });
      this.checkBoxCheked(this.empData.location);
    }

  }

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



  getAllCandidate(Location, SkillId) {
    this.PGMCANTILANDING = false;
    console.log(Location, SkillId, "All Req Body Dataaaaaaaa");
    this.primarySkillEvalCandidates = [];
    this.techUseCaseEvalCandidate = [];
    this.bussUseCaseEvalCandidate = [];
    this.filterprimarySkillEvalCandidates = [];
    this.filtertechUseCaseEvalCandidate = [];
    this.filterbussUseCaseEvalCandidate = [];
    this.registeredCandidates = [];
    this.AuthService.getAllCandidate({ location: Location, skillId: SkillId }).then(responseData => {

      console.log(responseData, responseData.length);

      this.registeredCandidates = responseData;
      this.PGMCANTILANDING = true;
      this.listCandidates = this.registeredCandidates;

      for (var value of this.registeredCandidates) {

        if (value.eventDetails) {
          // if (value.eventDetails.length != 0) {
            if (value.infoDetails.status == 'METTL_SCHEDULED' ||
              value.infoDetails.status == 'TA_APPROVED' ||
              value.infoDetails.status == 'METTL_REVIEW' ||
              value.infoDetails.status == 'METTL_COACH_ASSIGNED' ||
              value.infoDetails.status == 'METTL_REJECTED') {


              if (value.infoDetails.status == 'TA_APPROVED') {
                value.infoDetails.status
              }
              console.log('value.infoDetails.status', value.infoDetails.status)

              this.primarySkillEvalCandidates.push(value);

              this.primarySkillCandidateCount = this.primarySkillEvalCandidates.length;

            }

            else if (value.infoDetails.status == 'COACH_ASSIGNED' ||
              value.infoDetails.status == 'METTL_APPROVED' ||
              value.infoDetails.status == 'MINI_PG_STARTED' ||
              value.infoDetails.status == 'MINI_PG_COMPLETED' ||
              value.infoDetails.status == 'MINI_PG_COACH_REJECTED') {


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

            }

            else if (value.infoDetails.status == 'MAIN_PG_COACH_ASSIGNED' ||
              value.infoDetails.status == 'MAIN_PG_MANAGER_APPROVED' ||
              value.infoDetails.status == 'MAIN_PG_COMPLETED' ||
              value.infoDetails.status == 'MAIN_PG_MANAGER_REJECTED' ||
              value.infoDetails.status == 'MINI_PG_COACH_APPROVED' ||
              value.infoDetails.status == '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, 'infoDetails.experienceLevel')
      this.jobId = _.uniqBy(this.registeredCandidates, 'infoDetails.jobId')
      this.city = this.allLocations;
      this.skills = _.uniq(_.flattenDeep(this.registeredCandidates.map(i =>

        i.infoDetails.pgUserSkillDtlsName.map(j => j)

      )));
      this.levels = _.uniq(_.flattenDeep(this.levels.map(i =>

        i.infoDetails.experienceLevel

      )));
      this.jobId = _.uniq(_.flattenDeep(this.jobId.map(i =>

        i.infoDetails.jobId

      )));
      // this.city = _.uniq(_.flattenDeep(this.city.map(i =>

      //   i.infoDetails.city

      // )));
      /* this.levels = this.levels.filter(function (item, index, array) {
         return item.experienceLevel != null;
       })*/
      console.log(this.levels, 'levelsss');
      console.log(this.skills, 'skillsss');
      console.log(this.jobId, 'jobId');
      console.log(this.city, 'city');

      console.log(this.primarySkillEvalCandidates);
      console.log(this.techUseCaseEvalCandidate);
      console.log(this.bussUseCaseEvalCandidate);
      this.applyFilters();
    }).catch(err => {
      console.log(err);
    });

  }

  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);

  }


  goToCandidateDetails($event) {

    //  window.location.href = window.location.origin+'/'+'pgCandidatedetails'+'?'+'uuid='+$event

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

  }

  goToEventDetails($event) {

    //window.location.href = window.location.origin+'/'+'pgCandidatedetails'+'?'+'uuid='+$event

    this.router.navigate(['pgm/candidateEventDetails', $event]);

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

  redirect() {
    this.router.navigate(['pgm/exports']);
  }


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

    this.registeredCandidates = this.listCandidates;
  }

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

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


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


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

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


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


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

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


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


    });

  }

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

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


      return (item.infoDetails.status == 'MINI_PG_COACH_APPROVED'
        || item.infoDetails.status == 'MAIN_PG_COACH_REVIEWED'
        || item.infoDetails.status == 'MAIN_PG_COMPLETED'
        || item.infoDetails.status == 'MAIN_PG_STARTED'
        || item.infoDetails.status == 'MAIN_PG_COACH_ASSIGNED'
        || item.infoDetails.status == 'MAIN_PG_MANAGER_APPROVED'
        || item.infoDetails.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.status == 'MAIN_PG_STARTED' || item.infoDetails.status == 'MAIN_PG_COMPLETED');

      });
    }
    else if (filterId == 'coachAssign') {
      this.bussUseCaseEvalCandidate = this.filterbussUseCaseEvalCandidate.filter(function (item, index, array) {

        return (item.infoDetails.status == 'MINI_PG_COACH_APPROVED');

      });
    }
    else if (filterId == 'evaluation') {
      this.bussUseCaseEvalCandidate = this.filterbussUseCaseEvalCandidate.filter(function (item, index, array) {

        return (item.infoDetails.status == 'MAIN_PG_COMPLETED' || item.infoDetails.status == 'MAIN_PG_COACH_REVIEWED');

      });
    }
    else if (filterId == 'completed') {
      this.bussUseCaseEvalCandidate = this.filterbussUseCaseEvalCandidate.filter(function (item, index, array) {

        return (item.infoDetails.status == 'MAIN_PG_MANAGER_APPROVED' || item.infoDetails.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.status == 'MINI_PG_STARTED' || item.infoDetails.status == 'MINI_PG_COMPLETED');

      });
    }
    else if (filterId == 'coachAssign') {
      this.techUseCaseEvalCandidate = this.filtertechUseCaseEvalCandidate.filter(function (item, index, array) {

        return (item.infoDetails.status == 'METTL_APPROVED');

      });
    }
    else if (filterId == 'evaluation') {
      this.techUseCaseEvalCandidate = this.filtertechUseCaseEvalCandidate.filter(function (item, index, array) {

        return (item.infoDetails.status == 'MINI_PG_COMPLETED');

      });
    }
    else if (filterId == 'completed') {
      this.techUseCaseEvalCandidate = this.filtertechUseCaseEvalCandidate.filter(function (item, index, array) {

        return (item.infoDetails.status == 'MINI_PG_COACH_APPROVED' || item.infoDetails.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.status == 'METTL_COACH_ASSIGNED');

      });
    }
    else if (filterId == 'inProgress') {
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function (item, index, array) {

        return (item.infoDetails.status == 'METTL_SCHEDULED');

      });
    }
    else if (filterId == 'coachAssign') {
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function (item, index, array) {

        return (item.infoDetails.status == 'TA_APPROVED');

      });
    }
    else if (filterId == 'evaluation') {
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function (item, index, array) {

        return (item.infoDetails.status == 'METTL_REVIEW');

      });
    }
    else if (filterId == 'completed') {
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function (item, index, array) {

        return (item.infoDetails.status == 'METTL_APPROVED' || item.infoDetails.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(['']);

  }

}
