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-hoaddtraining',
  templateUrl: './hoaddtraining.component.html',
  styleUrls: ['./hoaddtraining.component.scss']
})
export class AddHoTrainingComponent 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=[];
  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();
  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=[];
  startdate:any=new Date();
  role_list: any = [];
  roleuserlist: any = [];
  role: any;
  selected_title: string;
  rolermlist: any;
  showrm: boolean;
  selecteduserid: any;
  showzmrm: boolean;
  showzmam: boolean;
  showzmdealer: boolean;
  roleamlist: any[];
  roledealerlist: any;
  role_selected: string;
  // 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(selected_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],
      role: ['', Validators.required],
      role_selected : ['', 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();
  }

  check_role_login(){
    if(this.user_role == 3){
      this.getRolelist();
    }
  }

  getRolelist(){
    this.server.get("videotraining/role")
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.role_list = data.result.data;
      }else{
        this.role_list=[];
      }
    })
  }

  changerole(data){
    this.showrm = false;
    this.showam = false;
    this.showdealer = false;
    this.showdse = false;
    this.showzmrm = false;
    this.showzmam = false;
    this.showzmdealer = false;
    this.totalparticipant_list = [];
    this.role = data;
    this.role_selected = '';
    if(this.role == 5 || this.role == 4){
      this.server.post("videotraining/getroleuser",{ role : data })
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed'){
          this.roleuserlist = data.result.data;
        }else{
          this.roleuserlist=[];
        }
      })
    }else{
      this.server.post("videotraining/getroleuser",{ role : '4' })
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed'){
          this.roleuserlist = data.result.data;
        }else{
          this.roleuserlist=[];
        }
      })
    }
  }

  changezm(value){
    let data = [];
    data.push(value);
    this.showam = false;
    this.showzmam = false;
    this.showzmdealer = false;
    this.showdealer = false;
    this.showdse = false;
    this.totalparticipant_list = [];
    this.server.post("videotraining/rmlist",{ value : JSON.stringify(data), role : this.role })
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.rm_list = data.result.data;
        this.showrm = true;
      }else{
        this.rm_list=[];
        this.showrm = false;
      }
    })
    this.getuserid(value);
  }

  getuserid(email){
    for(let i=0;i<this.roleuserlist.length;i++){
      if(this.roleuserlist[i].value == email){
        this.selecteduserid = this.roleuserlist[i].userid;
      }
    }
  }

  changezmsecond(value){
    let data = [];
    data.push(value);
    this.showam =false;
    this.showdealer =false;
    this.showzmam = false;
    this.showzmdealer = false;
    this.showdse =false;
    this.totalparticipant_list = [];
    let senddata = {"value":JSON.stringify(data) , "role" : this.role}
      this.server.post("videotraining/rmlist",senddata)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed'){
          this.showzmrm = true;
          this.rolermlist = data.result.data;
          // this.participant_data = data.result.data.participant;
        }else{
          this.rolermlist=[];
          this.showzmrm =false;
          this.showdealer =false;
          this.showdse =false;
        }
      })
    this.getuserid(value);
  }

  changezmrm(value){
    this.showdealer = false;
    this.showdse = false;
    this.showzmdealer = false;
    this.totalparticipant_list =[];
    this.getamlist(value);
  }

  getamlist(data){
    let value = [];
    value.push(data);
    let senddata = {"value" : JSON.stringify(value) , "role" : this.role}
      this.server.post("videotraining/amlist",senddata)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed'){
          if(this.role == 6){
            this.showam = true;
            this.am_list =  data.result.data;
          }else if(this.role == 7 || this.role == 14){
            this.showzmam = true;
            this.roleamlist = data.result.data;
          }
          // this.participant_data = data.result.data.participant;
        }else{
          this.roleamlist=[];
          this.am_list =[];
          this.showzmam = false;
          this.showam =false;
          this.showdealer =false;
          this.showdse =false;
        }
      })
  }
  changezmam(value){
    let data = [];
    data.push(value);
    this.showdse = false;
    this.totalparticipant_list =[];
    let senddata = {"value":JSON.stringify(data), "role" : this.role}
      this.server.post("videotraining/dealerlist",senddata)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed'){
          if(this.role == 7){
            // rm
            this.showdealer = true;
            this.dealer_list = data.result.data;
          }else if(this.role == 14){
            this.roledealerlist = data.result.data;
            this.showzmdealer = true;
          }
        }else{
          this.dealer_list=[];
          this.roledealerlist=[];
          this.showdealer =false;
          this.showzmdealer = false;
          this.showdse =false;
        }
      })
  }

  changezmdealer(value){
    this.showdse = true;
    let data = [];
    this.totalparticipant_list =[];
    data.push(value);
      let senddata = {"dealer_code":JSON.stringify(data)}
        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;
          }
      })
  }

  changetrainer(value){
   this.changezm(value)
  }

  getTrainingtypelist(){
    this.server.get("videotraining/traininglist")
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed'){
          this.training_type = data.result.data;
        }
    })
  }

  typeChange(type){
    this.trainingtitle = type;
    if(type=='none'){
      this.showtextbox = true;
    }else{
      this.showtextbox = false;
    }
  }
  Changerm(event){
    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 = {"value":JSON.stringify(this.typermdata) , "role" : this.role}
    this.server.post("videotraining/amlist",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){
    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 = {"value":JSON.stringify(this.typeamdata), "role" : this.role}
    this.server.post("videotraining/dealerlist",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){
    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;
    var senddata={};
    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;
  }

  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('ilearning');
    }
  }
  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, "");
    senddata = {
      "userid" : this.selecteduserid,
      "title" : value.title,
      "description" : value.description,
      "fromdate" : fromtime,
      "todate" : totime,
      "channel" : channel,
      "dse" : JSON.stringify(this.typedsedata),
      "role" : this.role
    }
    this.loader = true;
      this.server.post("videotraining/addtraining",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('ilearning');
          }, (data)=>{
            this.router.navigateByUrl('ilearning');
          })
        }else if(data.status == 406 && data.result.response == "failed"){
          alert(data.result.message)
        }else{
          this.router.navigateByUrl('');
        }
      })
   }else{
   }
  }
}
