import { Component, OnInit, ViewChild, ElementRef, NgZone, Output, EventEmitter  } from '@angular/core';
import * as moment from 'moment';
import { HyperService } from '../../core/services/http.service';
import { Router } from "@angular/router";
import { FormBuilder, FormGroup, Validators,FormControl } from '@angular/forms';
import { Subscription } from "rxjs";
import { Observable } from "rxjs/Observable";

import { DatepickerOptions } from 'ng2-datepicker';
import * as enLocale from 'date-fns/locale/en';
import { ConfirmPopupComponent } from "../../sales_executive/confirm-popup/confirm-popup.component";
import { LocalStorage } from '../../core/services/local_storage.service';
import { ToasterService } from '@service/toaster.service';
declare var $: any;

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

  @ViewChild(ConfirmPopupComponent) confirm_modal: ConfirmPopupComponent;
  
  @Output() sendCount = new EventEmitter();

  
  otpform_testride: FormGroup;
  otpform1: FormGroup;
  loader: boolean;
  is_modal_visible: boolean;
  screen_callback: any;
  is_modal_visible_create_enquiry: boolean;
  is_modal_visible_enquirylist: boolean;
  is_modal_visible_dse: boolean;
  is_modal_visible_dealer: boolean = false;
  is_modal_visible_testride: boolean = false;
  is_testride_success: boolean = false;
  model_list: any = [];
  title_list: any = [];
  company_list: any = [];
  source_list: any = [];
  profession_list: any = [];
  customertype_list: any = [];
  customerage_list: any = [];
  communication_list: any = [];
  enquiryForm: FormGroup;
  variantmodel_list: any = [];
  variantcolor_list: any = [];
  variantselected: any = {};
  sales_list: any = [];
  enquiry_list: any = [];
  timing_list: any = [];
  actionplan_list: any = [];
  purpose_list: any = [];
  start_time: any;
  inserttime: any;
  leadiidvalue: any;
  submitted: any;
  message: string;
  yearpresent: any;
  monthpresent: any;
  is_modal_visible_intitalerror: boolean = false;

  //==
  options: DatepickerOptions = {
    minYear: 2020,
   // maxYear: 2022,
    displayFormat: 'DD-MMM-YYYY',
    barTitleFormat: 'MMMM YYYY',
    dayNamesFormat: 'dd',
    firstCalendarDay: 0, // 0 - Sunday, 1 - Monday
    locale: enLocale,
    minDate: new Date(Date.now()), // Minimal selectable date
    //maxDate: new Date(Date.now()),  // Maximal selectable date
    // barTitleIfEmpty: 'Click to select a date',


  };

  options2: 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',

  };

  walletpin: string = '';
  wallet_pin: string = '';
  mpin11: any = '';
  mpin12: any = '';
  mpin13: any = '';
  mpin14: any = '';
  otp1: any = '';
  otp2: any = '';
  otp3: any = '';
  otp4: any = '';
  mpin_error: boolean = false;
  mpin_error1: boolean = false;
  isGetOtp: boolean = false;
  new_pin: boolean = false;
  isGetOtpChange: boolean = false;
  new_pin_change: boolean = false;
  resend_enable: boolean = false;
  otp: any = '';
  create_mpin: string = '';
  confirm_mpin: string = '';
  licenseno: any = '';
  licensedate: any = '';
  testrideid:any='';
  countdown: any='';
  loader_timing: any;
  loader_delay: any;
  stream$
  sub: Subscription
  mobilenoentered:any='';
  mobilenodisplay:any='';
  pagechangeurl:any='';


  constructor(
    private server: HyperService,
    private router: Router,
    private _eref: ElementRef,
    private formBuilder: FormBuilder,
    public toaster: ToasterService) {
    let today = Date.now();
    this.start_time = moment(today).format('YYYY-MM-DD hh:mm:ss');
  }

  // ngAfterViewInit() {
  //   this.message = this.confirm_modal.message
  //   alert("this.message-->"+this.message)
  //   this.is_modal_visible_create_enquiry = false;

  // }

  ngOnInit() {


   
    this.enquiryForm = this.formBuilder.group({
      titleselected: ['', Validators.required],
      fullname: ['', Validators.required],
      email: ['', Validators.required],
      companyselected: ['', Validators.required],
      communicationselected: ['', Validators.required],
      mobilenumber: ['', Validators.pattern(/^[0-9]{10,10}$/)],
      modelselected: ['', Validators.required],
      variantselected: ['', Validators.required],
      colorselected: ['', Validators.required],
      sourceselected: ['', Validators.required],
      professionselected: ['', Validators.required],
      customertypeselected: ['', Validators.required],
      customerageselected: ['', Validators.required],
      nextappointmentdate: ['', Validators.required],
      timeselected: ['', Validators.required],
      actionplanselected: ['', Validators.required],
      purposeselected: ['', Validators.required]

    });
    this.getcreateenquirydetails();
    this.formBuild();
    // this.salesdetailModal();
  }


  //==
  public salesdetailModal(url: string = "", data: any = {}, callBack: any = null) {
    //   console.log("inside sales details modal");
    this.is_modal_visible = true;
    this.loader = true;
    this.screen_callback = callBack;
    this.yearpresent = LocalStorage.getValue('temp_yr');
    this.monthpresent = LocalStorage.getValue('temp_mth');
    let smpinselectedvar = LocalStorage.getValue('setdseselected');
    //   console.log("this.yearpresent--salesdetailModal->",this.yearpresent);
    //   console.log("this.monthpresent--salesdetailModal->",this.monthpresent);
    // this.server.get("dashboard/sales/2018/05")
    this.server.get("dealerenquiry/enquirysales/" + smpinselectedvar + "/" + this.yearpresent + "/" + this.monthpresent + "")
      .then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response != 'failed') {
          this.sales_list = data.result.data;
          // console.log(this.sales_list)

        } else if (data.result.status == 406) { }
        else if (data.result.status == 401 && data.result.response == 'failed') { }
      });
  }
  //==
  public createenquiryModal(url: string = "", data: any = {}, callBack: any = null) {
    this.is_modal_visible_create_enquiry = true;
    this.screen_callback = callBack;
    this.yearpresent = LocalStorage.getValue('temp_yr');
    this.monthpresent = LocalStorage.getValue('temp_mth');
    //  console.log("this.yearpresent--salesdetailModal->",this.yearpresent);
    //  console.log("this.monthpresent--salesdetailModal->",this.monthpresent);
    // this.server.get("dashboard/sales/2018/05")
    this.server.get("dashboard/enquiry/" + this.yearpresent + "/" + this.monthpresent + "")
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed') {
          this.sales_list = data.result.data;
          // console.log(this.sales_list)

        } else if (data.result.status == 406) { }
        else if (data.result.status == 401 && data.result.response == 'failed') { }
      });

  }
  //==
  public enquirylistModal(url: string = "", data: any = {}, callBack: any = null) {
    this.is_modal_visible_enquirylist = true;
    this.loader = true;
    this.screen_callback = callBack;
    this.yearpresent = LocalStorage.getValue('temp_yr');
    this.monthpresent = LocalStorage.getValue('temp_mth');
    this.server.get("dashboard/enquiry/" + this.yearpresent + "/" + this.monthpresent + "")
      .then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response != 'failed') {
          this.enquiry_list = data.result.data;
          //  console.log(this.enquiry_list)

        } else if (data.result.status == 406) { }
        else if (data.result.status == 401 && data.result.response == 'failed') { }
      });
  }
  //==
  public showinitalfailurepop() {
    this.is_modal_visible_intitalerror = true;
  }

  //==
  public dsepopup() {
    this.is_modal_visible_dse = true;
  }
  public testridepopup(param,mobileno) {
   
    this.licenseno='';
    this.licensedate='';
    let temp1=LocalStorage.getValue('sessionstatusvalue');
    this.pagechangeurl=temp1;
    var strFirstThree = mobileno.substring(0,2);
    var strlastthree = mobileno.substring(mobileno.length-2);
    this.mobilenodisplay="XXXXXXXX"+strlastthree;
   // alert("mobileno--->"+this.mobilenodisplay)
    this.is_modal_visible_testride = true;
  //  this.formBuild();
    this.testrideid=param;
    this.TimeSet(5)
  }

  public dealererrorpopup() {
    this.is_modal_visible_dealer = true;
  }

  public oninitialCloseerrordealerModal() {
    this.is_modal_visible_dealer = false;
  }

  updatetestride(){
    let dateval = this.licensedate;
    let d1 = new Date(dateval);
    let dateinsertion = moment(d1).format("DD-MM-YYYY");
    if (this.licenseno!='' && dateinsertion!='') {

      this.server.post("enquiry/testrideupdate", {
        id: this.testrideid,
        license: this.licenseno,
        license_expiry: dateinsertion
      }).then((data) => {
        if (data.status == 200 && data.result.response == "success") {
          // this.leadiidvalue = data.result.data.id;
          // this.confirm_modal.showsuccessModal(this.leadiidvalue);
          this.is_modal_visible_testride=false;
          $('#pinModal_testride_dealer').modal('show');
         // this.toaster.show("Updated Succesfully");
        } else if (data.status == 406) {
          this.toaster.show("Updation Failed");
        }
      })
    } else {
      // alert("Invalid")
      this.toaster.show("Please enter valid license no and expiry date");
    }
  }

  ontestrideCloseModal() {
    this.is_modal_visible_testride = false;
    this.router.navigateByUrl(this.pagechangeurl);
  }



  oninitialCloseModal() {
    this.is_modal_visible_intitalerror = true;
    this.router.navigateByUrl("dashboard");
  }

  oninitialCloseTestRideModal() {
    this.is_testride_success = false;
  //  alert("this.pagechangeurl--->"+this.pagechangeurl);
   // this.router.navigateByUrl(this.pagechangeurl);
    window.location.reload();
    
  }

  inserttermsandcondition() {
    this.server.get("user/acceptleadmodule")
      .then((data) => {
        if (data.status == 200) {
          //   console.log("data in inserttermsandcondition ---->",data);
          LocalStorage.setValue('enquirymodulestatus', '1');
          this.is_modal_visible_intitalerror = false;
          LocalStorage.setValue('enquiry_pin','');
          this.sendCount.emit('reload');
         
          //this.router.navigateByUrl('dealer-myenquiries');
        } else if (data.result.status == 401 && data.result.response == 'failed') {
          this.router.navigateByUrl('');
        }
      });
  }

  onCloseModal() {
    this.is_modal_visible = false;
    this.is_modal_visible_create_enquiry = false;
    this.is_modal_visible_enquirylist = false;
    this.is_modal_visible_dse = false;
    this.screen_callback(true);
    this.is_modal_visible_dealer = false;
    this.is_testride_success = false;
  }
  //==
  getcreateenquirydetails() {
    this.server.get("enquiry/common")
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
          this.model_list = data.result.data.model;
          this.title_list = data.result.data.title;
          this.company_list = data.result.data.company;
          this.communication_list = data.result.data.communicate;
          this.source_list = data.result.data.source;
          this.purpose_list = data.result.data.purpose;
          this.actionplan_list = data.result.data.modeofcontact;
          this.timing_list = data.result.data.time;
          this.customerage_list = data.result.data.custage;
          this.customertype_list = data.result.data.custtype;
          this.profession_list = data.result.data.profession;

          this.variantmodel_list = [];
        } else if (data.result.status == 401 && data.result.response == 'failed') {
          this.router.navigateByUrl('');
        }
      });
  }
  //==
  onChangeModel(ev) {
    // this.variantcolor_list=[];
    this.variantmodel_list = [];
    this.variantcolor_list = [];
    //  this.enquiryForm.controls['colorselected'].setValue('');

    // console.log(this.enquiryForm.controls['variantselected'].setValue(''))
    let temp = this.model_list.filter(data => data.title_code === ev);
    //console.log(temp);
    //this.enquiryForm.controls['variantselected'].setValue('');
    //temp.push()
    let select_temp = temp[0].variant;
    // select_temp["key3"] = "value3";
    //  console.log(select_temp);
    this.variantmodel_list = select_temp;

    //this.enquiryForm.controls['variantselected'].setValue('');
  }
  //==
  onChangeVariant(ev) {
    this.variantcolor_list = [];
    let temp1 = this.variantmodel_list.filter(data => data.title_code === ev);
    this.variantcolor_list = temp1[0].color;
  }


  //==
  onSubmit(req) {
    // alert("FFFF")
    this.submitted = true
    // console.log(req)

    if (this.enquiryForm.valid) {
      this.inserttime = moment(this.enquiryForm.controls['nextappointmentdate'].value).format('DD-MM-YYYY');

      this.server.post("enquiry", {
        mobile: this.enquiryForm.controls['mobilenumber'].value,
        buyer_type: '1',
        title: this.enquiryForm.controls['titleselected'].value,
        first_name: this.enquiryForm.controls['fullname'].value,
        company: this.enquiryForm.controls['companyselected'].value,
        communicate: this.enquiryForm.controls['communicationselected'].value,
        newvechicledate: this.inserttime,
        newvechicletime: this.enquiryForm.controls['timeselected'].value,
        newvechicletactionplan: this.enquiryForm.controls['actionplanselected'].value,
        newvechicletpurpose: this.enquiryForm.controls['purposeselected'].value,
        oldvechicledate: '',
        oldvechicletime: '',
        oldvechicletactionplan: '',
        oldvechicletpurpose: '',
        model1: this.enquiryForm.controls['modelselected'].value,
        variant1: this.enquiryForm.controls['variantselected'].value,
        color1: this.enquiryForm.controls['colorselected'].value,
        model2: '',
        variant2: '',
        color2: '',
        oldvechiclemaker: '',
        oldvechiclemodel: '',
        profession: this.enquiryForm.controls['professionselected'].value,
        source: this.enquiryForm.controls['sourceselected'].value,
        custtype: this.enquiryForm.controls['customertypeselected'].value,
        custage: this.enquiryForm.controls['customerageselected'].value
      }).then((data) => {
        if (data.status == 200 && data.result.response == "success") {
          this.leadiidvalue = data.result.data.id;
          this.confirm_modal.showsuccessModal(this.leadiidvalue);
        } else if (data.status == 406) {

        }
      })
    } else {
      //alert("Invalid")
    }
  }
  //==


  //==
  onSubmitOtp(param) {
    // console.log("param--->",param);
   //  alert("2344555");
    this.walletpin = (this.mpin11.toString()) + (this.mpin12.toString()) + (this.mpin13.toString()) + (this.mpin14.toString());

    console.log("walletpin", this.walletpin)
    console.log(this.otpform_testride)
    if (this.otpform_testride.valid) {
      this.mpin_error = false;
      this.mpin_error1 = false;
      this.loader = true
      this.server.post("enquiry/testrideotp", { id: this.testrideid, otp: this.walletpin })
        .then((data) => {
          console.log(data)
          if (data.status == 200 && data.result.response == 'success') {
          //  alert("333");
            this.loader = false;
            $('#pinModal_testride_dealer').modal('hide');
            this.is_testride_success = true;
          } else if (data.result.status == 401 && data.result.response == 'failed') {
            // this.router.navigateByUrl('');
          } else if (data.result.response == "failed") {
            this.mpin_error = true;
            this.mpin_error1 = false;
            // this.mpin_error1 =  data.result.message;
          }
        })


    } else {
      this.mpin_error1 = true;
      this.mpin_error = false;
      this.validateAllFormFields(this.otpform_testride);
    }
  }
  //==
  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);
      }
    });
  }
  //==
  onInputChange() {
    $('input.password').on('keyup', function (e) {
      if ($(this).val() != '' && e.keyCode != 8) {
        if ($(this).val()) {
          $(this).next().focus();
        }
      } else {
        if (e.keyCode == 8) {
          // console.log($(this).val(),"$(this).val()sdf")
          $(this).prev().focus();
        }
      }

    });
  }
  //==
  formBuild() {
    this.otpform_testride = this.formBuilder.group({
      mpin11: ['', Validators.compose([Validators.required])],
      mpin12: ['', Validators.compose([Validators.required])],
      mpin13: ['', Validators.compose([Validators.required])],
      mpin14: ['', Validators.compose([Validators.required])]
    });
  }
  // formBuildOtp() {
  //   this.otpform1 = this.formBuilder.group({
  //     otp1: [null, Validators.compose([Validators.required])],
  //     otp2: [null, Validators.compose([Validators.required])],
  //     otp3: [null, Validators.compose([Validators.required])],
  //     otp4: [null, Validators.compose([Validators.required])]
  //   });
  // }

  TimeSet(Time) {
    this.loader_timing = Time * 60;
    this.loader_delay = this.loader_timing / 2;
    const interval = 1000;
    const duration = 10 * 6000 * Time;
    this.stream$ = Observable.timer(0, interval)
      .finally(() => this.onclose())
      .takeUntil(Observable.timer(duration + interval))
      .map(value => duration - value * interval);
    this.sub = this.stream$.subscribe(value => this.formatMin(value));
  }
  onclose() {
    this.countdown = ''
    this.resend_enable = true;

  }
  formatMin(s) {
    let ms = s % 1000;
    s = (s - ms) / 1000;
    let secs = s % 60;

    s = (s - secs) / 60;
    let mins = s % 60;
    let hrs = (s - mins) / 60;
    if (hrs > 0) {
      this.countdown = hrs + ':' + mins + ':' + secs;
    } else {
      this.countdown = mins + ':' + secs;
    }
  }
  resendotp(){
    //alert("333")
      this.updatetestride();
      this.TimeSet(5);
  }

  onfailureModal(){
    this.toaster.show("Updation Failed");
  }

}

