import {Component, OnInit, OnDestroy, Input} from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Subject } from 'rxjs/Subject';
import { EmployeeHttpService } from 'app/services/employee/employee-http.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import _ from "lodash";

import {error, log} from "util";
import {forEach} from "@angular/router/src/utils/collection";
import {Router,ActivatedRoute} from "@angular/router";
import {IMyDrpOptions} from "mydaterangepicker";
import { environment } from '../../../environments/environment.dev';

const img_path_prefix = environment.imageUrl+'/assets/img/employee/wizard/';
const img_path_suffix = '.png';

@Component({
  selector: 'app-pgm-recommended-assessment',
  templateUrl: './pgm-recommended-assessment.component.html',
  styleUrls: ['./pgm-recommended-assessment.component.scss']
})
export class PgmRecommendedAssessmentComponent implements OnInit {

  @Input() PrimarySkill: any;

  myDateRangePickerOptions: IMyDrpOptions = {
    // other options...
    dateFormat: 'dd.mm.yyyy',
  };
  public model: any = 'Due date';

  private placeholder: string = 'Select Due date';
  private $destroyed = new Subject();
  selectedSkillValues: any;
  selectedSkillDtls: any;
  selectedAssessment: any;
  checkImg = img_path_prefix + 'check' + img_path_suffix;
  private currentUser: any;
  courses: any = [];
  recommendedCourses: any = [];
  assessments = [];
  selectedCoursesDetails: any = [];
  selectedCourses: any = [];
  selectedEmployeeDetails: any = [];
  selectedEmployee: any = [];
  coaches: any = [];
  selectCoach = [];
  selectedCoursesEmployeeDetails: any = [];
  courseEmployeLists: any = [];
  empLists = [];
  Skills = [];
  UserID: any
  fullName: any;
  name: any
  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any
  };
 busiUsecaseId: any
 coachId: any
  dueDate: any
 skillTrackMstrId: any
 techUsecaseId: any
  assessmentDtlsId: any
  userInfoMstrId = []
  primarySkillID : any
  courseFilter: any = {courseName: ''};
  statusOf = true;
  // statusOf = 'afterRecommended';
  skilltrackResponse: Skilltrackdetails [];
  selectedTest = '';
  technicalDesc : any;
  bussniessDesc : any;
  technicalAllUC: any;
  bussniessAllUC : any;
  techMore = false
  bussMore = false

  useCaseFilter: any = { usecaseTitle : '' };
  assessment = [
    {name: 'Primary Skill', selected: false},
    {name: 'Technical UseCase', selected: false},
    {name: 'Busniess UseCase', selected: false},
  ]


  constructor(private employeeHttpService: EmployeeHttpService,
              private localStorageService: LocalStorageService,
              private AuthService: AuthService,
              private router: Router,
              private route: ActivatedRoute,
              private toastr: ToastsManager,) {

    this.route.params.subscribe(params =>
      this.UserID = params['id']
  )

    if (!this.UserID || this.UserID == null) {
      this.router.navigate(['pgm/landing/employee']);
    }
    else {

      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.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.PrimarySkill = this.UserID
    this.onchangeSkillMstr(this.PrimarySkill)
    this.AuthService.getAllSkillTrackMstr().then(resp => {
      console.log(resp, 'getAllSkills');
      this.Skills = resp.pgSkillTrackMstr
    }).catch(err => {
      console.log(err);
    })


    this.getAssessmentDetails(this.PrimarySkill)

    this.AuthService.getAllSkill().then(skilltrackdetails => {
      console.log(skilltrackdetails, 'getAllSkills');

      var customSkill = []
      var skills = _.uniqBy(skilltrackdetails.pgSkillTrackDtlsList,'pgSkillTrackMstr.skillTrackName')
      var masterSkills = _.uniqBy(_.flattenDeep(skills.map(i => i.pgSkillTrackMstr)))
      masterSkills.forEach(usrSkills => {
        var dtlsSkill = skilltrackdetails.pgSkillTrackDtlsList.filter(item => item.pgSkillTrackMstr.skillTrackName == usrSkills.skillTrackName)
        var skillTrackDtlsName = _.uniqBy(_.flattenDeep(dtlsSkill.filter(i => {return {id : i.skillTrackDtlsId, name : i.skillTrackDtlsName}})))
        customSkill.push({skillMaster:usrSkills,skillTrackDtls :dtlsSkill,skillTrackDtlsName:skillTrackDtlsName});
      });
       console.log(customSkill);
      this.skilltrackResponse = customSkill;



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

  }



  ngOnInit() {



  }


  getCoachesforCandidate(SkillId){
    this.coaches = []
    this.AuthService.getAllCoachesforCandidate({location:1,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)
    });
  }

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

  onSelectionChange(emp, event,value) {
    console.log(emp, 'selected Employeeee', value);
    console.log(event.target.checked);
    if (event.target.checked) {
      this.selectedEmployee = Object.assign({}, this.selectedEmployee, emp);

      this.selectedEmployeeDetails.push(emp);
      this.userInfoMstrId.push(value)

    } else {
      const index = this.userInfoMstrId.indexOf(value);
      this.userInfoMstrId.splice(index, 1);

      const empindex = this.selectedEmployeeDetails.indexOf(value);
      this.selectedEmployeeDetails.splice(empindex, 1);
       }
    console.log(this.userInfoMstrId);
    console.log(this.selectedEmployeeDetails, 'selected Employeeee');
  }


  keySearch(param) {

    console.log(param, 'param')

    if (param) {
      this.employeeHttpService.searchEmployee({filterParam: param}).takeUntil(this.$destroyed)
        .subscribe(data => {

          console.log(data, 'SearchEmployee');

          this.empLists = data.userList
        })
    } else {
      this.empLists = []
    }
  }


  selectCourseEmp(course: any = {}) {

    console.log(course);
    if (course.selected) {
      course.selected = false;
      this.courseEmployeLists = this.courseEmployeLists.filter(item => item.courseDetailsId !== course.courseDetailsId);
    } else {
      course.selected = true;
      this.courseEmployeLists.push(course)
    }

    console.log(this.courseEmployeLists, 'courseEmployeLists')
  }

  selectCourse(course: any = {}) {
    if (course.selected) {
      course.selected = false;
      this.selectedCourses = this.selectedCourses.filter(item => item.courseId !== course.courseDetailsId);
    } else {
      course.selected = true;
      this.selectedCourses.push({'courseId': course.courseDetailsId, "assessment": course.assessment});
      this.selectedCoursesDetails.push(course)
    }
    console.log(this.selectedCourses, 'selectedCourses');
    console.log(this.selectedCoursesDetails, 'selectedCoursesDetails');
    //   this.employeeWizardService.setCourses(this.selectedCourses);
  }


  closeModal() {
    console.log('closeModal');
    document.getElementById('closeAssignCoachModal').click();
  }


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

  onSelectCoach(coach,coachId) {
    this.selectCoach[0] = coach;
    this.coachId = coachId;



    console.log(this.selectCoach, 'selctedCoach')
    console.log(this.coachId, 'coachId');
  }


  getAssessmentDetails(skillId){
    this.AuthService.getAssessmentDetails(skillId).then(resp => {
      console.log(JSON.parse(resp), 'getAssessment=================================>');
      resp = JSON.parse(resp)
      this.assessments = resp.pgAssessmentDtls;
    }).catch(err => {
      console.log(err);
    })
  }


  onchangeSkillMstr(data){

    console.log(data)
    this.primarySkillID = data
    this.skillTrackMstrId = data
    this.getAssessmentDetails(this.primarySkillID)
    this.getAllTechnicalUseCase(this.primarySkillID)
    this.getAllBussniessUseCase(this.primarySkillID)
    this.getAllSkillTrackDetailsBy(this.primarySkillID)
    this.getCoachesforCandidate([this.primarySkillID]);

  }
  onSkillMaster(e,data){
    console.log(e)
    console.log(data,'selected skill details')
    this.selectedSkillValues = data.assessmentId;
    this.selectedAssessment = data;
    this.assessmentDtlsId = data.assessmentId;
  }

  selectAssessment(tileIndex: number,tileName: string) {
    const category = this.assessment;
    if (category[tileIndex].selected) {
      category[tileIndex].selected = false;
      this.selectedTest = '';
      // this.selectedCategories = this.selectedCategories.filter(item => item.id !== category.id);
    } else {
      category[tileIndex].selected = true;
      this.selectedTest = tileName;
    }

    console.log(this.assessment,'Selectedassessment');
  }

  getAllTechnicalUseCase(id){
    this.AuthService.getAllTechnicalUseCaseList(id).then(resp => {
      console.log(resp, 'getAllTechnicalUseCaseList');

      this.technicalDesc = _.orderBy(resp.useCaseList,['id'],[ 'desc'])
      this.technicalAllUC = this.technicalDesc
      console.log(this.technicalDesc);

    }).catch(err => {
      console.log(err);
    })
  }
  getAllBussniessUseCase(id) {
    this.AuthService.getAllBussniessUseCaseList(id).then(resp => {
      console.log(resp, 'getAllBussniessUseCaseList');
      this.bussniessDesc = _.orderBy(resp.useCaseList,['id'],[ 'desc'])
      this.bussniessAllUC = this.bussniessDesc
      console.log(this.bussniessDesc);

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

  }

  getAllSkillTrackDetailsBy(id) {
    this.AuthService.getAllSkillTrackDetailsBy(id).then(resp => {
      console.log(resp.pgSkillTrackDtlsList, 'getAllSkillTrackDetailsBy');
      this.selectedSkillDtls = resp.pgSkillTrackDtlsList
      console.log(this.selectedSkillDtls);

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

  }
  selectUsecase(evnt) {
    console.log(evnt,'selectTechUsecase');
    if(evnt.useCase == 'technical') {
      let selectedUC = this.technicalDesc[evnt.index]
      this.technicalDesc = []
      this.technicalDesc.push(selectedUC);
      this.techMore = true
      this.techUsecaseId = evnt.useCaseId
    }
    else if(evnt.useCase == 'bussiness'){
      let selectedUC = this.bussniessDesc[evnt.index]
      this.bussniessDesc = []
      this.bussniessDesc.push(selectedUC);
      this.bussMore = true
      this.busiUsecaseId = evnt.useCaseId
    }
    else {

    }
  }


  changeUC(uc) {
    if (uc == 'tech') {
      this.technicalDesc = this.technicalAllUC;
      this.techMore = false;
    }
    else if (uc == 'buss') {
      this.bussniessDesc = this.bussniessAllUC;
      this.bussMore = false;
    } else {
    }
  }

  cancel() {

    this.router.navigate( ['pgm/landing/employee']);

  }

  done() {

    if(this.assessment[0].selected || this.assessment[1].selected || this.assessment[2].selected ){

      this.statusOf = false

    }
    else {
      this.toastr.error('Select any one Assessments')
    }

  }

  cancelFirst() {
    this.statusOf = true
  }

  onSubmit() {

    if(this.userInfoMstrId.length == 0 ){
      this.toastr.error('Select any one Employee')
    } else {

      let reqJson = {}

      console.log(this.assessmentDtlsId);
      console.log(this.busiUsecaseId);
      console.log(this.techUsecaseId);
      console.log(this.coachId);
      console.log(this.skillTrackMstrId);
      console.log(this.userInfoMstrId);
      console.log(this.dueDate);

     /* if(this.assessmentDtlsId){
        reqJson['assessmentDtlsId'] = this.assessmentDtlsId;
      }if(this.busiUsecaseId){
        reqJson['busiUsecaseId'] = this.busiUsecaseId;
      }if(this.techUsecaseId){
        reqJson['techUsecaseId'] = this.techUsecaseId;
      }
      reqJson['coachId'] = this.coachId
      reqJson['skillTrackMstrId'] = this.skillTrackMstrId
      reqJson['userInfoMstrId'] = this.userInfoMstrId
      reqJson['dueDate'] = this.dueDate;*/

      let reqJSON = {
        selfAssessmentBean: [
        {
          businessAssessmentId: [this.busiUsecaseId],
          courseId: [],
          primaryAssessmentId: [this.assessmentDtlsId],
          skillTrackMstrId: this.skillTrackMstrId,
          technicalAssessmentId: [this.techUsecaseId]
        }
      ],
        userInfoMstrId: this.userInfoMstrId,
        mandetory: true
    }

    /*NEW Self Assessment*/
    this.AuthService.selfAssessment(reqJSON).then(resp => {
        console.log(resp, 'selfAssessment');
        this.toastr.success(resp.successMessage);
        this.router.navigate(['pgm/landing/employee']);
      }).catch(err => {
        console.log(err);
      });
    }
    /*Old One Recommended Assessment*/
    /* this.AuthService.recommendAssessment(reqJSON).then(resp => {
        console.log(resp, 'recommendAssessment');
        this.toastr.success(resp.successMessage);
        this.router.navigate(['pgm/landing/employee'])
      }).catch(err => {
        console.log(err);
      });
    }*/


  }

  onDateChanged(evnt){

    console.log(evnt)

    this.dueDate = evnt.formatted
    console.log(this.dueDate)
  }


  assignBtnClick(){

    if(this.userInfoMstrId.length !== 0) {
      document.getElementById('openModalButton').click();
    }
    else {
      this.toastr.error('Select atleast one employee')
    }
  }


  scheduleAssignCoach() {
    console.log('ok');
    console.log(this.selectCoach, 'selectCoach');
    console.log(this.userInfoMstrId, 'courseEmployeLists')
    document.getElementById('closeAssignCoachModal').click()
  }


}
  interface Skilltrackdetails {
  pgSkillTrackDtlsList: {
    skillTrackDtlsId: number,
    pgSkillTrackMstr: {
      skillTrackMstrId: number,
      skillTrackName: string
    }
    skillTrackDtlsName: string
  }
}


