import {Component, OnInit, Inject, HostListener} from '@angular/core';
import { UserInfo } from 'app/models/userInfo.model';
import { AuthService } from 'app/services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { NavBarService } from '../../../pgm/pgm.service';
import { EmployeeHttpService } from 'app/services/employee/employee-http.service';
import { EmployeeService } from 'app/employee.service';
import { Subject } from 'rxjs/Rx';
import { DOCUMENT } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastsManager } from 'ng2-toastr';
import _ from 'lodash';
import {IMyDpOptions} from 'mydatepicker';
import {BulkUploadFileService} from "../../../ta/ta-bulk-upload/bulk-upload-file.service";
import { environment } from "../../../../environments/environment.dev";
@Component({
  selector: 'app-select-course-and-assessment',
  templateUrl: './select-course-and-assessment.component.html',
  styleUrls: ['./select-course-and-assessment.component.scss']
})
export class SelectCourseAndAssessmentComponent implements OnInit {

  private $destroyed = new Subject();
  documentDetails;
  selectedTab: number;
  showcatdispDiv: boolean = false;
  coursesLists;
  allCourses;
  primaryAssessment;
  technicalAssessment;
  businessAssessment;
  allReservedCourses;
  primaryReservedAssessment;
  technicalReservedAssessment;
  businessReservedAssessment;
  allSelectedCourses: any = [];
  primarySelectedAssessment: any = [];
  technicalSelectedAssessment: any = [];
  businessSelectedAssessment: any = [];
  skillMstrIds;
  selectedCoursesDetails: any = [];
  selectedCourses: any = [];
  selectedCoursesSetDueDate: any = [];
  selectedCourseIdCollection: string;
  skills: any;
  selectedSkill: any = [];
  empLists: any = [];
  loader = true;
  currentPageData: { title: string, back: string };
  onlyOneRole: boolean;
  public currentPageNumber = 0;
  img_path = environment.imageUrl+'/assets/img/Taflow/';
  initials = '';
  employee: any = {};
  tabDetails = [
    { className: 'first', Id: 2, containerText: 'Courses', count: 0 },
    { className: 'second', Id: 3, containerText: 'Primary Assessment', count: 0 },
    { className: 'third', Id: 4, containerText: 'Technical Assessment', count: 0 },
    { className: 'fourth', Id: 1, containerText: 'Business Assessment', count: 0 },
  ];
  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any,
    email: any
  };
  afterSelect = true;
  selectedEmployeeDetails: any = [];
  selectedEmployee: any = [];
  BeforeSelectCls = "col-lg-12";
  AfterSelectCls = "col-lg-0";
  UperBeforSelectCls = "col-lg-8";
  UperAfterSelectCls = "col-lg-4";

  myDatePickerOptions: IMyDpOptions = {
    // other options...
    dateFormat: 'dd-mm-yyyy',
    openSelectorTopOfInput : true,
    inline: false,
  };
  public model: any = 'Due date';

  private placeholder: string = 'Select Due date';

  dueDate: any
  //img_path = '../assets/img/Taflow/';
  dragAreaClass: string = 'dragarea';

  dueDateContainer = true;
  uploadContainer = false;
  searchContainer = false;
  employeeListContainer = false
  uploadedEmployeeList = false
  confirmationContainer = false

  courseAssigned = false;
  assessmentAssigned = false;
  empLists1 = [];
  imageUrl = environment.imageUrl;
  constructor( @Inject(DOCUMENT) document,
               protected localStorageService: LocalStorageService,
               private navBarService: NavBarService,
               private employeeHttpService: EmployeeHttpService,
               private employeeService: EmployeeService,
               private route: ActivatedRoute,
               private AuthService: AuthService,
               private toaster: ToastsManager,
               private router: Router,
               private bulkUploadFileService: BulkUploadFileService,
  ) {
    this.navBarService.setCurrentPage(3);
    console.log(document);
    this.documentDetails = document;
    this.selectedTab = 0;
    this.getAllSkills();
    // this.route.queryParams.subscribe(params => {
    //   console.log(params)
    // });
    // this.employeeNavBarService.getSelectedCourse();
    // this.selectedSkill = this.employeeService.getSelectedCourse();
    console.log(this.selectedSkill);
    this.callGetSeachedData();
    if (window.location.origin !== 'http://localhost:8080') {
      let empData;
      empData = this.localStorageService.get('userInfo');
      this.empData = empData;
      if (empData['roles'].length > 1) {
        this.onlyOneRole = false;
      } else {
        this.onlyOneRole = true;
      }

      console.log(this.empData, 'userInfo Detailssssss');
      if (this.empData['fullName']) {
        this.initials = this.empData['fullName'].replace(/\W*(\w)\w*/g, '$1').toUpperCase();
      }
    } else {
      this.initials = 'LS';
    }
    this.empData = this.localStorageService.get('userInfo');
    this.employee = this.localStorageService.get('userInfo');
  }



  ngOnInit() {
   // this.currentPageData = dashboardPages[0];
  }
  toggleActive(newValue: number) {
    this.selectedTab = newValue;
  }
  callGetSeachedData() {
    if (this.localStorageService.get('selectedCourse') && this.localStorageService.get('serachedText')) {
      const getIds = this.selectedSkilIdDetails(this.localStorageService.get('selectedCourse'));
      const searchedText = '&keyword=' + this.localStorageService.get('serachedText');
      const searchedTextAndId = getIds + searchedText;
      this.getBnyCourseDetails(searchedTextAndId);
    } else if (this.localStorageService.get('selectedCourse')) {
      const getIds = this.selectedSkilIdDetails(this.localStorageService.get('selectedCourse'));
      this.getBnyCourseDetails(getIds);
    } else if (this.localStorageService.get('serachedText')) {
      const searchedText = '?keyword=' + this.localStorageService.get('serachedText');
      this.getBnyCourseDetails(searchedText);
    }
  }
  smoothScroll(target) {
    // document.getElementById('el');
    let scrollContainer = target;
    do { // find scroll container
      scrollContainer = scrollContainer.parentNode;
      if (!scrollContainer) return;
      scrollContainer.scrollTop += 1;
    } while (scrollContainer.scrollTop === 0);

    let targetY = 0;
    do { // find the top of target relatively to the container
      if (target == scrollContainer) break;
      targetY += target.offsetTop;
    } while (target = target.offsetParent);

    var scroll = function (c, a, b, i) {
      i++; if (i > 30) return;
      c.scrollTop = a + (b - a) / 30 * i;
      setTimeout(function () { scroll(c, a, b, i); }, 20);
    }
    // start scrolling
    scroll(scrollContainer, scrollContainer.scrollTop, targetY, 20);
  }
  getBnyCourseDetails(selectedSkill) {
    this.loader = true;
    this.employeeHttpService.getBNYEmployeeCourseDetails(selectedSkill).subscribe(response => {
      console.log(response);
      this.coursesLists = response;
      this.allCourses = response.allCourses;
      this.businessAssessment = response.businessAssessment;
      this.technicalAssessment = response.technicalAssessment;
      this.primaryAssessment = response.primaryAssessment;
      this.allReservedCourses = response.allCourses;
      this.businessReservedAssessment = response.businessAssessment;
      this.technicalReservedAssessment = response.technicalAssessment;
      this.primaryReservedAssessment = response.primaryAssessment;
      this.skillMstrIds = response.skillMstrIds;
      if (this.localStorageService.get('serachedText')) {
        this.selectedSkill = _.filter(this.skills, (v) => _.includes(this.skillMstrIds, v.skillTrackMstrId));
      }

      this.getCourseCount(response);
      this.loader = false;
    }, (error) => {
      this.loader = false;
      this.allCourses = [];
      this.primaryAssessment = [];
      this.technicalAssessment = [];
      this.businessAssessment = [];
    });
  }
  getCourseCount(courseList) {
    this.tabDetails.forEach((data) => {
      if (data.containerText === 'Courses') {
        data.count = courseList.allCourses.length;
      } else if (data.containerText === 'Primary Assessment') {
        data.count = courseList.primaryAssessment.length;
      } else if (data.containerText === 'Technical Assessment') {
        data.count = courseList.technicalAssessment.length;
      } else if (data.containerText === 'Business Assessment') {
        data.count = courseList.businessAssessment.length;
      }
    })
  }

  selectCourse(course: any = {}, category) {
    if (course.selected) {
      course.selected = false;
      if (category === 'course') {
        this.allSelectedCourses = this.allSelectedCourses.filter(item => item.courseDetailsId !== course.courseDetailsId);
        // this.selectedCourses = this.selectedCourses.filter(item => item.courseDetailsId !== course.courseDetailsId);
      } else if (category === 'Primary') {
        this.primarySelectedAssessment = this.primarySelectedAssessment.filter(item => item.assessmentId !== course.assessmentId);
        // this.selectedCourses = this.selectedCourses.filter(item => item.assessmentId !== course.assessmentId);
      } else if (category === 'Technical') {
        this.technicalSelectedAssessment = this.technicalSelectedAssessment.filter(item => item.id !== course.id);
        // this.selectedCourses = this.selectedCourses.filter(item => item.id !== course.id);
      } else if (category === 'Business') {
        this.businessSelectedAssessment = this.businessSelectedAssessment.filter(item => item.id !== course.id);
        // this.selectedCourses = this.selectedCourses.filter(item => item.id !== course.id);
      }
      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)
      if (category === 'course') {
        // this.selectedCourses.push({ 'courseId': course.courseDetailsId, "assessment": course.assessment });
        this.allSelectedCourses.push(course);
      } else if (category === 'Primary') {
        // this.selectedCourses.push({ 'courseId': course.courseDetailsId, "assessment": course.assessment });
        this.primarySelectedAssessment.push(course)
      } else if (category === 'Technical') {
        // this.selectedCourses.push({ 'courseId': course.courseDetailsId, "assessment": course.assessment });
        this.technicalSelectedAssessment.push(course)
      } else if (category === 'Business') {
        // this.selectedCourses.push({ 'courseId': course.courseDetailsId, "assessment": course.assessment });
        this.businessSelectedAssessment.push(course)
      }
      this.selectedCourses.push({ 'courseId': course.courseDetailsId, "assessment": course.assessment });
    }
    console.log(this.selectedCourses, 'selectedCourses');
    console.log(this.selectedCoursesDetails, 'selectedCoursesDetails');
  }


  setDueDate(course: any = {}, category) {
    if (course.selected) {
      this.selectedCoursesSetDueDate = this.selectedCoursesSetDueDate.filter(item => item.courseDetailsId !== course.courseDetailsId);

      this.allSelectedCourses.forEach(item => {
        if(item.courseDetailsId == course.courseDetailsId) {
          item.selected = false;
         // item.dueDate = undefined;
        }

      })
    } else {
     // course.selected = true;
      this.allSelectedCourses.forEach(item => {
        if(item.courseDetailsId == course.courseDetailsId) {
          item.selected = true;
         // item.dueDate = "30 june 2018";

          this.selectedCoursesSetDueDate.push(item);
        }
      })
    }
    console.log(this.allSelectedCourses, 'allSelectedCourses');
    console.log(this.selectedCourses, 'selectedCourses');
    console.log(this.selectedCoursesSetDueDate, 'selectedCoursesSetDueDate');
  }


  onDateChanged(evnt){
    console.log(evnt.formatted);
    this.dueDate = evnt.formatted
    this.allSelectedCourses.forEach(allCourse => {
    this.selectedCoursesSetDueDate.forEach(dueDateCourse => {
      if(allCourse.courseDetailsId == dueDateCourse.courseDetailsId) {
         allCourse.selected = false;
       // this.setDueDate(dueDateCourse,'category');
        allCourse.dueDate = this.dueDate;
      }
    })
    })
    this.selectedCoursesSetDueDate = [];
  }


  assignCourseAssessment() {
    this.allSelectedCourses.forEach(allCourse => {

    })
    let setDateCoure = [] = this.allSelectedCourses.filter(item => item.dueDate);

    console.log(setDateCoure)
    if(setDateCoure.length !== this.allSelectedCourses.length){
      this.toaster.error( "Please set Due Date All courses");
    } else {

      this.BeforeSelectCls = "col-lg-8";
      this.AfterSelectCls = "col-lg-4 aftrSlctCls";
      this.UperBeforSelectCls = "col-lg-4";
      this.UperAfterSelectCls = "col-lg-3";
      this.employeeListContainer = true;
      this.dueDateContainer = false;
    }
  }


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

  selectedSkilIdDetails(selectedskillId) {
    // this.selectedSkill = _.filter(this.skills, (v) => _.includes(selectedskillId, v.skillTrackMstrId));
    this.selectedCourseIdCollection = null;
    selectedskillId.forEach(element => {
      if (!this.selectedCourseIdCollection) {
        this.selectedCourseIdCollection = '?skillIds=' + element.skillTrackMstrId;
      } else {
        this.selectedCourseIdCollection = this.selectedCourseIdCollection + ',' + element.skillTrackMstrId;
      }
    });
    this.selectedSkill = this.localStorageService.get('selectedCourse');
    return this.selectedCourseIdCollection;
  }
  updateCourse() {

  }

  deleteCourse(skillData) {
    if (this.selectedSkill.length > 0) {
      this.selectedSkill.forEach((element, index) => {
        if (element.skillTrackMstrId === skillData.skillTrackMstrId) {
          this.selectedSkill.splice(index, 1);
        }
      });
      this.localStorageService.remove('selectedCourse');
      this.localStorageService.set('selectedCourse', this.selectedSkill);
      this.callGetSeachedData();
    }
    // this.selectedSkill
    // console.log(skillData);
    // _.remove(this.selectedSkill, obj => skillData.includes(obj.skillTrackMstrId));
  }
  displaySelectedCats() {
    if (this.showcatdispDiv == false) {
      this.showcatdispDiv = true;
    }
    else if (this.showcatdispDiv == true) {
      this.showcatdispDiv = false;
    }

  }



  selectedCourseAssessment(){
    console.log(this.allSelectedCourses);
    console.log(this.primarySelectedAssessment);
    console.log(this.technicalSelectedAssessment);
    console.log(this.businessSelectedAssessment);
    this.afterSelect = false;
    this.allSelectedCourses.forEach(item => {
      item.selected = false;
      item.dueDate = undefined;
    });
    this.primarySelectedAssessment.forEach(item => {
      item.selected = false;
    });
    this.technicalSelectedAssessment.forEach(item => {
      item.selected = false;
    });
    this.businessSelectedAssessment.forEach(item => {
      item.selected = false;
    });

  }
  SearchforCourses(event) {
    const val = event.target.value.toLowerCase();

    // filter our data
    const tempCourse = this.allReservedCourses.filter(function (d) {
      return d['courseName'].toLowerCase().indexOf(val) !== -1 || !val;
    });
    const tempBusiness = this.businessReservedAssessment.filter(function (d) {
      return d['usecaseTitle'].toLowerCase().indexOf(val) !== -1 || !val;
    });
    const tempTechnical = this.technicalReservedAssessment.filter(function (d) {
      return d['usecaseTitle'].toLowerCase().indexOf(val) !== -1 || !val;
    });
    const tempPrimary = this.primaryReservedAssessment.filter(function (d) {
      return d['assessmentDesc'].toLowerCase().indexOf(val) !== -1 || !val;
    });
    this.allCourses = tempCourse;
    this.primaryAssessment = tempPrimary;
    this.businessAssessment = tempBusiness;
    this.technicalAssessment = tempTechnical;
    this.tabDetails.forEach((data) => {
      if (data.containerText === 'Courses') {
        data.count = this.allCourses.length;
      } else if (data.containerText === 'Primary Assessment') {
        data.count = this.primaryAssessment.length;
      } else if (data.containerText === 'Technical Assessment') {
        data.count = this.technicalAssessment.length;
      } else if (data.containerText === 'Business Assessment') {
        data.count = this.businessAssessment.length;
      }
    })
  }

  goToPrevPage() {
    if (this.localStorageService.get('serachedText')) {
      this.selectedSkill.forEach(element => {
        element.isSelected = true;
      });
      this.localStorageService.set('selectedCourse', this.selectedSkill);
    }
    this.router.navigate(['talent-transformation/employee/CourseAndAssessment', 1]);
  }



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


  onSelectionChange (emp, value, evnt) {
    console.log('selected Employeeee Events', evnt);
    console.log(emp, 'selected Employeeee', value);

    if (evnt.target.checked) {
      this.selectedEmployee = Object.assign({}, this.selectedEmployee, emp);
      this.selectedEmployeeDetails.push(emp);
      console.log(this.selectedEmployeeDetails, 'selected EmployeeDetails');
    } else {
      this.selectedEmployeeDetails = this.selectedEmployeeDetails.filter(item => item.adId !== emp.adId)
      console.log(this.selectedEmployeeDetails, 'selected EmployeeDetails');

    }
  }

  empAssignClick(params){
    if (params == 'search') {
      this.uploadContainer = false;
      this.searchContainer = true;
      this.employeeListContainer = false;
    } else {
      this.uploadContainer = true;
      this.searchContainer = false;
      this.employeeListContainer = false;
    }
  }


  keySearch (param) {

    console.log(param, 'param');

    if (param) {
      this.employeeHttpService.quicksearchEmployee({filterParam: param})
        .subscribe(data => {
          // console.log('SearchEmployee' + JSON.stringify(data));
          // if (data.userList.length !== 0) {
          //   this.empLists = data.userList;
          //   this.confirmationContainer = true;
          // }
          this.empLists1 = data;
          this.confirmationContainer = true;
          this.empLists = [];
        });
    } else {
      this.empLists = [];
    }
  }

  goToDashboard () {
    this.router.navigate(['talent-transformation/landing/employee'])
  }


  onFileChange(event) {
    let files = event.target.files;
    this.saveFiles(files);
  }
  @HostListener('dragover', ['$event']) onDragOver(event) {
    this.dragAreaClass = "droparea";
    event.preventDefault();
  }
  @HostListener('dragenter', ['$event']) onDragEnter(event) {
    this.dragAreaClass = "droparea";
    event.preventDefault();
  }
  @HostListener('dragend', ['$event']) onDragEnd(event) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
  }
  @HostListener('dragleave', ['$event']) onDragLeave(event) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
  }
  @HostListener('drop', ['$event']) onDrop(event) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
    event.stopPropagation();
    var files = event.dataTransfer.files;
    this.saveFiles(files);
  }

  saveFiles(files) {
    console.log(files)


    if (files.length > 0) {
      let formData: FormData = new FormData();
      for (var j = 0; j < files.length; j++) {
        formData.append("file[]", files[j], files[j].name);
      }
      // var parameters = {
      //     projectId: this.projectId,
      //     sectionId: this.sectionId
      // }
      //this.bulkUploadFileService.upload(formData, parameters)
      this.bulkUploadFileService.EmployeUpload(formData)
        .subscribe(
          uplResult => {
            console.log(uplResult);

            this.empLists = uplResult.userList

            this.uploadedEmployeeList = true;
            this.confirmationContainer = true;

          },
          error => {
            console.log(JSON.stringify(error));

          });
    }
  }

  submitCourseAssessment() {

    if(this.selectedEmployeeDetails.length == 0){
      this.toaster.error('Please Select Employee');
    } else {
      this.assignCourse(this.allSelectedCourses, this.selectedEmployeeDetails);
      this.assignAssessment();
    }

  }



  assignCourse(course,empList) {

    var courseJson = []
    var userJson = []
    if(course.length !== 0) {
      course.forEach(list => {
        const filteredCourse = {
           dueDate: list.dueDate,
          courseId: list.courseDetailsId,
          recommended: true,
          loggedInUserEmail: this.empData.email,
        };
        courseJson.push(filteredCourse);
      });
      empList.forEach(user => {
        if(user.userInfoMstrId) {
          userJson.push(user.userInfoMstrId);
        } else {
          userJson.push(user.userInfoMstr.userInfoMstrId);
        }
      })
      const ReqJson = {
        userId : userJson,
        courseDetails: courseJson
      }
      console.log(ReqJson)

      this.AuthService.addUserCourses(ReqJson).then(resp => {

        console.log(resp);
        if (resp.status == 'error') {
          console.log(resp);
          this.toaster.error(resp.message);

        } else {

        this.courseAssigned = true;
        this.confirmationContainer = false;
        this.BeforeSelectCls = "col-lg-8 changeOpacity";
      }

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

    }

  }
  assignAssessment() {



    const skillIds = _.map(this.selectedSkill, function (row, index) {
      return _.omit(row, ['createdBy', 'createdDt', 'description', 'isSelected',
        'skillTrackName', 'status', 'updatedBy', 'updatedDt',]);
    });
    const courseBasedOnSkill = [];
    const users = [];
    skillIds.forEach((element, index) => {
      const selfAssessmentBean = {
        learningPathList: [],
        primaryAssessmentId: [],
        technicalAssessmentId: [],
        businessAssessmentId: [],
        skillTrackMstrId: Number
      };
      this.primarySelectedAssessment.forEach(list => {
        if (element.skillTrackMstrId === list.pgSkillTrackMstr.skillTrackMstrId) {
          selfAssessmentBean.primaryAssessmentId.push(Number(list.assessmentId));
        }
      });
      this.technicalSelectedAssessment.forEach(list => {
        if (element.skillTrackMstrId === list.skillTrackMstrId) {
          selfAssessmentBean.technicalAssessmentId.push(list.id);
        }
      });
      this.businessSelectedAssessment.forEach(list => {
        if (element.skillTrackMstrId === list.skillTrackMstrId) {
          selfAssessmentBean.businessAssessmentId.push(list.id);
        }
      });
      selfAssessmentBean.skillTrackMstrId = element.skillTrackMstrId;
      if ( selfAssessmentBean.businessAssessmentId.length > 0 || selfAssessmentBean.primaryAssessmentId.length > 0 || selfAssessmentBean.technicalAssessmentId.length > 0) {
        courseBasedOnSkill.push(selfAssessmentBean);
      }
    });

    this.selectedEmployeeDetails.forEach(user => {
      users.push(user.userInfoMstrId);
    })

    const assessmentData = {
      selfAssessmentBean: courseBasedOnSkill,
      "mandatory": true,
      "dueDate": "2018-10-01T09:45:00.000",
      "userInfoMstrId": users,
      "loggedInUserEmail": this.empData.email,
    };

    this.AuthService.selfAssessment(assessmentData).then(resp => {

      console.log(resp);
      if(resp.status == 'error'){
        console.log(resp);
        this.toaster.error(resp.message);
      } else {
        this.assessmentAssigned = true;
        this.confirmationContainer = false;
        this.BeforeSelectCls = "col-lg-8 changeOpacity";
      }
    }).catch(err => {
      console.log(err);
    })

  }

  deleteItems(evnt,type){
    console.log(evnt,type)
    if (type === "technical") {
      this.technicalSelectedAssessment.splice(evnt,1)
    } else if (type === "business") {
      this.technicalSelectedAssessment.splice(evnt,1)
    } else if(type === "primary") {
      this.primarySelectedAssessment.splice(evnt,1)
    } else {

    }
  }



}
