import { Component, OnInit, ViewChild } from '@angular/core';
import { LocalStorage } from '../../core/services/local_storage.service';
import { HyperService } from '../../core/services/http.service';
import { Router, ActivatedRoute } from '@angular/router';
import * as moment from 'moment';
import { AddparticipantpopComponent } from '../addparticipantpop/addparticipantpop.component';
import { ConfirmpopComponent } from '../confirmpop/confirmpop.component';
import { Location } from '@angular/common';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { DatepickerOptions } from 'ng2-datepicker';
import { AmazingTimePickerService } from 'amazing-time-picker';
import { ToasterService } from '../../core/services/toaster.service';

@Component({
  selector: 'app-addtraining',
  templateUrl: './addtraining.component.html',
  styleUrls: ['./addtraining.component.scss']
})
export class AddTrainingComponent implements OnInit {
  sub: any;
  sch_id: any;
  training_detail: any = [];
  participant_data: any = {};
  is_addparticipant: boolean = false;
  addparticipantsmpin:any;
  loader: boolean;
  type: any;
  user_id: any;
  userData: any = {};
  zmmail:string='';
  rmmail:string='';
  ammail:string='';
  participantdata : any;
  registerForm: FormGroup;
  @ViewChild(AddparticipantpopComponent) participant_pop: AddparticipantpopComponent;
  @ViewChild(ConfirmpopComponent) confirm_pop: ConfirmpopComponent;
  training_type: any;
  trainingtitle: any;
  showtextbox: boolean;
  rm_list: any=[];
  am_list: any=[];
  showam: boolean;
  showdealer: boolean;
  dealer_list: any=[];
  extended_type = '';
  dse_list: any;
  showdse: boolean;
  typermdata: any=[];
  typeamdata: any=[];
  typedealerdata: any=[];
  typedsedata: any=[];
  typezmuserdata: any=[];
  typermuserdata: any=[];
  typeamuserdata: any=[];
  dob: any;
  timevalue: Date = new Date();
  userdata:any;
  today=new Date();
  submitted: boolean;
  year = this.today.getFullYear();
  month = this.today.getMonth();
  day = this.today.getDate();
  // mindate:any = moment({year: this.year, month: this.month, day: this.day}).format('YYYY-MM-DD');
  options: DatepickerOptions = {
    minDate:  new Date(this.year,this.month,this.day) // Minimal selectable date
  }
  currenttime;
  endtimes: any;
  startTime: any;
  endTime: any;
  public min = new Date();
  user_role: any;
  user_role_am_mail: any=[];
  user_role_dealer_mail: any=[];
  user_role_dse_mail: any=[];
  totalparticipant_list: any=[];
  totalzmparticipant_list : any =[];
  totalrmparticipant_list : any =[];
  totalamparticipant_list : any =[];
  startdate:any=new Date();
  zm_userlist:any =[];
  rm_userlist:any =[];
  am_userlist:any =[];
  showzmuser: boolean = false;
  showrmuser: boolean = false;
  showamuser: boolean = false;
  // config:AtpTimePickerComponent;
  constructor(private server: HyperService,private toaster: ToasterService, private atp: AmazingTimePickerService, private formBuilder: FormBuilder,private router: Router, private route: ActivatedRoute,private _location: Location) {
    this.sub = this.route.params.subscribe(params => {
      this.sch_id = params['id'];
      this.type = params['type'];
      this.user_id = params['token'];
      this.userData.emailid = params['email'];
      this.rmmail = params['rmmail'];
      this.ammail = params['ammail'];
      this.zmmail = params['zmmail'];
    });
  }

  openstartclock(){
    var today_date = this.today.getFullYear()+'/'+this.today.getMonth()+'/'+this.today.getDate();
    var date = this.registerForm.controls['startdate'].value;
    var selected_date = date.getFullYear()+'/'+date.getMonth()+'/'+date.getDate()
    if(new Date(selected_date) > new Date(today_date)){
      this.currenttime = '00:00'
    }else{
      this.currenttime = new Date().getHours()+':'+new Date().getMinutes();
    }
    const amazingTimePicker = this.atp.open({
      time:  this.currenttime,
      rangeTime: { start: this.currenttime, end: this.endtimes },
      arrowStyle: {
          background: 'red',
          color: 'white'
      }
    });
      amazingTimePicker.afterClose().subscribe(time => {
        this.startTime = time;
        this.registerForm.controls['startTime'].setValue(this.startTime)
    });
    this.registerForm.controls['endTime'].setValue('');
  }

  openendclock(){
    if(this.startTime!=null && this.startTime!='' && this.startTime!=undefined){
       let a : any =this.startTime.split(':');
       let b = Number(a[1])+Number(5);
       let min;
       let correct_time;
       if(b>=60){
        a[0] = Number(a[0])+Number(1);
        min = b - Number(60);
        correct_time = a[0]+':'+min;
       }else{
        min = b;
        correct_time = a[0]+':'+min;
       }
      const amazingTimePicker = this.atp.open({
        time:  correct_time,
        rangeTime: { start: correct_time, end: this.endtimes },
        arrowStyle: {
            background: 'red',
            color: 'white'
        }
      });
        amazingTimePicker.afterClose().subscribe(time => {
          this.endTime = time;
          this.registerForm.controls['endTime'].setValue(this.endTime)
      });
    }else{
      this.toaster.show('Please select start time');
    }
  }

  changedate(){
    this.registerForm.controls['startTime'].setValue('');
    this.registerForm.controls['endTime'].setValue('');
  }

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      title: ['', Validators.required],
      description: ['', Validators.required],
      // customer_mobile: ['', [Validators.required, Validators.pattern(/^[0-9]{10,10}$/)]],
      // customer_name: ['', Validators.required],
      startdate: [new Date(),Validators.required],
     // enddate : [new Date(),Validators.required],
      startTime : ['',Validators.required],
      endTime : ['',Validators.required]
    });
  
    LocalStorage.setValue('is_firsttime', false);
    this.getTrainingtypelist();
    this.user_role = LocalStorage.getValue('user_data').role;
    this.check_role_login();
    this.getuserlist();
  }

  getuserlist(){
    this.server.post("common/ilearnuserlist",{ role : 4 })
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showzmuser = true;
        this.zm_userlist = data.result.data;
      }else{
        this.showzmuser = false;
      }
    })

    this.server.post("common/ilearnuserlist",{ role : 6 })
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.rm_userlist = data.result.data;
        this.showrmuser = true;
      }else{
        this.showrmuser = false;
      }
    })

    this.server.post("common/ilearnuserlist",{ role : 7 })
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.am_userlist = data.result.data;
        this.showamuser = true;
      }else{
        this.showamuser = false;
      }
    })
  }

  check_role_login(){
    if(this.user_role == 5 || this.user_role == 4){
      this.getRmlist();
    }else if(this.user_role == 6){
      this.getAmlist();
    }else if(this.user_role == 7){
      this.getdealerlist();
    }else if(this.user_role == 14){
      this.getdselist();
    }
  }

  getAmlist(){
    this.user_role_am_mail.push(LocalStorage.getValue('user_data').emailid);
    let senddata = {};
    senddata = {"rm_email":JSON.stringify(this.user_role_am_mail)}
    this.server.post("common/traineram",senddata)
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showam = true;
        this.am_list = data.result.data;
        // this.participant_data = data.result.data.participant;
      }else{
        this.am_list=[];
        this.showam =false;
        this.showdealer =false;
        this.showdse =false;
      }
    })
  }

  getdealerlist(){
    this.user_role_dealer_mail.push(LocalStorage.getValue('user_data').emailid);
    let senddata = {};
    senddata = {"am_email":JSON.stringify(this.user_role_dealer_mail)}
    this.server.post("common/trainerdealer",senddata)
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showdealer = true;
        this.dealer_list = data.result.data;
        // this.participant_data = data.result.data.participant;
      }else{
        this.dealer_list=[];
        this.showdealer =false;
        this.showdse =false;
      }
  })
  }

  getdselist(){
    this.user_role_dse_mail.push(LocalStorage.getValue('user_data').dealer_code);
    let senddata = {};
    senddata = {"dealer_code":JSON.stringify(this.user_role_dse_mail)}
    this.server.post("common/dselist",senddata)
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showdse = true;
        this.dse_list = data.result.data;
        // this.participant_data = data.result.data.participant;
      }else{
        this.dse_list=[];
        this.typedsedata=[];
        this.showdse =false;
      }
  })
  }

  getTrainingtypelist(){
    this.server.get("videotraining/traininglist")
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed'){
          this.training_type = data.result.data;
        }
    })
  }
  getRmlist(){
    this.server.post("common/trainerrm",'')
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.rm_list = data.result.data;
      }
    })
  }
  open() {
  //  const amazingTimePicker = this.atb.open();
  //   amazingTimePicker.afterClose().subscribe(time => {
  //   });
  }
  typeChange(type){
    this.trainingtitle = type;
    if(type=='none'){
      this.showtextbox = true;
    }else{
      this.showtextbox = false;
    }
  }
  Changerm(event,i){
    this.typeamdata = [];
    this.typedealerdata = [];
    this.typedsedata = [];
    this.totalparticipant_list = [];
    this.showdealer = false;
    this.showdse = false;
    var value=event.target.value;
    var senddata={};
    const index = this.typermdata.indexOf(value);
    if(event.target.checked){
      this.typermdata.push(event.target.value);
    }else{
      if (index > -1) {
        this.typermdata.splice(index, 1);
      }
    }
    senddata = {"rm_email":JSON.stringify(this.typermdata)}
    this.server.post("common/traineram",senddata)
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showam = true;
        this.am_list = data.result.data;
        // this.participant_data = data.result.data.participant;
      }else{
        this.am_list=[];
        this.showam =false;
        this.showdealer =false;
        this.showdse =false;
      }
  })
  }
  Changeam(event,i){
    this.typedealerdata = [];
    this.typedsedata = [];
    this.totalparticipant_list =[];
    this.showdse = false;
    var value=event.target.value;
    var senddata={};
    const index = this.typeamdata.indexOf(value);
    if(event.target.checked){
      this.typeamdata.push(event.target.value);
    }else{
      if (index > -1) {
        this.showdealer = false;
        this.typeamdata.splice(index, 1);
      }
    }
    senddata = {"am_email":JSON.stringify(this.typeamdata)}
    this.server.post("common/trainerdealer",senddata)
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showdealer = true;
        this.dealer_list = data.result.data;
        // this.participant_data = data.result.data.participant;
      }else{
        this.dealer_list=[];
        this.showdealer =false;
        this.showdse =false;
      }
  })
  }
  Changedealer(event,i){
    this.typedsedata = [];
    this.totalparticipant_list = [];
    var value=event.target.value;
    var senddata={};
    const index = this.typedealerdata.indexOf(value);
    if(event.target.checked){
      this.typedealerdata.push(event.target.value);
    }else{
      if (index > -1) {
        this.showdse =false;
        this.typedealerdata.splice(index, 1);
      }
    }
    senddata = {"dealer_code":JSON.stringify(this.typedealerdata)}
    this.server.post("common/dselist",senddata)
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showdse = true;
        this.dse_list = data.result.data;
        // this.participant_data = data.result.data.participant;
      }else{
        this.dse_list=[];
        this.typedsedata=[];
        this.showdse =false;
      }
  })
  }
  Changedse(event){
    this.totalparticipant_list =[];
    var value=event.target.value;
    const index = this.typedsedata.indexOf(value);
    if(event.target.checked){
      this.typedsedata.push(event.target.value);
      this.displaylist(this.typedsedata);
    }else{
      if (index > -1) {
        this.typedsedata.splice(index, 1);
        this.displaylist(this.typedsedata);
      }
    }
  }

  displaylist(data){
    this.totalparticipant_list=[];
    for(let i=0;i<this.dse_list.length;i++){
      for(let j=0;j<data.length;j++){
        if(this.dse_list[i].userid==data[j]){
          this.totalparticipant_list.push(this.dse_list[i]);
        }
      }
    }
  }

  addParticipant(){
    this.is_addparticipant = true;
  }

  Changezmuser(event,i){
    this.totalzmparticipant_list =[];
    var value=event.target.value;
    const index = this.typezmuserdata.indexOf(value);
    if(event.target.checked){
      this.typezmuserdata.push(event.target.value);
      this.displayzmlist(this.typezmuserdata);
    }else{
      if (index > -1) {
        this.typezmuserdata.splice(index, 1);
        this.displayzmlist(this.typezmuserdata);
      }
    }
  }

  displayzmlist(data){
    this.totalzmparticipant_list=[];
    for(let i=0;i<this.zm_userlist.length;i++){
      for(let j=0;j<data.length;j++){
        if(this.zm_userlist[i].userid==data[j]){
          this.totalzmparticipant_list.push(this.zm_userlist[i]);
        }
      }
    }
  }

  Changermuser(event,i){
    this.totalrmparticipant_list =[];
    var value=event.target.value;
    const index = this.typermuserdata.indexOf(value);
    if(event.target.checked){
      this.typermuserdata.push(event.target.value);
      this.displayrmlist(this.typermuserdata);
    }else{
      if (index > -1) {
        this.typermuserdata.splice(index, 1);
        this.displayrmlist(this.typermuserdata);
      }
    }
  }

  displayrmlist(data){
    this.totalrmparticipant_list=[];
    for(let i=0;i<this.rm_userlist.length;i++){
      for(let j=0;j<data.length;j++){
        if(this.rm_userlist[i].userid==data[j]){
          this.totalrmparticipant_list.push(this.rm_userlist[i]);
        }
      }
    }
  }

  Changeamuser(event,i){
    this.totalamparticipant_list =[];
    var value=event.target.value;
    const index = this.typeamuserdata.indexOf(value);
    if(event.target.checked){
      this.typeamuserdata.push(event.target.value);
      this.displayamlist(this.typeamuserdata);
    }else{
      if (index > -1) {
        this.typeamuserdata.splice(index, 1);
        this.displayamlist(this.typeamuserdata);
      }
    }
  }

  displayamlist(data){
    this.totalamparticipant_list=[];
    for(let i=0;i<this.am_userlist.length;i++){
      for(let j=0;j<data.length;j++){
        if(this.am_userlist[i].userid==data[j]){
          this.totalamparticipant_list.push(this.am_userlist[i]);
        }
      }
    }
  }

  backclicked(){
    this._location.back();
    // this.is_selected[LocalStorage.getValue('active_menu_training')] = "selected"
  }
  closenewrow(){
    this.addparticipantsmpin = "";
    this.is_addparticipant = false;
  }
 
  onCancel(){
    if(this.type!="mobile"){
      this.router.navigateByUrl('myschedules');
    }else{
      this.router.navigateByUrl('myschedules/' +this.type+'/'+this.userData.emailid+'/'+this.user_id);
    }
  }
  onSubmit(value){
    this.submitted = true;
    if (this.registerForm.valid) {
    var senddata = {};
    let start_date = moment(value.startdate,'YYYY-MM-DD').format("YYYY-MM-DD");
    let to_date = moment(value.startdate,'YYYY-MM-DD').format("YYYY-MM-DD");
    let today = moment(this.today,'YYYY-MM-DD').format("YYYY-MM-DD");
    let fromtime = start_date+' '+this.startTime+':00';
    let totime = to_date+' '+this.endTime+':00';
    let channel = LocalStorage.getValue('user_data').emp_code +'_'+today.replace(/-/g, "")+'_'+value.startTime.replace(/:/g, "");
    var a=this.typedsedata.concat(this.typezmuserdata,this.typermuserdata);
    senddata = {
      "title" : value.title,
      "description" : value.description,
      "fromdate" : fromtime,
      "todate" : totime,
      "channel" : channel,
      "dse" : JSON.stringify(a.concat(this.typeamuserdata))
    }
    this.loader = true;
      this.server.post("videotraining",senddata
      ).then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response == "success") {
          let msg2 = "Training scheduled successfully";
          this.confirm_pop.confirmPopups(msg2, (data) => {
            this.router.navigateByUrl('myschedules');
          }, (data)=>{
            this.router.navigateByUrl('myschedules');
          })
        }else if(data.status == 406 && data.result.response == "failed"){
          this.confirm_pop.confirmPopups(data.result.message, (data) => {
          }, (data)=>{
          })
        }else{
          this.router.navigateByUrl('');
        }
      })
   }else{
   }
  }
  isValidTraining(){
  
  }
}
