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

// full-Calendar
// import { FullCalendarComponent, CalendarOptions } from '@fullcalendar/angular';

@Component({
  selector: 'app-neweditclstraining',
  templateUrl: './neweditclstraining.component.html',
  styleUrls: ['./neweditclstraining.component.scss']
})
export class NewEditClsTrainingComponent implements OnInit {
  loader: boolean;
  trainer_welcomenote = '';
  trainer_error: string = '';
  itemdetail = [];
  is_filter: boolean = true;
  filter_year: any;
  filter_month: any;
  filter_date: any;
  selected_type: any = 1;
  date_now:any;
  sub: any;
  type: any;
  valid_pattern: string;
  type1:any;
  user_id: any;
  userData: any = {};
  setMenuId:string;
  videoitemdetail: any;
  batchitemdetail: any;
  registerForm: FormGroup;
  @ViewChild(ConfirmpopComponent) confirm_pop: ConfirmpopComponent;
  today=new Date();
  submitted: boolean;
  year = this.today.getFullYear();
  month = this.today.getMonth();
  day = this.today.getDate();
  options_start: DatepickerOptions = {
    minDate:  new Date(this.year,this.month,this.day) // Minimal selectable date
  }
  options_end: DatepickerOptions = {
    minDate:  new Date(this.year,this.month,this.day) // Minimal selectable date
  }
  rm_list: any = [];
  showdse: boolean = false;
  typermdata: any=[];
  typeamdata: any=[];
  typedealerdata: any=[];
  typedsedata: any=[];
  typezmuserdata: any=[];
  typermuserdata: any=[];
  typeamuserdata: any=[];
  totalparticipant_list = [];
  showdealer: boolean;
  showam: boolean = false;
  dealer_data: any=[];
  dse_list: any=[];
  dse_data:any =[];
  showcomment: boolean = false;
  showdealerdrop: boolean = false;
  level_list: any;
  currenttime: string;
  endtimes: any;
  startTime: any = [];
  endTime: any = [];
  public min = new Date();
  zoneam_list: any;
  zonedealer_list: any;
  correcttime = new Date().getHours()+':'+new Date().getMinutes();
  venue_address: any;
  enddate: any;
  segmentvalues:any = {};
  add_buttons : any =[];
  am_data: any = [];
  zones: any;
  zone:any;
  title_details: any;
  precheck:any;
  postcheck:any;
  show_other_text:boolean = false;
  searchvalue : any;
  status: any;
  training_day_count: any = 1;
  openpick: boolean = true;
  restrict_reason:any;
  showerror: boolean = false;
  trainingname: any;
  trainingid: any;
  schedule_id: any;
  schedule_data: any;
  participant_list: any = [];
  showselected_option: boolean =false;
  btn_text: string = 'Add Participant';
  save_btn_text : string = 'Update';
  assessmentlist: any = [];
  hideaddbtn: boolean = false;
  sendreq_params = {};
  schedule_date: string;
  showdateerror: boolean;
  reason_list: any;
  showtext: boolean;
  ques_id: string;
  ques_id_cancel: string;
  reschedule: any;
  reason:any;
  reschedule_option: any;
  startTime_index: any;
  durationTime = [];
  hideminutes = [];
  custom_reason : any;
  iscustom_error: boolean;
  totalhour :any;
  totaltimeformat: any;
  segment_id: any;
  showmodify: any;
  publish_status: any;
  constructor(private route: ActivatedRoute,private toaster: ToasterService,private _location: Location,private formBuilder : FormBuilder ,private server: HyperService, private router: Router,private atp: AmazingTimePickerService,) { }

  ngOnInit() {
    this.route.params.subscribe(params => {
      let temp = params['id'];
      this.schedule_id = temp;
    });

    this.enddate = new Date();
    this.enddate = moment(this.enddate).format('MMM DD, YYYY')
    LocalStorage.setValue('is_firsttime', false);
    this.getdetails();
    this.getbaselevel();
    this.getRmlist();
    this.getzone();
    this.getreasondata();
    this.segmentvalues = [
      {
        'type' : 'Motorcycle',
        'id' : 1
      },
      {
        'type' : 'Scooter',
        'id' : 2
      },
      {
        'type' : 'Scooter & Motorcycle',
        'id' : 3
      }
    ]
    
    this.registerForm = this.formBuilder.group({
      adhoc_training : [''],
      business_segment : ['',Validators.required],
      title: ['', Validators.required],
      othertitlename : [''],
      description: [''],
      zone : [''],
      startdate: [new Date(),Validators.required],
      enddate : [new Date(),Validators.required],
      startTime : [''],
      endTime : [''],
      venue_type : ['',Validators.required],
      venue_dealer : [''],
      venue_am : [''],
      venue_address : ['', Validators.required],
      is_feedback : [''],
      assessnamepre : [''],
      assessquescountpre : [''],
      assessTimepre : [''],
      assessnamepost : [''],
      assessquescountpost : [''],
      assessTimepost : [''],
      durationTime : [''],
      hideminutes:['']
    });
    setTimeout(()=>{
      this.setdays();
    },1000);
    this.zone = LocalStorage.getValue('user_data').zone;
    // this.registerForm.controls['zone'].setValue(this.zone);
  }

  getreasondata(){
    this.server.get("crtraining/cancelreschedulelist").then((data) => {
      if (data.status == 200 && data.result.response == "success") {
        this.reason_list= data.result.data;
      }else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  getdetails(){
    this.loader = true;
    this.server.get("crtraining/"+this.schedule_id).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        this.schedule_data= data.result.data[0];
        this.reschedule_option = this.schedule_data.reschedule_status;
        this.trainingid = this.schedule_data.lvl_id;
        this.trainingname = this.schedule_data.title;
        this.status = this.schedule_data.status;
        this.show_other_text = this.trainingid == 7 ? true : false;
        this.showmodify = this.schedule_data.training_update_status;
        this.publish_status = this.schedule_data.status;
        if(!this.showmodify && this.publish_status != 0){
          this.router.navigateByUrl('trainer');
        }
        if(this.show_other_text){
          this.registerForm.controls['othertitlename'].setValidators([Validators.required]);
          this.registerForm.controls['othertitlename'].updateValueAndValidity();
          this.registerForm.controls['description'].setValidators([Validators.required]);
          this.registerForm.controls['description'].updateValueAndValidity();
        }else{
          this.registerForm.controls['othertitlename'].clearValidators();
          this.registerForm.controls['othertitlename'].updateValueAndValidity();
          this.registerForm.controls['description'].clearValidators();
          this.registerForm.controls['description'].updateValueAndValidity();
        }
        let fromtime = JSON.parse(this.schedule_data.starttime)
        let totime = JSON.parse(this.schedule_data.endtime)
        var start =(moment(this.schedule_data.start_date).format('DD-MM-YYYY HH:mm:ss')).split(' ');
        var end =(moment(this.schedule_data.end_date).format('DD-MM-YYYY HH:mm:ss')).split(' ');
        this.registerForm.controls['title'].setValue(this.schedule_data.lvl_id)
        this.registerForm.controls['description'].setValue(this.schedule_data.schedule_name)
        this.registerForm.controls['othertitlename'].setValue(this.schedule_data.training_other_title)
        this.registerForm.controls['zone'].setValue(this.schedule_data.filter_zone);
        // this.registerForm.controls['startTime0'].setValue(fromtime[0])
        setTimeout(()=>{
          this.add_buttons.forEach(btn => {
            this.registerForm.controls['startTime'+btn.id].setValue(fromtime[btn.id])
            this.registerForm.controls['endTime'+btn.id].setValue(totime[btn.id])
            var end = moment(totime[btn.id], "HH:mm:ss");
            var start = moment(fromtime[btn.id], "HH:mm:ss")
            var duration:any = moment.duration(end.diff(start));
            var hours = '0' + parseInt(duration.asHours());
            var hideminutes = parseInt(duration.asMinutes());
            var minutes = '0' + parseInt(duration.asMinutes()) % 60;
            var durationformat = hours.slice(-2)+':'+minutes.slice(-2)
            this.registerForm.controls['durationTime'+btn.id].setValue(durationformat);
            this.registerForm.controls['hideminutes'+btn.id].setValue(hideminutes)
          });
          this.add_buttons.forEach(btn => {
            this.totalhour = this.totalhour+this.registerForm.controls['hideminutes'+btn.id].value
            var hours = (this.totalhour / 60);
            var rhours = Math.floor(hours);
            var shour = '0'+rhours;
            var minutes = (hours - rhours) * 60;
            var rminutes = Math.round(minutes);
            var sminutes = '0'+rminutes
            this.totaltimeformat = shour.slice(-2) + " : " + sminutes.slice(-2);
          });
        },1500)
       this.restrict_reason = this.schedule_data.date_restriction;
        this.registerForm.controls['venue_type'].setValue(this.schedule_data.venue_type)
        if(this.schedule_data.venue_type == 1){
          this.showcomment = false;
          this.showdealerdrop = true;
          this.getam();       
        }else{
          this.showdealerdrop = false;
          this.showcomment = true;
        }
        let venueam = this.schedule_data.venue_am;
        if(venueam !='' && venueam != undefined && venueam !=null){
          let venue = JSON.parse(venueam);
          this.registerForm.controls['venue_am'].setValue(venue[0]);
          this.getarea();
        }
        if(this.schedule_data.is_feedback == 1){
          this.registerForm.controls['is_feedback'].setValue(this.schedule_data.is_feedback)
        }
        this.registerForm.controls['venue_dealer'].setValue(this.schedule_data.venue_dealer)
        this.registerForm.controls['venue_address'].setValue(this.schedule_data.venue_address)
        this.registerForm.controls['venue_address'].setValue(this.schedule_data.venue_address)
        this.registerForm.controls['venue_address'].setValue(this.schedule_data.venue_address)
        this.registerForm.controls['startdate'].setValue(moment(this.schedule_data.start_date).format("YYYY-MM-DD"));
        this.registerForm.controls['enddate'].setValue(moment(this.schedule_data.end_date).format("YYYY-MM-DD"));
        if(this.schedule_data.adhoc_training == 1){
          this.registerForm.controls['adhoc_training'].setValue(this.schedule_data.adhoc_training);
        }
        this.registerForm.controls['business_segment'].setValue(this.schedule_data.business_segment);
        this.segment_id = this.schedule_data.business_segment;
        this.participant_list = this.schedule_data.participant;
        if(this.participant_list.length == 0){
          this.hideaddbtn = true;
          this.getRmlist();
          this.showselected_option = true;
        }else{
          this.hideaddbtn = false;
          this.showselected_option = false;
        }
        // setTimeout(()=>{
        //   this.totalhour = this.schedule_data.training_total_hours;
        // },1000)
        this.startTime=this.registerForm.controls['startTime'].value;
        this.assessmentlist = this.schedule_data.assessment;
        if(this.assessmentlist.length!=0){
          if(this.assessmentlist.length >1){
            if(this.assessmentlist[0].assessmenttype == 'pre' && this.assessmentlist[1].assessmenttype == 'Post'){
              this.precheck = 1;
              this.registerForm.controls['assessnamepre'].setValue(this.assessmentlist[0].assessmentname)
              this.registerForm.controls['assessquescountpre'].setValue(this.assessmentlist[0].total_question)
              this.registerForm.controls['assessTimepre'].setValue(this.assessmentlist[0].assessmenttime)
              this.postcheck = 2;
              this.registerForm.controls['assessnamepost'].setValue(this.assessmentlist[1].assessmentname)
              this.registerForm.controls['assessquescountpost'].setValue(this.assessmentlist[1].total_question)
              this.registerForm.controls['assessTimepost'].setValue(this.assessmentlist[1].assessmenttime)
            }
          }else{
            if(this.assessmentlist[0].assessmenttype == 'pre'){
              this.precheck = 1;
              this.registerForm.controls['assessnamepre'].setValue(this.assessmentlist[0].assessmentname)
              this.registerForm.controls['assessquescountpre'].setValue(this.assessmentlist[0].total_question)
              this.registerForm.controls['assessTimepre'].setValue(this.assessmentlist[0].assessmenttime)
            }
            else if(this.assessmentlist[0].assessmenttype == 'Post'){
              this.postcheck = 1;
              this.registerForm.controls['assessnamepre'].setValue(this.assessmentlist[0].assessmentname)
              this.registerForm.controls['assessquescountpre'].setValue(this.assessmentlist[0].total_question)
              this.registerForm.controls['assessTimepre'].setValue(this.assessmentlist[0].assessmenttime)
            }else{

            }
          }
        }
      } else if (data.result.response == "failed") {
      }
    })
  }

  getarea(){
    this.server.post("common/trainerdealer", { 'am_email' : this.schedule_data.venue_am }).then((data) => {
      if (data.status == 200 && data.result.response == "success") {
        this.zonedealer_list = data.result.data;
      } 
      else if (data.result.response == "failed" && data.status == 406) {
      }else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  enableoption(){
    this.searchvalue = '';
    if(!this.showselected_option){
      this.showselected_option = true;
      this.btn_text = 'Cancel';
    }else{
      this.showam = false;
      this.showdealer = false;
      this.showdse = false;
      this.showselected_option = false;
      this.totalparticipant_list = [];
      this.am_data = [];
      this.dealer_data = [];
      this.dse_data = [];
      this.btn_text = 'Add Participant';
    }
  }

  delete(smpin){
    this.participant_list = this.participant_list.filter((item) => item.smpin !== smpin);
    if(this.participant_list.length == 0){
      this.hideaddbtn = true;
      if(!this.showselected_option){
        this.showselected_option = true;
        this.getRmlist();
      }
    }else{
      this.hideaddbtn = false;
      this.showselected_option = false;
    }
  }

  selectreason(e){
    this.showtext = e.target.value == 6 ? true : false;
  }

  dataradio(e){
    this.showtext = false;
    this.ques_id = '';
    this.ques_id_cancel = '';
    this.custom_reason = '';
    this.iscustom_error = true;
  }

  setdays(){
    this.add_buttons = [];
    var currentDate = new Date(this.registerForm.controls['startdate'].value);
    var between = [];
    while (currentDate <=new Date(this.registerForm.controls['enddate'].value)) {
      between.push(moment(currentDate).format('MMM DD, YYYY'));
      currentDate.setDate(currentDate.getDate() + 1);
    }
    for (let i = 0; i <  between.length; i++) {
      this.add_buttons.push({
        'id' : i,
        'day' : 'Day'+' '+ (i+1),
        'date' : between[i]
      });
    }
    this.training_day_count = between.length;
    let i = 0;
    this.add_buttons.forEach(btn => {
      this.registerForm.addControl('startTime'+String(btn.id),new FormControl(this.startTime[btn.id],[Validators.required]));
      this.registerForm.addControl('endTime'+String(btn.id),new FormControl(this.endTime[btn.id],[Validators.required]));
      this.registerForm.addControl('durationTime'+String(btn.id),new FormControl(this.durationTime[btn.id]));
      this.registerForm.addControl('hideminutes'+String(btn.id),new FormControl(this.hideminutes[btn.id]));
    });
    this.showdateerror = true;
  }

  openstartclock(index){
    var today_date = this.today.getFullYear()+'/'+this.today.getMonth()+'/'+this.today.getDate();
    // var date = this.registerForm.controls['startdate'].value;
    var date = new Date(this.add_buttons[index].date);
    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'+index].setValue(this.startTime)
    });
    this.registerForm.controls['endTime'+index].setValue('');
  }

  openendclock(index){
    this.startTime_index = this.registerForm.controls['startTime'+index].value;
    if(this.startTime_index!=null && this.startTime_index!='' && this.startTime_index!=undefined){
       let a : any =this.startTime_index.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'+index].setValue(this.endTime)
          // this.startTime = (this.startTime != '' && this.startTime != undefined) ? this.startTime : this.registerForm.controls['startTime'+index].value;
          var end = moment(this.endTime, "HH:mm:ss");
          var start = moment(this.startTime_index, "HH:mm:ss")
          var duration:any = moment.duration(end.diff(start));
          var hours =  '0' + parseInt(duration.asHours());
          var hideminutes = parseInt(duration.asMinutes());
          var minutes =  '0' + parseInt(duration.asMinutes()) % 60;
          var durationformat = hours.slice(-2)+':'+minutes.slice(-2)
          this.registerForm.controls['durationTime'+index].setValue(durationformat);
          this.registerForm.controls['hideminutes'+index].setValue(hideminutes)
          this.totalhour = 0;
          this.add_buttons.forEach(btn => {
            this.totalhour = this.totalhour+this.registerForm.controls['hideminutes'+btn.id].value
            var hours = (this.totalhour / 60);
            var rhours = Math.floor(hours);
            var shour = '0'+rhours;
            var minutes = (hours - rhours) * 60;
            var rminutes = Math.round(minutes);
            var sminutes = '0'+rminutes
            this.totaltimeformat = shour.slice(-2) + " : " + sminutes.slice(-2);
          });
      });
    }else{
      this.toaster.show('Please select start time');
    }
  }

  changestartdate(tempvalue){
    this.totalhour = 0;
    this.enddate = '';
    this.openpick = true;
    this.openpick = false;
    var endDate= new Date(tempvalue);
    if(this.schedule_data.training_days != 0){
      endDate.setDate(endDate.getDate() + Number(this.schedule_data.training_days)-1);
    }else{
      endDate.setDate(endDate.getDate() + Number(this.schedule_data.training_days));
    }

    this.registerForm.get('startdate').valueChanges.subscribe((data)=>{
      this.add_buttons.forEach(btn => {
        this.registerForm.removeControl('startTime'+String(btn.id));
        this.registerForm.removeControl('endTime'+String(btn.id));
        this.registerForm.removeControl('durationTime'+String(btn.id));
        this.registerForm.removeControl('hideminutes'+String(btn.id));
      });
    })

    this.registerForm.controls['enddate'].setValue(endDate);
    this.enddate = moment(endDate).format('MMM DD, YYYY')
    this.registerForm.controls['enddate'].updateValueAndValidity();
    this.options_end={
      minDate: new Date(tempvalue)
    }
    setTimeout(() => {
      this.setdays();    
    }, 1000);
  }
 
  changeenddate(tempvalue){
    this.totalhour = 0;
    this.showdateerror = false;
    this.registerForm.get('enddate').valueChanges.subscribe((data)=>{
      this.add_buttons.forEach(btn => {
        this.registerForm.removeControl('startTime'+String(btn.id));
        this.registerForm.removeControl('endTime'+String(btn.id));
        this.registerForm.removeControl('durationTime'+String(btn.id));
        this.registerForm.removeControl('hideminutes'+String(btn.id));
      });
    })
    setTimeout(() => {
      this.setdays();    
    }, 1000);
    if(this.trainingname!='' && this.trainingname!=undefined && this.trainingname!=null){
      this.openpick = false;
    }
    this.enddate = moment(tempvalue).format('MMM DD, YYYY')
    // this.registerForm.controls['enddate'].setValue(tempvalue);
  }

  enddate_submit(){
    if(this.restrict_reason !=null && this.restrict_reason !=undefined && this.restrict_reason!='' ){
      this.showerror = false;
      this.openpick = true;
      $('#end-date-modal').modal('hide');
    }else{
      this.showerror = true;
    }
  }

  cancelend_date_modal(){
    this.showerror = false;
  }

  backclicked(){
    this._location.back();
  }

  onCancel(){
    this.router.navigateByUrl('trainer');
  }

  getRmlist(){
    this.server.post("common/trainerrm",'')
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.rm_list = data.result.data;
      }else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  getzone(){
    this.server.post("common/zone",'')
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.zones = data.result.data;
      }else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }
  
  getbaselevel(){
    this.server.get("crtraining/baselevel").then((data) => {
      if (data.status == 200 && data.result.response == "success") {
        this.level_list = data.result.data;
      } else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  changezone(e){
    this.getam();
    this.server.post("common/trainerrm",{ 'zone' : e.target.value })
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.rm_list = data.result.data;
      }
    })
  }

  Changerm(event,i,rm){
    this.typeamdata = [];
    this.typedealerdata = [];
    this.typedsedata = [];
    // this.showdealer = false;
    // this.showdse = false ;
    var senddata={};
    if(event.target.checked){
      this.typermdata.push(event.target.value);
      senddata = {"rm_email":JSON.stringify(this.typermdata),'typeid' : this.trainingid}
      this.server.post("common/traineram",senddata)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed'){
          this.showam = true;
          this.am_data.push({
            'rm_name' : rm.rm_name,
            'list' : data.result.data
          });
          this.typermdata = [];
        }else if (data.result.response == "failed" && data.status == 401) {
          this.router.navigateByUrl('');
        }else{
          this.showam =false;
          this.showdealer =false;
          this.showdse =false;
        }
      })
    }
    else{
      this.am_data.splice(this.am_data.findIndex(x=>x.rm_name == rm.rm_name),1)
      this.showam = this.am_data.length != 0 ? true : false;
      if(this.showdealer){
          this.dealer_data = this.dealer_data.filter(function(item){
          return item.rm_name != rm.rm_name 
        })
      }
      if(this.showdse){
        this.dse_data = this.dse_data.filter(function(item){
          return item.rm_name != rm.rm_name  
        })
      }
      this.showdse = this.dse_data.length == 0 ? false : true;
      this.showdealer = this.dealer_data.length == 0 ? false : true;
      if(this.totalparticipant_list.length!=0){
        this.totalparticipant_list = this.totalparticipant_list.filter(function(item){
          return item.rm_name != rm.rm_name  
        })
      }
    }         
  }
  Changeam(event,i,am,rmname){
    this.typedealerdata = [];
    this.typedsedata = [];
    // this.showdse = false;
    var senddata={};
    if(event.target.checked){
      this.typeamdata.push(event.target.value);
      senddata = {"am_email":JSON.stringify(this.typeamdata),'typeid' : this.trainingid,'segment' : this.segment_id}
      this.server.post("common/trainerdealer",senddata)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed'){
          this.showdealer = true;
          this.dealer_data.push({
            'rm_name' : rmname,
            'am_name' : am.am_name,
            'list' : data.result.data
          });
          this.typeamdata = [];
        }else if (data.result.response == "failed" && data.status == 401) {
          this.router.navigateByUrl('');
        }else{
          // this.dealer_list=[];
          this.showdealer =false;
          this.showdse =false;
        }
      })
    }else{
      this.dealer_data.splice(this.dealer_data.findIndex(x=>x.am_name == am.am_name),1)
      this.showdealer = this.dealer_data.length != 0 ? true : false;
      if(this.showdse){
        this.dse_data = this.dse_data.filter(function(item){
          return item.am_name != am.am_name 
        })
      }
      this.showdse = this.dse_data.length == 0 ? false : true;
      if(this.totalparticipant_list.length!=0){
        this.totalparticipant_list = this.totalparticipant_list.filter(function(item){
          return item.am_name != am.am_name  
        })
      }
    }
  }
  Changedealer(event,i,dealer,prev){
    this.typedsedata = [];
    var value=event.target.value;
    var senddata={};
    const index = this.typedealerdata.indexOf(value);
    if(event.target.checked){
      this.typedealerdata.push(event.target.value);
      senddata = {"dealer_code":JSON.stringify(this.typedealerdata),'typeid' : this.trainingid,'segment' : this.schedule_data.business_segment}
      this.server.post("common/dselist",senddata)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed'){
          this.showdse = true;
          this.dse_data.push({
            'am_name' : prev.am_name,
            'rm_name' : prev.rm_name,
            'dealer_name' : dealer.dealer_name,
            'dealer_code' : dealer.dealer_code,
            'list' : data.result.data
          });
          this.typedealerdata = [];
        }else if (data.result.response == "failed" && data.status == 401) {
          this.router.navigateByUrl('');
        }else{
          // this.dse_list=[];
          this.typedsedata=[];
          this.showdse =false;
        }
      })
    }else{
      this.dse_data.splice(this.dse_data.findIndex(x=>x.dealer_code == dealer.dealer_code),1)   
      this.showdse = this.dse_data.length != 0 ? true : false;

      if(this.totalparticipant_list.length!=0){
        this.totalparticipant_list = this.totalparticipant_list.filter(function(item){
          return item.dealer_code != dealer.dealer_code 
        })
      }
    }
  }

  Changedse(event,data,prev){
    // this.totalparticipant_list =[];
    var value=event.target.value;
    if(event.target.checked){
      this.totalparticipant_list.push({
        'rm_name' : prev.rm_name,
        'am_name' : prev.am_name,
        'dealer_code' : prev.dealer_code,
        'dealer_name' : prev.dealer_name,
        'id' : data.userid,
        'fname' : data.fname,
        'lname' : data.lname,
        'profile' : data.profile,
        'profile_photo' : data.profile_photo,
        'smpin' : data.smpin
      });
    }else{
      this.totalparticipant_list.splice(this.totalparticipant_list.findIndex(x=>x.id == data.userid),1)   
    }
  }

  removedse(dse){
    this.totalparticipant_list.splice(this.totalparticipant_list.findIndex(x=>x.id == dse.id),1)  
    $('.check'+dse.id).prop('checked',false) 
  }

  searchkey(){
    this.dse_data.find(function(item){
      // if(item.list.length!=0){
      //   item.list.find(function(data){
      //     if(data.smpin == this.searchvalue){

      //     }
      //   })
      // }
    })
  }

  onSearchChange(searchValue) {
    if(isNaN(searchValue)){
      this.valid_pattern="[A-Za-z]";
      this.type1 ="text";
    }else{
      this.valid_pattern="^[7-9][0-9]{9}$";
      this.type1 ="number";
    }
  }

  selectvenuetype(e){
    this.registerForm.controls['venue_dealer'].setValue('');
    this.registerForm.controls['venue_am'].setValue('');
    if(e.target.value == '1'){
      this.showcomment = false;
      this.showdealerdrop = true;
      this.getam();
      this.registerForm.controls['venue_address'].setValue('');
    }else if(e.target.value == '2'){
      this.showdealerdrop = false;
      this.showcomment = true;
      this.registerForm.controls['venue_address'].setValue('');
    }
  }

  getam(){
    this.registerForm.controls['venue_address'].setValue('');
    this.server.get("common/trainerzoneam/"+this.zone).then((data) => {
      if (data.status == 200 && data.result.response == "success") {
        this.zoneam_list = data.result.data;
      } 
      else if (data.result.response == "failed") {
      }
    })
  }

  changearea(e){
    this.loader = true;
    let obj =[];
    obj.push(e.target.value);
    this.registerForm.controls['venue_address'].setValue('');
    this.server.post("common/trainerdealer", { 'am_email' : JSON.stringify(obj) }).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        this.zonedealer_list = data.result.data;
      } 
      else if (data.result.response == "failed" && data.status == 406) {
      }
    })
  }

  selectdealer(e){
    for(let i=0;i<this.zonedealer_list.length;i++){
      if(e.target.value == this.zonedealer_list[i].dealer_code){
        this.venue_address = this.zonedealer_list[i].address; 
      }
    }
    if(this.venue_address != '' && this.venue_address != null && this.venue_address != undefined){
      this.registerForm.controls['venue_address'].setValue(this.venue_address) 
    }else{
      this.registerForm.controls['venue_address'].setValue('') 
    }
  }

  getvalue(e){
    if(e.target.checked){
      if(e.target.value == 1){
        this.registerForm.controls['assessnamepre'].setValidators([Validators.required]);
        this.registerForm.controls['assessnamepre'].updateValueAndValidity();
        this.registerForm.controls['assessquescountpre'].setValidators([Validators.required]);
        this.registerForm.controls['assessquescountpre'].updateValueAndValidity();
        this.registerForm.controls['assessTimepre'].setValidators([Validators.required]);
        this.registerForm.controls['assessTimepre'].updateValueAndValidity();
      }else if(e.target.value == 2){
        this.registerForm.controls['assessnamepost'].setValidators([Validators.required]);
        this.registerForm.controls['assessnamepost'].updateValueAndValidity();
        this.registerForm.controls['assessquescountpost'].setValidators([Validators.required]);
        this.registerForm.controls['assessquescountpost'].updateValueAndValidity();
        this.registerForm.controls['assessTimepost'].setValidators([Validators.required]);
        this.registerForm.controls['assessTimepost'].updateValueAndValidity();
      }
    }else{
      if(e.target.value == 1){
        this.registerForm.controls['assessnamepre'].clearValidators();
        this.registerForm.controls['assessnamepre'].updateValueAndValidity();
        this.registerForm.controls['assessquescountpre'].clearValidators();
        this.registerForm.controls['assessquescountpre'].updateValueAndValidity();
        this.registerForm.controls['assessTimepre'].clearValidators();
        this.registerForm.controls['assessTimepre'].updateValueAndValidity();
      }else if(e.target.value == 2){
        this.registerForm.controls['assessnamepost'].clearValidators();
        this.registerForm.controls['assessnamepost'].updateValueAndValidity();
        this.registerForm.controls['assessquescountpost'].clearValidators();
        this.registerForm.controls['assessquescountpost'].updateValueAndValidity();
        this.registerForm.controls['assessTimepost'].clearValidators();
        this.registerForm.controls['assessTimepost'].updateValueAndValidity();
      }
    }
  }

  cancelmodal(){
    $('#publish-modal').modal('hide');
  }

  onSubmit(value){
    this.submitted = true;
    if (this.registerForm.valid) {
    let assessments = [{
      "name" : value.assessnamepre,
      "ques_count" : value.assessquescountpre,
      "duration" : value.assessTimepre,
      "assessment" : "pre"
    },
    {
      "name" : value.assessnamepost,
      "ques_count" : value.assessquescountpost,
      "duration" : value.assessnamepost,
      "assessment" : "post"
    }]
    let start_date = moment(value.startdate,'YYYY-MM-DD').format("YYYY-MM-DD");
    let to_date = moment(value.enddate,'YYYY-MM-DD').format("YYYY-MM-DD");
    this.schedule_date = moment(value.startdate,'YYYY-MM-DD').format("DD-MM-YYYY");
    var am=[];
    am.push(value.venue_am)
    if(value.is_feedback == true){
      value.is_feedback = 1
    }else{
      value.is_feedback = 0
    }
    value.adhoc_training = (value.adhoc_training && value.adhoc_training!='')  ? 1 : 0;
    let start_time = [];
    let end_time = [];
    let times = 0;
    let dsedata = [];
    this.add_buttons.forEach(btn => {
      start_time.push( this.registerForm.controls['startTime'+btn.id].value)
      end_time.push( this.registerForm.controls['endTime'+btn.id].value);
      times = times+this.registerForm.controls['hideminutes'+btn.id].value
    });
    this.totalparticipant_list.forEach(list => {
      dsedata.push(list.id)
    });
    let prevdsedata = [];
    let final_dse = []
    for(let i=0;i<this.participant_list.length;i++){
      prevdsedata.push(this.participant_list[i].userid);
    }
      final_dse = dsedata.concat(prevdsedata);
    let assessment = [{
      "name" : value.assessnamepre,
      "ques_count" : value.assessquescountpre,
      "duration" : value.assessTimepre,
      "assessment" : "pre"
    },
    {
      "name" : value.assessnamepost,
      "ques_count" : value.assessquescountpost,
      "duration" : value.assessTimepost,
      "assessment" : "post"
    }]
    this.sendreq_params = {
      "title" : value.title,
      "description" : value.description,
      "startdate" : start_date,
      "enddate" : to_date,
      "starttime" : JSON.stringify(start_time),
      "endtime" : JSON.stringify(end_time),
      "is_feedback":value.is_feedback,
      "venue_type": value.venue_type,
      "venue_dealer": value.venue_dealer ,
      "venue_address" : value.venue_address,
      "assessments" : JSON.stringify(assessment),
      "dse" : JSON.stringify(final_dse),
      "venue_am" : JSON.stringify(am),
      "adhoc_training" : value.adhoc_training,
      "business_segment" : value.business_segment,
      "training_other_title" : value.othertitlename,
      "date_restriction" : this.restrict_reason,
      "status" : this.status,
      "schedule_id" : this.schedule_id,
      "filter_zone" : value.zone,
      "training_total_hours" : times
    }
    // $('#publish-modal').modal('show');
   }else{
   }
  }

  submitdata(){
    $('#publish-modal').modal('hide');
    this.loader = true;
    this.server.post("crtraining/updatetraining",this.sendreq_params
    ).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        let msg2 = "Training updated successfully";
        this.confirm_pop.confirmPopups(msg2, (data) => {
          this.router.navigateByUrl('trainer');
        }, (data)=>{
          this.router.navigateByUrl('trainer');
        })
      }else if(data.status == 406 && data.result.response == "failed"){
        this.confirm_pop.confirmPopups(data.result.message, (data) => {
        }, (data)=>{
        })
      }else{
        this.router.navigateByUrl('');
      }
    })
  }

  validate(){
    if(this.showtext){
      this.iscustom_error = (this.custom_reason != '' && this.custom_reason != undefined) ? true : false;
      return (this.custom_reason != '' && this.custom_reason != undefined)
    }else{
      return true;
    }
  }

  sendreq(){
    if(this.reason == 'cancel'){
      if(this.ques_id_cancel != null && this.ques_id_cancel != '' && this.ques_id_cancel != undefined){
        if(this.validate()){
          this.loader = true;
          this.server.get('crtraining/canceltraining/'+this.schedule_id+'/'+this.ques_id_cancel).then((res)=>{
            this.loader = false;
            if (res.status == 200 && res.result.response == "success") {
              let msg2 = "Training Cancelled";
              this.confirm_pop.confirmPopups(msg2, (data) => {
                this.router.navigateByUrl('trainer');
              }, (data)=>{
                this.router.navigateByUrl('trainer');
              })
            }else if(res.status == 406 && res.result.response == "failed"){
              this.confirm_pop.confirmPopups(res.result.message, (data) => {
              }, (data)=>{
              })
            }else{
              // alert(res.result.message);
              this.router.navigateByUrl('trainer');
            }
          })
        }
      }else{
        this.toaster.show('Please select reason for Cancel');
      }
     
    }else if(this.reason == 'reschedule'){
      if(this.ques_id != null && this.ques_id != '' && this.ques_id != undefined){
        let start_time = [];
        let end_time = [];
        let times = 0;
        let startdate = this.registerForm.controls['startdate'].value ;
        let enddate = this.registerForm.controls['enddate'].value ;
        this.add_buttons.forEach(btn => {
          start_time.push( this.registerForm.controls['startTime'+btn.id].value)
          end_time.push( this.registerForm.controls['endTime'+btn.id].value);
          times = times+this.registerForm.controls['hideminutes'+btn.id].value
        });
        let sendre_data = {
          "startdate" : moment(startdate,'YYYY-MM-DD').format("YYYY-MM-DD"),
          "enddate" : moment(enddate,'YYYY-MM-DD').format("YYYY-MM-DD"),
          "starttime" : JSON.stringify(start_time),
          "endtime" : JSON.stringify(end_time),
          "training_total_hours" : times
        }
        if(this.validate()){
          this.loader = true;
          this.server.post('crtraining/rescheduletraining/'+this.schedule_id+'/'+this.ques_id,sendre_data).then((res)=>{
            this.loader = false;
            if (res.status == 200 && res.result.response == "success") {
              let msg2 = "Training Rescheduled Successfully";
              this.confirm_pop.confirmPopups(msg2, (data) => {
                this.router.navigateByUrl('trainer');
              }, (data)=>{
                this.router.navigateByUrl('trainer');
              })
            }else if(res.status == 406 && res.result.response == "failed"){
              this.confirm_pop.confirmPopups(res.result.message, (data) => {
              }, (data)=>{
              })
            }else if (res.result.response == "failed" && res.status == 401) {
              this.router.navigateByUrl('');
            }else{
              // alert(res.result.message);
              this.router.navigateByUrl('trainer');
            }
          })
        }else{
        }
      }else{
        this.toaster.show('Please select reason for Reschedule');
      }
    }else{
      this.toaster.show('Please select Cancel or Reschedule option');
    }
  }

  isInteger(){
    $('input.dura').on('keyup', function(e) {
      if($(this).val()== '0'){
        $(this).val('')
      }
    });
  }

  restrictAlphabets(e) {
    var x = e.which || e.keycode;
    if ((x >= 48 && x <= 57))
      return true;
    else
      return false;
  }

}
