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-newcreateclstraining',
  templateUrl: './newcreateclstraining.component.html',
  styleUrls: ['./newcreateclstraining.component.scss']
})
export class NewCreateClsTrainingComponent 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;
  // times = {
  //   year: 31557600,
  //   month: 2629746,
  //   day: 86400,
  //   hr: 3600,
  //   min: 60,
  //   sec: 1
  // }
  sub: any;
  type: any;
  valid_pattern: string;
  type1:any;
  user_id: any;
  userData: any = {};
  setMenuId:string;
  videoitemdetail: any;
  batchitemdetail: any;
  registerForm: FormGroup;
  // calendarOptions: CalendarOptions = {
  //   initialView: 'dayGridMonth'
  // };
  @ViewChild(ConfirmpopComponent) confirm_pop: ConfirmpopComponent;
  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_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_date: any;
  sendreq_params = {};
  btn_text: any;
  Opened = true;
  showdateerror: boolean;
  selected_end_date: any;
  timing=[];
  duration=[];
  hideminutes = [];
  titlechanged: boolean = false;
  totalhour:any = 0;
  training_title_id: any;
  assessmentdata: any;
  segment_id: any;
  clicktitle:boolean = true;
  clickzone:boolean = true;
  resetfieldname: string;
  totaltimeformat: any;
  disableform = true;
  seg_show: boolean = false;
  showt_titlebtn1: boolean;
  showt_titlebtn2: boolean;
  showt_titlebtn3: boolean;
  constructor(private route: ActivatedRoute,private toaster: ToasterService,private _location: Location,private formBuilder : FormBuilder ,private server: HyperService, private router: Router,private atp: AmazingTimePickerService,) { }

  ngOnInit() {
    this.enddate = new Date();
    this.enddate = moment(this.enddate).format('MMM DD, YYYY')
    LocalStorage.setValue('is_firsttime', false);
    this.getbaselevel();
    this.getRmlist();
    this.getzone();
    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 : ['', Validators.required],
      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 : [true],
      assessnamepre : [''],
      assessquescountpre : [''],
      assessTimepre : [''],
      assessnamepost : [''],
      assessquescountpost : [''],
      assessTimepost : [''],
      duration : ['']
    });
    setTimeout(()=>{
      this.setdays();
    },1000);
    this.zone = LocalStorage.getValue('user_data').zone;
    this.registerForm.controls['zone'].setValue(this.zone);
    this.clickzone = false;
  }

  changesegment(e,index){
    if(index == '1'){
      this.segment_id = e.target.value;
    }else{
      this.segment_id = e;
    }
    this.seg_show = true;
    this.disableform = false;
    this.getassessment();
    this.showam = false;
    this.showdealer = false;
    this.showdse = false;
    this.totalparticipant_list = [];
    this.am_data = [];
    this.dealer_data = [];
    this.dse_data = [];
    this.getRmlist();
    LocalStorage.setValue('beforeselect_segment',this.segment_id)
    LocalStorage.setValue('afterselect_segment','')
  }

  changetitle(e){
    // if(this.training_title_id != undefined || this.training_title_id != ''){
    //   $('#reset-modal').modal('show');
    // }else{
    this.clicktitle = false;
    this.totalhour = 0;
    this.titlechanged = true;
    this.preassement(false);
    this.postassement(false);    
    // this.openpick = false;
    this.showam = false;
    this.showdealer = false;
    this.showdse = false;
    this.totalparticipant_list = [];
    this.am_data = [];
    this.dealer_data = [];
    this.dse_data = [];
    this.precheck = '';
    this.postcheck = '';
    // $(".pre").prop("disabled", false);
    // $(".post").prop("disabled", false);
    this.getRmlist();

    this.add_buttons.forEach(btn => {
      this.registerForm.removeControl('startTime'+String(btn.id));
      this.registerForm.removeControl('endTime'+String(btn.id));
      this.registerForm.removeControl('duration'+String(btn.id));
      this.registerForm.removeControl('hideminutes'+String(btn.id));
    });

    this.level_list.forEach(level => {
      if(level.lvl_id == e.target.value){
        this.trainingname = level.lvl_name;
        this.trainingid = e.target.value;
      }
    });
    this.show_other_text = e.target.value == 7 ? true : false;
    this.openpick = e.target.value ==7 ? true : false;
    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();
    }
    for(let i=0;i<this.level_list.length;i++){
      if(e.target.value == this.level_list[i].lvl_id){
        this.title_details = this.level_list[i];
      }
    }    
    this.training_title_id = e.target.value;
    if(this.title_details!=''&&this.title_details!=undefined){
      this.training_day_count = this.title_details.training_days; 
      var currentDate = new Date();
      currentDate.setDate(currentDate.getDate() + Number(this.title_details.training_gap_days));
      this.registerForm.controls['startdate'].setValue(currentDate);
      var endDate= new Date(this.registerForm.controls['startdate'].value);
      if(this.title_details.training_days != 0){
        endDate.setDate(endDate.getDate() + Number(this.title_details.training_days)-1);
      }else{
        endDate.setDate(endDate.getDate() + Number(this.title_details.training_days));
      }
      this.registerForm.controls['enddate'].setValue(endDate);
      this.enddate = moment(endDate).format('MMM DD, YYYY')
      this.selected_end_date = endDate;
      this.registerForm.controls['enddate'].updateValueAndValidity();
      setTimeout(() => {
        this.setdays();
      }, 1000);
      let assess_data = this.title_details.assessment_values.split(',');
        if(assess_data[0]!=''){
          this.precheck = assess_data[0];
          // $(".pre").prop("disabled", true);
          this.preassement(true);
        }
      if(assess_data.length == 2){
        this.postcheck = assess_data[1];
        // $(".post").prop("disabled", true);
        this.postassement(true);
      }
    }
    this.getassessment();
  //}
  }

  getassessment(){
    this.segment_id = this.registerForm.controls['business_segment'].value;
    if(this.segment_id !='' && this.segment_id !=null && this.segment_id != undefined){
      this.server.get("crtraining/getassessmentnames/"+this.training_title_id+"/"+this.segment_id).then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response == "success") {
          this.assessmentdata = data.result.data;
          this.assessmentdata.pre !='' && this.assessmentdata.pre != undefined && this.assessmentdata.pre != null ? this.registerForm.controls['assessnamepre'].setValue(this.assessmentdata.pre) :  this.registerForm.controls['assessnamepre'].setValue('');
          this.assessmentdata.post !='' && this.assessmentdata.post != undefined && this.assessmentdata.post != null ? this.registerForm.controls['assessnamepost'].setValue(this.assessmentdata.post) :  this.registerForm.controls['assessnamepost'].setValue('');
        } else if (data.result.response == "failed" && data.status == 401) {
          this.router.navigateByUrl('');
        }
      })
    }
  }

  setdays(){
    this.add_buttons = [];
    var between = [];
    var currentDate = new Date(this.registerForm.controls['startdate'].value);
    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('duration'+String(btn.id),new FormControl( this.duration[btn.id]));
      this.registerForm.addControl('hideminutes'+String(btn.id),new FormControl( this.hideminutes[btn.id]));
    });
    this.showdateerror = true;

    this.registerForm.updateValueAndValidity();
  }

  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 = this.registerForm.controls['startTime'+index].value;
    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'+index].setValue(this.endTime)
          var end = moment(this.endTime, "HH:mm:ss");
          var start = moment(this.startTime, "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['duration'+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 = '';
    if(this.titlechanged){
      if(this.training_title_id == 7){
        this.openpick == true;
      }else{
        this.openpick = false;
      }
    }else{
      this.openpick = true;
    }
    // this.openpick = this.titlechanged ? false : true;
    var endDate= new Date(tempvalue);
    if(this.title_details != undefined && this.title_details != ''){
      if(this.title_details.training_days != 0){
        endDate.setDate(endDate.getDate() + Number(this.title_details.training_days)-1);
      }else{
        endDate.setDate(endDate.getDate() + Number(this.title_details.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('duration'+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.selected_end_date = endDate;
    this.registerForm.controls['enddate'].updateValueAndValidity();

    // this.registerForm.controls['enddate'].setValue(tempvalue);
    this.options_end={
      minDate: new Date(tempvalue)
    } 
    setTimeout(() => {
      this.setdays();    
    }, 1000);
  }
 
  changeenddate(tempvalue){
    this.totalhour = 0;
    this.enddate = '';
    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('duration'+String(btn.id));
        this.registerForm.removeControl('hideminutes'+String(btn.id));
      });
    })
    
    if(this.trainingname!='' && this.trainingname!=undefined && this.trainingname!=null){
      this.openpick = false;
    }
    
    this.enddate = moment(tempvalue).format('MMM DD, YYYY')
    this.selected_end_date = tempvalue;

    setTimeout(() => {
      this.setdays();    
    }, 1000);
    // 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) => {
      this.loader = false;
      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.clickzone = false;
    this.zone = e.target.value;
    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;
        this.showam = false;
        this.am_data = [];
        this.showdealer = false;
        this.dealer_data = [];
        this.showdse = false;
        this.dse_data = [];
        this.totalparticipant_list = [];
      }else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  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.segment_id}
      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) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        this.zoneam_list = data.result.data;
      } 
      else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  changearea(e){
    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 == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  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.preassement(true)
      }else if(e.target.value == 2){
        this.postassement(true)
      }
    }else{
      if(e.target.value == 1){
        this.preassement(false)

      }else if(e.target.value == 2){
        this.postassement(false)
      }
    }
  }

  preassement(val){
    if(val){
      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{
      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();
    }
  }

  postassement(val){
    if(val){
      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{
      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();
    }
  }

  onsave(val,text){
    this.status = val;
    this.btn_text = text;
  }
  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.assessTimepost,
      "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,'DD-MM-YYYY').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)
    });
    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(assessments),
      "dse" : JSON.stringify(dsedata),
      "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,
      "filter_zone" : this.zone,
      "training_total_hours" : times
    }
    $('#publish-modal').modal('show'); 
   }else{
   }
  }

  submitdata(){
    $('#publish-modal').modal('hide');
    this.loader = true;
    this.server.post("crtraining",this.sendreq_params
    ).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('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('');
      }
    })
  }

  isInteger(){
    // return e.key == '0' ? false : true; 
    // if (e.key == 0 && String.fromCharCode(e.which) == '0') {
    //   return false
    // }
    $('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;
  }

  okdata(){
    this.clicktitle = true;
    $('#reset-modal').modal('hide');
  }

  okzonedata(){
    this.clickzone = true;
    $('#reset-modal').modal('hide');
  }

  oksegdata(){
    // this.seg_show = false;
    $('#reset-modal').modal('hide');
    this.registerForm.controls['business_segment'].setValue(LocalStorage.getValue('afterselect_segment'));
    this.changesegment(LocalStorage.getValue('afterselect_segment'),'2');
  }

  openreset(val){
    $('#reset-modal').modal('show');
    this.resetfieldname = val == '1' ? 'Training Title' : val == '2' ? 'Zone' :  val == '3' ? 'Segment' : '';
    if(val == 1){
      this.showt_titlebtn1 = true;
      this.showt_titlebtn2 = false;
      this.showt_titlebtn3 = false;
    }else if(val == 2){
      this.showt_titlebtn2 = true;
      this.showt_titlebtn1 = false;
      this.showt_titlebtn3 = false;
    }else{
      this.showt_titlebtn3 = true;
      this.showt_titlebtn1 = false;
      this.showt_titlebtn2 = false;
    }
  }

  openseg(e){
    LocalStorage.setValue('afterselect_segment' , e.target.value);
    this.openreset('3');
  }

  onseg_cancel(){
    this.registerForm.controls['business_segment'].setValue(LocalStorage.getValue('beforeselect_segment'))
  }
}
