import { Component, OnInit, ViewChild, ElementRef, NgModule } from '@angular/core';
import { HyperService } from '../../core/services/http.service';
import { Router, NavigationEnd, RoutesRecognized } 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 { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { View, EventSettingsModel, DayService, WeekService, WorkWeekService, MonthService, ResizeService, DragAndDropService, PopupOpenEventArgs, DragEventArgs, ResizeEventArgs, ActionEventArgs, EventRenderedArgs, ScheduleComponent } from '@syncfusion/ej2-angular-schedule';
import { ChangeArgs } from '@syncfusion/ej2-buttons';
import { ToasterService } from '@service/toaster.service';
import { enableRipple } from '@syncfusion/ej2-base';
import { TaskstatusDealerComponent } from "../taskstatus-dealer/taskstatus-dealer.component";
import { ConfirmPopupComponent } from '../../sales_executive/confirm-popup/confirm-popup.component';
import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';
import { send } from 'q';
import { CONFIG } from '../../config';
import { filter, pairwise } from 'rxjs/operators';
import $ from 'jquery';
import * as enLocale from 'date-fns/locale/en';
declare var $: $;

@Component({
  selector: 'app-activitydaylist-dealer',
  templateUrl: './activitydaylist-dealer.component.html',
  styleUrls: ['./activitydaylist-dealer.component.scss']
})
export class ActivitydaylistDealerComponent implements OnInit {
  // @ViewChild(TaskstatusDealerComponent) taskmodal: TaskstatusDealerComponent;
  @ViewChild(ConfirmPopupComponent) confirm_modal: ConfirmPopupComponent;
  todaylist: any = [];
  id_date: any;
  date_value: any;
  is_edit: boolean = false;
  edit_value: any;

  timearr: any = [];
  loader: boolean = false;
  addplanform: FormGroup;
  submittedvalue: boolean = false;
  followupdate: any = '';
  description_edit:any;
  fromtime_edit:any;
  totime_edit:any;
  activity_edit:any;
  delete_value:any;
  smpinselected:any='';
  smpinselectedname:any='';
  
  constructor(private route: ActivatedRoute, public toaster: ToasterService, private formBuilder: FormBuilder, private server: HyperService, private router: Router, public elm: ElementRef, private sanitizer: DomSanitizer) { }
  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',

  };
  ngOnInit() {
    this.formBuild();
    this.smpinselectedname=LocalStorage.getValue('setdseselectedname');
   // this.getcommondetails();
    this.route.params.subscribe(params => {
      this.id_date = params['id'];
    //  console.log(" given_date ", JSON.stringify(this.id_date))
    });
    let date_value = LocalStorage.getValue('activity_day_list');

    let dateval = date_value.EndTime;
  //  console.log('dateval-->', dateval)
  //  console.log('activity_day_listdate', this.date_value)

    let d1 = new Date(dateval);
    this.date_value = moment(d1).format("YYYY-MM-DD");

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

    this.activitylist();

  }





  activitylist() {
    let smpinvalue=LocalStorage.getValue('setdseselected')
    this.smpinselected = smpinvalue


    this.todaylist = '';
    let req = {
      type: 'date',
      month: '',
      year: '',
      date: this.date_value
    }
    this.server.post("dealerenquiry/plannerlist/"+this.smpinselected, req).then((data) => {
      if (data.status == 200 && data.result.response == "success") {
      //  console.log("data-getmonthlist->", data.result.data.date);
        this.todaylist = data.result.data.date;


        // this.setvaluecal(this.totalcalenderlist)
      } else if (data.result.response == "failed" && data.status == 401) {

      }
    })
  }
  back() {
    this.is_edit = false;
  }
  sendtolist(tempvar){
  //  console.log("tempvar----->",tempvar); 
     if(tempvar == 'list'){
      this.activitylist(); 
     }else{
       //this.router.navigateByUrl('');
     }
   }
  deletetoday(item_id){
    this.delete_value = this.todaylist.find(element => element.id == item_id.id);
    this.confirm_modal.deleterowmodal(item_id.id)
  }
  edittoday(item_id) {
  //  console.log("edit-->", item_id.id)
    this.edit_value = this.todaylist.find(element => element.id == item_id.id);
    this.is_edit = true;
  //  console.log("edit-->", this.edit_value)
    this.activity_edit=this.edit_value.plan_title;
    this.description_edit=this.edit_value.plan_description;
    this.fromtime_edit=this.edit_value.fromtime;
    this.totime_edit=this.edit_value.totime;
    let plandate=this.edit_value.plan_date

    // this.followupdate = this.edit_value.plandate
    // console.log("followupdate-->",this.followupdate)

    // this.followupdate = {
    //   "year": 2018,
    //   "month": 8,
    //   "day": 15
    // }
    // this.addplanform.get('dateval').setValue({
    //   year: parseInt(this.followupdate.format('YYYY'), 10),
    //   month: parseInt(this.followupdate.format('M'), 10),
    //   day: parseInt(this.followupdate.format('D'), 10)
    // });
    //var date12 = new Date()
   // console.log("date12",date12)
    //var date29 =  date12.setDate(date12.getDate())
    var date30 =  new Date(plandate);
    this.addplanform.controls['dateval'].setValue(date30);
  //  console.log("this.addplanform.controls['dateval'].setValue(date30)",this.addplanform.controls['dateval'].value)
   // console.log("followupdate-->", 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])]
    });
  }

  updateplan(){
  ///  console.log(this.addplanform.controls['dateval'].value);
    this.submittedvalue=true; 
    let dateval=this.followupdate;
    let d1 = new Date(dateval);
    let dateinsertion = moment(d1).format("DD-MM-YYYY");
    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/plannerupdate/"+this.edit_value.id,req).then((data) => {
        if (data.status == 200 && data.result.response == "success") {
     //     console.log("data-addplan->",data);
          this.confirm_modal.showaddplansuccessModal(data);
          this.is_edit = false;
        } 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);
    }
  }

  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);
        }
    });
  }
  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.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') {

         }
    });
  }
}
