import { Component, OnInit, ViewChild, ElementRef,NgModule  } from '@angular/core';
import { HyperService } from '../../core/services/http.service';
import { Router, RouterModule, Routes, ActivatedRoute } from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { DatePipe } from '@angular/common';
import * as moment from 'moment';
import { LocalStorage } from '../../core/services/local_storage.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { DatepickerOptions } from 'ng2-datepicker';
import * as enLocale from 'date-fns/locale/en';
import { ConfirmPopupComponent } from '../../sales_executive/confirm-popup/confirm-popup.component';
// declare var $: any;
import { Subscription } from "rxjs";
import { Observable } from "rxjs/Observable";
import { Location } from '@angular/common';
import { ToasterService } from '@service/toaster.service';
import $ from 'jquery';
declare var $: $;

@Component({
  selector: 'app-add-plan',
  templateUrl: './add-plan.component.html',
  styleUrls: ['./add-plan.component.scss']
})
export class AddPlanComponent implements OnInit {

  @ViewChild(ConfirmPopupComponent) confirm_modal: ConfirmPopupComponent;


  timearr:any=[];
  totimearr:any=[];
  temp_arr:any=[];
  loader:boolean=false;
  addplanform: FormGroup;
  submittedvalue:boolean=false;
  followupdate:any='';

  options: DatepickerOptions = {
    minYear: 2020,
    maxYear: 2030,
     displayFormat: 'DD-MMM-YYYY',
     barTitleFormat: 'MMMM YYYY',
     dayNamesFormat: 'dd',
     firstCalendarDay: 0, // 0 - Sunday, 1 - Monday
     locale: enLocale,
    // minDate: new Date("Sun Dec 31 1899 17:58:53 GMT+0530 (India Standard Time)"), // Minimal selectable date
   //  minDate: new Date("Sun Dec 31 1899 17:58:53 GMT+0530 (India Standard Time)"), // Minimal selectable date
 
     minDate: new Date(Date.now()),  // Maximal selectable date
     barTitleIfEmpty: 'Click to select a date',
        
 };



  constructor(
    private server: HyperService, 
    private router: Router,
    private _eref: ElementRef,
    private route: ActivatedRoute,
    private formBuilder: FormBuilder,
    private toaster: ToasterService
    ) {
      
        
    }


  ngOnInit() {
    var date12 = new Date()
    // Add  day
    var date29 =  date12.setDate(date12.getDate())
    var date30 =  new Date(date29);
    //console.log("date30---->",date30);
    this.followupdate=date30;
    this.getcommondetails();
    this.formBuild();
    this.addplanform.controls['dateval'].setValue(date30);
  }

  formBuild() {
    this.addplanform = this.formBuilder.group({
      activity: [null, Validators.compose([Validators.required])],
      dateval: [null, Validators.compose([Validators.required])],
      description:[null, Validators.compose([Validators.required])],
      fromtime: ['', Validators.compose([Validators.required])],
      totime: ['', Validators.compose([Validators.required])]
    });
  }

  addplan(){
    this.submittedvalue=true;
    let dateval=this.followupdate;
    let d1 = new Date(dateval);
    let dateinsertion = moment(d1).format("DD-MM-YYYY");

    let ftime = this.addplanform.controls['fromtime'].value;
    let ttime = this.addplanform.controls['totime'].value;

   // let ftimeindex= this.timearr.findIndex(ftime)
  //  let ttimeindex= this.timearr.findIndex(ttime);

    if(ftime > ttime){
      // let resultvalue: any={};
      //   let result=[];
      //   resultvalue.result=[];
      //   resultvalue.result.mess='To time should be greater than from time';
      //   resultvalue.type='a';
      //  this.confirm_modal.showerrormodal(result);
      alert("To time should be greater than from time");
    }else{
    let req={
      title:this.addplanform.controls['activity'].value,
      plandate:dateinsertion,
      description:this.addplanform.controls['description'].value,
      fromtime:this.addplanform.controls['fromtime'].value,
      totime:this.addplanform.controls['totime'].value
    }
   // this.submittedvalue=false;
    if (this.addplanform.valid) {
     // console.log("valid->");
      this.server.post("enquiry/plannersave",req).then((data) => {
        if (data.status == 200 && data.result.response == "success") {
       //   console.log("data-addplan->",data);
          this.confirm_modal.showaddplansuccessModal(data);
        } else if (data.result.status == 401 && data.result.response == 'failed') {
         // this.router.navigateByUrl('');
      }else if (data.result.status == 406 && data.result.response == 'failed') {
        let result=[];
        // resultvalue.result=[];
        // resultvalue.result.mess=resultvalue.mess;
        // resultvalue.type='a';
        this.confirm_modal.showerrormodal(data);
    }
      })
      
    }else{
      //this.submittedvalue=false;
      console.log("not valid ")
      this.validateAllFormFields(this.addplanform);
    }
    }
 
  }
  getcommondetails() {
    this.loader = true;
    this.server.get("enquiry/plannertimer")
    .then((data) => {

        if (data.status == 200 && data.result.response != 'failed') {
        this.timearr=data.result.data;
        this.totimearr= data.result.data;
        this.timearr.forEach(element => {
         let titleval=element.title
        });

        
        this.loader = false;
        }else if (data.result.status == 406 ) {
              //alert(data.result.message)
        }
         else if (data.result.status == 401 && data.result.response == 'failed') {

         }
    });
  }
  selectfromtime(tempval){
   // console.log("tempval--->",tempval);
      let slicearr=[];
   this.timearr.forEach(element => {
      if(element.title_code == tempval){
        slicearr.push({'title': element.title,'title_code':element.title_code})
      }else{

      }
   });  
  }

  // selectfromtime(tempval){ 
  
  //   console.log("tempval-->", tempval);
  //   console.log("before fromtimearr-->", this.timearr);
  //   this.timearr.forEach((element, index) => {     
  //       let index_q = this.timearr.findIndex(x => x.title_code <= tempval); 
  //       this.totimearr.splice(index_q, 1);      
  //   });
  selecttotime(tempval){
 

  }

  sendtolist(tempvar){
  // console.log("tempvar----->",tempvar); 
    if(tempvar == 'list'){
      this.router.navigateByUrl('activityplanner');
    }else{
      //this.router.navigateByUrl('');
    }
  }


  validateAllFormFields(formGroup: FormGroup) {
    Object.keys(formGroup.controls).forEach(field => {
        const control = formGroup.get(field);
        if (control instanceof FormControl) {
            control.markAsTouched({
                onlySelf: true
            });
        } else if (control instanceof FormGroup) {
            this.validateAllFormFields(control);
        }
    });
  }

}
