import { Component, OnInit,Input } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { AuthService } from '../services/auth.service';
import { utils, write, WorkBook } from 'xlsx';
import { saveAs } from 'file-saver';
import {IMyDrpOptions} from 'mydaterangepicker';

@Component({
  selector: 'app-filter-component',
  templateUrl: './filter-component.component.html',
  styleUrls: ['./../ta/ta-dashboard/ta-dashboard.component.css','./filter-component.component.scss']
})
export class FilterComponentComponent implements OnInit {

  myDateRangePickerOptions: IMyDrpOptions = {
    // other options...
    dateFormat: 'dd.mm.yyyy',
  };

  // For example initialize to specific date (09.10.2018 - 19.10.2018). It is also possible
  // to set initial date range value using the selDateRange attribute.

  private model: any = {beginDate: {year: 2018, month: 10, day: 9},
    endDate: {year: 2018, month: 10, day: 19}};

  table = [
    {
      First: 'one',
      Second: 'two',
      Third: 'three',
      Forth: 'four',
      Fifth: 'five'
    },
    {
      First: 'un',
      Second: 'deux',
      Third: 'trois',
      Forth: 'quatre',
      Fifth: 'cinq'
    },
  ];
  myFile: File;
  //myFile:File; /* property of File type */

  url:string
  contentType:string
  mettleReport:string
  Skills: any[]
  TA: any[]
  locations: any[]
  filterDtls = false
  exportEnble = true


  data = []

  datar = [
    {
      "error": null,
      "reportBean": null,
      "name": "Demo Candidate202",
      "onboardDate": 1509107119000,
      "primarySkills": "Javascript",
      "yearOfExp": "INTERMEDIATE",
      "location": "PUNE",
      "screeningTestName": null,
      "screeningScore": null,
      "miniPgScore": null,
      "mainPgScore": null,
      "screeningCoach": null,
      "miniPgCoach": null,
      "mainPgCoach": null,
      "currentStatus": "TA_REJECTED",
      "taname": "Name: PG-TA email-id: PG-TA@altimetrik.com"
    },
    {
      "error": null,
      "reportBean": null,
      "name": "Demo Candidate2",
      "onboardDate": 1509092094000,
      "primarySkills": "Javascript",
      "yearOfExp": "INTERMEDIATE",
      "location": "BANGALORE",
      "screeningTestName": null,
      "screeningScore": null,
      "miniPgScore": null,
      "mainPgScore": null,
      "screeningCoach": null,
      "miniPgCoach": null,
      "mainPgCoach": null,
      "currentStatus": "METTL_SCHEDULED",
      "taname": "Name: PG-TA email-id: PG-TA@altimetrik.com"
    },
    {
      "error": null,
      "reportBean": null,
      "name": "DEMOTEST CANDIDATE",
      "onboardDate": 1510213024000,
      "primarySkills": "Javascript",
      "yearOfExp": "INTERMEDIATE",
      "location": "BENGALURU",
      "screeningTestName": null,
      "screeningScore": null,
      "miniPgScore": null,
      "mainPgScore": null,
      "screeningCoach": null,
      "miniPgCoach": null,
      "mainPgCoach": null,
      "currentStatus": "TA_APPROVED",
      "taname": "Name: Coach email-id: Coach@altimetrik.com"
    }
  ]

  settings = {
    defaultStyle: false,
    hideSubHeader: true,
    actions: false,
    columns: {
      name: {
        filter:false,
        title: 'name'
      },
      primarySkills: {
        filter:false,
        title: 'primarySkills'
      },
      yearOfExp: {
        filter:false,
        title: 'levels'
      },
      location: {
        filter:false,
        title: 'location'
      },
      currentStatus: {
        filter:false,
        title: 'currentStatus'
      },
      onboardDate: {
        filter:false,
        title: 'onboardDate'
      }
    },

  };

  constructor(private AuthService:AuthService,public sanitizer: DomSanitizer) {


    //  this.getFiles()

    var Today = new Date();
    console.log(Today,'todayyyyyyyyyyyyy');
    var day = Today.getDate();
    var monthIndex = Today.getMonth();
    var year = Today.getFullYear();
    console.log(day,'day',monthIndex,'monthIndex',year,'year');

    this.model = {beginDate: {year: year, month: monthIndex, day: day},
      endDate: {year: year, month: monthIndex+1, day: day}};

    this.AuthService.getAllSkill().then(res => {
      var skill = res;
      console.log(skill, "Skills")
      this.Skills = skill.pgSkillTrackDtlsList
      console.log(this.Skills, "skills");
    }).catch(err => {
      console.log(err)
    });


    this.AuthService.getLocations().then(res => {
      var skill = res;
      this.locations = skill.pgLocationList
      console.log(this.locations, "locations")
    }).catch(err => {
      console.log(err)
    });

    this.AuthService.getFetchAllTA().then(res => {
      var ta = res;
      this.TA = res
      console.log(this.TA, "locations")
    }).catch(err => {
      console.log(err)
    });

  }

  ngOnInit() {}

  getDateFormat(e){

    console.log(e);
    console.log(this.model);
  }

  exports() {



    this.data.forEach(item => {


      delete item.error;
      delete item.reportBean;

      // var Date = new Date(item.onboardDate).toLocaleDateString()

      // item.date = Date;

    })


    console.log(this.data,'data modal classs');




    const ws_name = 'SomeSheet';
    const wb: WorkBook = { SheetNames: [], Sheets: {} };
    const ws: any = utils.json_to_sheet(this.data);
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    const wbout = write(wb, { bookType: 'xlsx', bookSST: true, type:
        'binary' });

    function s2ab(s) {
      const buf = new ArrayBuffer(s.length);
      const view = new Uint8Array(buf);
      for (let i = 0; i !== s.length; ++i) {
        view[i] = s.charCodeAt(i) & 0xFF;
      };
      return buf;
    }

    saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), 'exported.xlsx');
  }


  filterItem(date,location,skill,ta,cName){
    console.log(date.formatted);
    console.log( cName);
    console.log( ta);
    console.log( skill);
    console.log( location);
    var ss = []
    if (date.formatted) {
      if (date.formatted.length != 0) {
        ss = date.formatted.split(" - ")
      }
    }
    console.log(ss);
    var reqJson = {}

    /*if(ss.length != 0 ){
      reqJson['START_DATE'] = ss[0]
      reqJson['END_DATE'] = ss[1]
    }
    else {

      var Today = new Date();
      console.log(Today,'todayyyyyyyyyyyyy');
      var day = Today.getDate();
      var monthIndex = Today.getMonth();
      var currentmonthIndex = monthIndex+1;
      var year = Today.getFullYear();
      reqJson['START_DATE'] = day+'.'+monthIndex+'.'+year
      reqJson['END_DATE'] = day+'.'+currentmonthIndex+'.'+year
    }*/
    if(skill) {
      if (skill.length != 0 || skill) {
        reqJson['PRIMARY_SKILL'] = skill
      }
    }
    if(ta){
      if(ta.length != 0 || ta) {
        reqJson['CANDIDATE_TA'] = ta
      }
    }
    if(location){
      reqJson['LOCATION'] = location
    }
    if(cName){
      reqJson['CANDIDATE_NAME'] = cName
    }

    console.log(reqJson,'REPORT FILTER REQUEST JSON')

    this.exportEnble = false


    this.AuthService.reportEmployeeFilter({
        "filter": {
          "ALL": []
        }
      }
    ).then(resp => {
      console.log(resp);

      var report = []

      for (var i = 0; i < resp.reportBean.length; i++) {

        resp.reportBean[i].courseDetails.forEach(course => {

          report.push({
            Name: resp.reportBean[i].name,
            Location: resp.reportBean[i].location,
            NoOfRecommendedCourses: resp.reportBean[i].noOfRecommendedCourses,
            CoachName: course.coachName,
            courseName: course.courseName,
            Status: course.status,
            PrimarySkillScore: course.primarySkillScore,
            TechnicalSkillScore: course.technicalSkillScore,
            BusinessSkillScore: course.businessSkillScore,
          })
        })
      }
      console.log(report,'reportreportreportreportreport');

console.log(report,'reportreportreportreportreport');
/*this.data = resp.reportBean;
this.exportEnble = false
this.filterDtls = false*/
    }).catch(err => {

      console.log(err);
    })


  }


}
