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 { EnquirypopupDealerComponent } from '../enquirypopup-dealer/enquirypopup-dealer.component';
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';
import 'rxjs/add/observable/combineLatest';
declare var $: $;

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

  loader: boolean;
  stream$
  displaystockval: any = '';
  sub: Subscription
  buyertypearr: any = [];
  communicatearr: any = [];
  actionplanarr: any = [];
  companyarr: any = [];
  custagearr: any = [];
  custtypearr: any = [];
  modelarr: any = [];
  modeofcontactarr: any = [];
  professionarr: any = [];
  purposearr: any = [];
  sourcearr: any = [];
  timearr: any = [];
  titlearr: any = [];
  genderarr: any = [];
  enquiryform: FormGroup;
  otpform: FormGroup;
  followupdate: any = '';
  variantarr: any = [];
  sharebrouchereboolean: boolean = false;
  colorarr: any = [];
  verifiednumber: boolean = false;
  submittedvalue: boolean = false;
  othersdisplay: boolean = false;
  broucheredisplay: boolean = false;
  page_per_size: number = 10;
  current_page: number;
  total_page: number;
  activeItem: number = -1;
  activePage: number = 1;
  page_count: number;
  countdown: any;
  ngtitleemail: any = '';
  mpin1: any = '';
  mpin2: any = '';
  mpin3: any = '';
  mpin4: any = '';
  otp1: any = '';
  otp2: any = '';
  otp3: any = '';
  otp4: any = '';
  keyword = 'title';
  loader_timing: any;
  loader_delay: any;
  mpin_error: boolean = false;
  mpin_error1: boolean = false;
  resend_enable: boolean = false;
  walletpin: string = '';
  wallet_pin: string = '';
  pin_error: boolean = false;
  is_exist: any = '';
  otp_expiry: any = '';
  back_value: any = '';
  modelselected: any = '';
  variantselected: any = '';
  colorselected: any = '';
  smpinselected: any = '';
  setsmpin: any = '';
  companytypeng: any = '';
  selecteddse: any = '';
  enquirydata: any = '';
  enquiryvariant: any = '';
  newvechicledate: any = '';
  mobilenodisplay: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',

  };
  //===
  options2: DatepickerOptions = {
    minYear: 2020,
    maxYear: 2050,
    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',

  };
  testdrivestatus: any = '';
  licensedate: any = '';
  licenseno: any = '';
  displaylicense: boolean = false;
  tervaluelicense:any='';


  @ViewChild(ConfirmPopupComponent) confirm_modal: ConfirmPopupComponent;
  @ViewChild(EnquirypopupDealerComponent) content_modal: EnquirypopupDealerComponent;
  constructor(
    private server: HyperService,
    private router: Router,
    private _eref: ElementRef,
    private route: ActivatedRoute,
    private formBuilder: FormBuilder,
    private toaster: ToasterService
  ) {


  }

  ngOnInit() {

    this.formBuild();
    this.assigndefault();
    this.formbuildmodel();


    let spin = '';
    this.server.get("dealer/userlist/0/1")
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed') {
          this.setsmpin = data.result.data;
          spin = data.result.data[0].smpin;
          // spin.push({smpin:'select',fname:'Select',lname:''})
          // this.setsmpin.unshift({ smpin: '', fname: 'Select', lname: '' })
          this.loader = false;
        } else if (data.result.status == 406) {
          //alert(data.result.message)
        }
        else if (data.result.status == 401 && data.result.response == 'failed') {

        }
      });


    LocalStorage.setValue('routerpath', 'createenquiry');


    // this.getcommondetails();
    var date12 = new Date()
    // Add a day
    var date29 = date12.setDate(date12.getDate() + 1)
    var date30 = new Date(date29);
    this.followupdate = date30;


    this.loader = true;
    this.broucheredisplay = false;

    let smpinvalue = LocalStorage.getValue("setdseselected");
    // alert("smpinvalue--->"+smpinvalue)
    if ((smpinvalue != '') && (smpinvalue != undefined) && (smpinvalue != null)&& (smpinvalue != 'all')) {

      this.smpinselected = smpinvalue;
      this.selecteddse = this.smpinselected;
      this.enquiryform.controls['selecteddsefrm'].setValue(this.selecteddse);
      //  alert("33-->"+smpinvalue)
      this.selectdse()
      this.enquiryform.controls['followupdatefm'].setValue(date30);
      this.enquiryform.controls['timeval'].setValue('10:00');
    } else {
      this.smpinselected = '';
      this.selecteddse='';
      this.enquiryform.controls['firsttimebuyer'].setValue('');
      this.enquiryform.controls['titletype'].setValue('');
      this.enquiryform.controls['customertype'].setValue('');
    }



    
    this.route.params.subscribe(params => {
      this.back_value = params['back'];
      if (this.back_value == 'back') {
        let returnvalue = LocalStorage.getValue('req');
           console.log('returnvalue--->', returnvalue)
        this.verifiednumber = returnvalue.mobileverification;
        this.enquiryform.controls['firsttimebuyer'].setValue(returnvalue.buyer_type);
        this.enquiryform.controls['surname'].setValue(returnvalue.surname);
        this.enquiryform.controls['titletype'].setValue(returnvalue.title);
        this.enquiryform.controls['titlename'].setValue(returnvalue.first_name);
        this.enquiryform.controls['titleemail'].setValue(returnvalue.email);
        this.enquiryform.controls['companytype'].setValue(returnvalue.company);
        this.enquiryform.controls['communicatetype'].setValue(returnvalue.communicate);
        this.enquiryform.controls['mobileno'].setValue(returnvalue.mobile);
        this.modelselected = returnvalue.model1;
        this.variantselected = returnvalue.variant1;
        this.colorselected = returnvalue.color1;




        // alert(returnvalue.custtype)
        this.enquiryform.controls['customertype'].setValue(returnvalue.custtype);
        this.enquiryform.controls['customerprofession'].setValue(returnvalue.profession);
        this.enquiryform.controls['customerage'].setValue(returnvalue.custage);
        //this.enquiryform.controls['followupdatefm'].setValue(date30);
        let ret=returnvalue.newvechicledate;
        var datefollowup =  new Date(ret);
        console.log("datefollowup-->"+datefollowup)
        this.followupdate=datefollowup;


        this.enquiryform.controls['timeval'].setValue(returnvalue.newvechicletime);
        this.enquiryform.controls['actionplan'].setValue(returnvalue.newvechicletactionplan);
        this.enquiryform.controls['purpose'].setValue(returnvalue.newvechicletpurpose);
        this.enquiryform.controls['genderval'].setValue(returnvalue.gender);
        this.enquiryform.controls['address1'].setValue(returnvalue.address1);
        this.enquiryform.controls['sourceval'].setValue(returnvalue.source);
        this.enquiryform.controls['others'].setValue(returnvalue.work_place_name);

        this.licenseno = returnvalue.license;
        let dateupdate = returnvalue.license_expiry;
        if((this.licenseno !='')&&(dateupdate !='')){
          this.testdrivestatus='1';
          this.tervaluelicense='1';
          this.displaylicense=true;         
          var date30 =  new Date(dateupdate);
          console.log("date30---->",date30);
          this.licensedate = date30;
          console.log("this.licensedate---->",this.licensedate);
        }else{
          this.tervaluelicense='0';
          this.testdrivestatus='0';
        }



      } else if (this.back_value == 'non-sync') {
        let returnvalue = LocalStorage.getValue('non-syncenquiry');
        this.verifiednumber = returnvalue.mobileverification;
        this.enquiryform.controls['firsttimebuyer'].setValue(returnvalue.buyer_type);
        this.enquiryform.controls['titletype'].setValue(returnvalue.title);
        this.enquiryform.controls['titlename'].setValue(returnvalue.first_name);
        this.enquiryform.controls['surname'].setValue(returnvalue.surname);
        this.enquiryform.controls['titleemail'].setValue(returnvalue.email);
        this.enquiryform.controls['companytype'].setValue(returnvalue.company);
        this.enquiryform.controls['communicatetype'].setValue(returnvalue.communicate);
        this.enquiryform.controls['mobileno'].setValue(returnvalue.mobile);
        this.enquiryform.controls['modeltype'].setValue(returnvalue.model1);
        this.enquiryform.controls['varianttype'].setValue(returnvalue.variant1);
        this.enquiryform.controls['colorval'].setValue(returnvalue.color1);
        setTimeout(() => {
          this.selectmodel(0);
        }, 100);

        setTimeout(() => {
          this.selectvariant(0);
        }, 200);

        setTimeout(() => {
          this.selectcolor();
        }, 300);

        this.enquiryform.controls['customertype'].setValue(returnvalue.custtype);
        this.enquiryform.controls['customerprofession'].setValue(returnvalue.profession);
        this.enquiryform.controls['customerage'].setValue(returnvalue.custage);
        this.enquiryform.controls['followupdatefm'].setValue(date30);
        this.enquiryform.controls['timeval'].setValue(returnvalue.newvechicletime);
        this.enquiryform.controls['actionplan'].setValue(returnvalue.newvechicletactionplan);
        this.enquiryform.controls['purpose'].setValue(returnvalue.newvechicletpurpose);
        this.enquiryform.controls['genderval'].setValue(returnvalue.gender);
        this.enquiryform.controls['address1'].setValue(returnvalue.address1);
        this.enquiryform.controls['sourceval'].setValue(returnvalue.source);
        this.enquiryform.controls['others'].setValue(returnvalue.work_place_name);

      } else {
        //  alert("this.selecteddse--->"+this.selecteddse);
           if(this.selecteddse !=''){
            this.enquiryform.controls['firsttimebuyer'].setValue('03');
            this.enquiryform.controls['titletype'].setValue('MR');
            this.enquiryform.controls['customertype'].setValue('I');
           }
        

      }
    })


    // this.getcommondetails();

  }


  getcommondetails() {
    // alert("33")
    this.loader = true;
    this.server.get("dealerenquiry/common/" + this.smpinselected)
      .then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response != 'failed') {
          this.buyertypearr = data.result.data.buyertype;
          this.communicatearr = data.result.data.communicate;
          this.actionplanarr = data.result.data.actionplan;
          this.companyarr = data.result.data.company;
          this.custagearr = data.result.data.custage;
          this.custtypearr = data.result.data.custtype;
          this.modelarr = data.result.data.model;
          this.modeofcontactarr = data.result.data.modeofcontact;
          this.professionarr = data.result.data.profession;
          this.purposearr = data.result.data.purpose;
          this.sourcearr = data.result.data.source;
          this.timearr = data.result.data.time;
          this.titlearr = data.result.data.title;
          this.genderarr = data.result.data.gender;

          // alert("this.back_value-->"+this.back_value)
           if((this.back_value ==undefined)||(this.back_value =='')){
            this.enquiryform.controls['firsttimebuyer'].setValue('03');
            this.enquiryform.controls['titletype'].setValue('MR');
            this.enquiryform.controls['customertype'].setValue('I');
           }

          if (this.modelselected != '' && this.modelselected != undefined) {
            this.selectmodel(0)
          }
          // console.log("this.companyarr--->",this.companyarr)
          // this.companyarr.forEach((element,index) => {
          //   if(element.title_code=='OT'){
          //     this.companyarr[index].title_code='000';
          //   }
          // });

          if (this.modelselected != '' && this.modelselected != undefined && this.variantselected != '' && this.variantselected != undefined) {
            this.selectvariant(0)
          }
          setTimeout(() => {
            $('.selectpicker').selectpicker('refresh');
          }, 1000);
          this.loader = false;
        } else if (data.result.status == 406) {
          //alert(data.result.message)
        }
        else if (data.result.status == 401 && data.result.response == 'failed') {

        }
      });
  }


  resetlist() {
    if (this.back_value != 'back') {
      this.buyertypearr = [];
      this.communicatearr = [];
      this.actionplanarr = [];
      this.companyarr = [];
      this.custagearr = [];
      this.custtypearr = [];
      this.modelarr = [];
      this.modeofcontactarr = [];
      this.professionarr = [];
      this.purposearr = [];
      this.sourcearr = [];
      this.timearr = [];
      this.titlearr = [];
      this.variantarr = [];
      this.genderarr = [];
    }
  }
  //==
  formBuild() {
    this.enquiryform = this.formBuilder.group({
      firsttimebuyer: [null, Validators.compose([Validators.required])],
      titletype: [null, Validators.compose([Validators.required])],
      modeltype: [null, Validators.compose([Validators.required])],
      companytype: [null, Validators.compose([Validators.required])],
      communicatetype: [null, Validators.compose([Validators.required])],
      customertype: [null, Validators.compose([Validators.required])],
      customerage: [null, Validators.compose([Validators.required])],
      customerprofession: [null, Validators.compose([Validators.required])],
      purpose: [null, Validators.compose([Validators.required])],
      timeval: [null, Validators.compose([Validators.required])],
      sourceval: [null, Validators.compose([Validators.required])],
      actionplan: [null, Validators.compose([Validators.required])],
      titlename: [null, Validators.compose([Validators.required])],
      titleemail: [null],
      mobileno: [null, Validators.compose([Validators.required, Validators.minLength(10)])],
      varianttype: [null, Validators.compose([Validators.required])],
      colorval: [null, Validators.compose([Validators.required])],
      followupdatefm: [null],
      surname: [null],
      // followupdatefm:[null, Validators.compose([Validators.required])],
      genderval: [null, Validators.compose([Validators.required])],
      address1: [null],
      others: [''],
      selecteddsefrm: ['']
    });
  }
  //==
  formbuildmodel() {
    this.otpform = this.formBuilder.group({
      mpin1: [null, Validators.compose([Validators.required])],
      mpin2: [null, Validators.compose([Validators.required])],
      mpin3: [null, Validators.compose([Validators.required])],
      mpin4: [null, Validators.compose([Validators.required])]
    });
  }

  assigndefault() {
    this.enquiryform.controls['firsttimebuyer'].setValue('');
    this.enquiryform.controls['titletype'].setValue('');
    this.enquiryform.controls['titlename'].setValue('');
    this.enquiryform.controls['titleemail'].setValue('');
    this.enquiryform.controls['companytype'].setValue('');
    this.enquiryform.controls['communicatetype'].setValue('');
    this.enquiryform.controls['mobileno'].setValue('');
    this.enquiryform.controls['modeltype'].setValue('');
    this.enquiryform.controls['varianttype'].setValue('');
    this.enquiryform.controls['colorval'].setValue('');
    this.enquiryform.controls['customerprofession'].setValue('');
    this.enquiryform.controls['customertype'].setValue('');
    this.enquiryform.controls['customerage'].setValue('');
    this.enquiryform.controls['followupdatefm'].setValue('');
    this.enquiryform.controls['timeval'].setValue('');
    this.enquiryform.controls['actionplan'].setValue('');
    this.enquiryform.controls['purpose'].setValue('');
    this.enquiryform.controls['surname'].setValue('');
    this.enquiryform.controls['genderval'].setValue('');
    this.enquiryform.controls['address1'].setValue('');
    this.enquiryform.controls['sourceval'].setValue('');
  }

  selectmodel(val) {
    this.displaystockval = '';
    if (val == 1) {
      this.enquiryform.controls['varianttype'].setValue('');
      this.enquiryform.controls['colorval'].setValue('');
    }


    let rest = this.modelselected;
    //  console.log("modelarr-->", this.modelarr)
    //   console.log("rest==>", rest)
    const found = this.modelarr.find(element => element.title_code == rest);
    //  console.log("found==>", found)
    let variantvalue = found.variant;
    //  console.log("variantvalue==>", variantvalue)
    this.variantarr = variantvalue;
    // this.colorarr = [];
  }
  //==
  selectvariant(val) {
    if (val == 1) {
      this.enquiryform.controls['colorval'].setValue('');
    }

    this.displaystockval = ''
    let rest = this.modelselected;
    let rest1 = this.variantselected;
    const found = this.modelarr.find(element => element.title_code == rest);
    let variantvalue = found.variant;
    const found1 = variantvalue.find(element => element.title_code == rest1);
    let variantvalue1 = found1.color;
    this.colorarr = variantvalue1;
    //  console.log("this.variantselected==>", this.variantselected);
    //  console.log("this.colorselected==>", this.colorselected);

    // this.enquiryform.controls['colorval'].setValue('');
  }
  //==
  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);
      }
    });
  }
  //==


  //==
  createenquiry() {
    var flaglicense = '';
    var licensedatevalue = '';
    if ((this.selecteddse == '') || (this.selecteddse == undefined) || (this.selecteddse == null)) {
      this.content_modal.dealererrorpopup();
    } else {
      this.submittedvalue = true;
      //  console.log("followupdatefm-->", this.followupdate)
      // return false;
      if (this.enquiryform.valid) {
        //  console.log("valid ");
        if (this.verifiednumber == true) {


          let dateval = this.followupdate;
          let d1 = new Date(dateval);
          let dateinsertion = moment(d1).format("DD-MM-YYYY");
          console.log("testdrivestatus--->",this.testdrivestatus);
          if ((this.tervaluelicense == '1')||(this.tervaluelicense == '0')) {
            console.log("this.licenseno---->", this.licenseno);
            console.log("this.licensedate---->", this.licensedate);


            if(this.tervaluelicense =='1'){
            if ((this.licenseno != '') && (this.licensedate != '')) {
              flaglicense = '1';
              let dateval1 = this.licensedate;
              let d11 = new Date(dateval1);
              licensedatevalue = moment(d11).format("DD-MM-YYYY");

            } else {
              licensedatevalue = '';
              this.licenseno = '';
              flaglicense = '0';
              // this.toaster.show('Please enter the License details');
              // return false;
            }
          } else {
            flaglicense = '1';
          }
          console.log("flaglicense---->", flaglicense);
          if (flaglicense == '1') {


            let req = {
              mobile: this.enquiryform.controls['mobileno'].value,
              mobileverification: this.verifiednumber,
              buyer_type: this.enquiryform.controls['firsttimebuyer'].value,
              title: this.enquiryform.controls['titletype'].value,
              gender: this.enquiryform.controls['genderval'].value,
              first_name: this.enquiryform.controls['titlename'].value,
              email: this.enquiryform.controls['titleemail'].value,
              address1: this.enquiryform.controls['address1'].value,
              company: this.enquiryform.controls['companytype'].value,
              communicate: this.enquiryform.controls['communicatetype'].value,
              model1: this.enquiryform.controls['modeltype'].value,
              variant1: this.enquiryform.controls['varianttype'].value,
              color1: this.enquiryform.controls['colorval'].value,
              source: this.enquiryform.controls['sourceval'].value,
              profession: this.enquiryform.controls['customerprofession'].value,
              custtype: this.enquiryform.controls['customertype'].value,
              custage: this.enquiryform.controls['customerage'].value,
              newvechicledate: dateinsertion,
              last_name: this.enquiryform.controls['surname'].value,
              newvechicletime: this.enquiryform.controls['timeval'].value,
              newvechicletactionplan: this.enquiryform.controls['actionplan'].value,
              newvechicletpurpose: this.enquiryform.controls['purpose'].value,
              work_place_name: this.enquiryform.controls['others'].value,
              license_expiry: licensedatevalue,
              license: this.licenseno

            }
            // console.log("req-->",req);
            // return false;

            this.server.post("dealerenquiry/enquirysubmit/" + this.smpinselected, req).then((data) => {
              if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                this.confirm_modal.showsuccessModal(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.toaster.show('Please enter the License details');
            return false;
          }
          } else {
            this.toaster.show('Please select Test Ride given');
            return false;
          }
        } else {
          this.toaster.show('Mobile Number should be verified before submission');
          return false;
        }

      } else {
        console.log("not valid ")
        this.validateAllFormFields(this.enquiryform);
      }
    }
  }
  closeenquiry() {
    //alert("3");
    this.router.navigateByUrl('dealer-myenquiries');
  }
  sendotp() {
    let req = {
      mobile: ''
    }
    this.server.post("enquiry/otp", req).then((data) => {
      if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {

      } 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);
      }
    });
  }
  //==
  verifyotp() {
    //  alert("this.smpinselected---->"+this.smpinselected);
    let req = {
      mobile: '',
      otp: ''
    }
    this.server.post("dealerenquiry/otpvalidate/" + this.smpinselected + "", req).then((data) => {
      if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
        //  this.resend_enable = 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);
      }
    });
  }
  //==
  public selectcolor() {
    this.displaystockval = ''
    let req = {
      model: this.enquiryform.controls['modeltype'].value,
      variant: this.enquiryform.controls['varianttype'].value,
      color: this.enquiryform.controls['colorval'].value
    }
    this.server.post("dealerenquiry/stockavailability/" + this.smpinselected + "", req).then((data) => {
      if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
        // console.log("verifyvariant--->",data)

        this.displaystockval = data.result.data.status;
      } 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);
      }
    });
  }
  //==
  selectcommunicationtype(event) {

  }
  //==
  // selectcompany(event) {
  //   let selectedcompany = this.enquiryform.controls['companytype'].value;
  //   // console.log("selected:", selectedcompany);
  //   if (selectedcompany == 'OT') {
  //     this.othersdisplay = true;
  //   } else {
  //     this.othersdisplay = false;
  //   }
  // }

  selectcompany() {
    // alert("selectcompany--->"+this.companytypeng);
    let selectedcompany = this.enquiryform.controls['companytype'].value;
    // // console.log("selected:", selectedcompany);
    if (selectedcompany == 'OT') {
      this.othersdisplay = true;
    } else {
      this.othersdisplay = false;
    }
  }
  //==
  selecttitle(event) {

  }
  //==
  selectenquirytype(event) {

  }
  //==
  selectcustomertype(event) {
    let selectedcompany = this.enquiryform.controls['companytype'].value;
    // // console.log("selected:", selectedcompany);
    if (selectedcompany == 'OT') {
      this.othersdisplay = true;
    } else {
      this.othersdisplay = false;
    }
  }
  //==
  selectgender(event) {

  }
  //==
  selectcustomerprofession(event) {

  }
  //==
  selectcustomerage(event) {

  }
  //===
  selecttime(event) {

  }
  //
  selectactionplan(event) {

  }

  customSearchFn(term: string, item) {
    return item.title.toLowerCase().startsWith(term.toLowerCase());
  }
  onChangeSearch(event) {

  }
  selectEvent(event) {
    //  console.log("event--->",this.companytypeng)

  }
  onFocused(event) {

  }
  //==
  sendtolist(tempvar) {

    if (tempvar == 'list') {
      this.router.navigateByUrl('dealer-myenquiries');
    } else {

    }
  }

  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();
        }
      }

    });
  }
  //==

  onClickCancel() {
    //alert("onSubmitOtp-->");
    this.resend_enable = false;
    this.sub.unsubscribe()
    this.sub = this.stream$.subscribe(0, this.formatMin(0));
    $('#pinModal').modal('hide');
  }
  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;
    }
  }
  onSubmitOtp() {
    // alert("222")
    this.mpin_error = false;
    this.mpin_error1 = false;
    this.resend_enable = false;
    this.walletpin = (this.mpin1.toString()) + (this.mpin2.toString()) + (this.mpin3.toString()) + (this.mpin4.toString());
    if (this.otpform.valid) {
      //  if(this.walletpin==this.wallet_pin){
      this.mpin_error = false;
      this.mpin_error1 = false;
      // this.loader = true
      this.server.post("dealerenquiry/otpvalidate/" + this.smpinselected + "", {
        otp: this.walletpin,
        mobile: this.enquiryform.controls['mobileno'].value
      })
        .then((data) => {
          //  console.log(data)
          if (data.status == 200 && data.result.response == 'success') {
            //   this.loader = false;
            this.verifiednumber = true;
            $('#pinModal').modal('hide');
          } else if (data.result.status == 401 && data.result.response == 'failed') {
            this.router.navigateByUrl('');
            this.verifiednumber = false;
          } else if (data.result.status == 406 && data.result.response == "failed") {
            //  $('#pinModal').modal('show');
            this.verifiednumber = false;
            this.mpin_error = true;
            this.mpin_error1 = false;
            // this.mpin_error1 =  data.result.message;
          }
        })
      // }else{
      //     this.mpin_error=true;
      //     this.mpin_error1=false;
      // }
      //  $('#pinModal').modal('hide');      
    } else {
      this.mpin_error1 = true;
      this.mpin_error = false;
      this.validateAllFormFields(this.otpform);
    }

    //  this.router.navigateByUrl('myenquiries');
  }

  //==
  openotpmodal() {
    this.formbuildmodel();
  }
  sendmobileotp() {

    this.mpin_error1 = false;
    this.mpin_error = false;


    this.otp1 = '';
    this.otp2 = '';
    this.otp3 = '';
    this.otp4 = '';


    this.mpin1 = '';
    this.mpin2 = '';
    this.mpin3 = '';
    this.mpin4 = '';

    let mobileexists: any = '';

    let textvalue: any = '';

    let ret = this.enquiryform.controls['mobileno'].value
    //const usingSpread = [...ret];
    const usingArrayFrom = Array.from(ret);
    // console.log("usingSpread---->", usingArrayFrom);
    this.resend_enable = false;

    this.verifiednumber = false;
    if (this.enquiryform.controls['mobileno'].value == '') {
      // alert("Please enter a ");
      this.toaster.show('Please enter a mobile number');
    } else if (usingArrayFrom.length != 10) {
      this.toaster.show('Please enter 10 digit mobile number');
    } else {
      let mobilenosend=this.enquiryform.controls['mobileno'].value 
    var strFirstThree = mobilenosend.substring(0,2);
    var strlastthree = mobilenosend.substring(mobilenosend.length-2);
    this.mobilenodisplay=strFirstThree+"XXXXXX"+strlastthree;
      let req = {
        mobile: this.enquiryform.controls['mobileno'].value
      }
      this.server.post("dealerenquiry/otp/" + this.smpinselected + "", req)
        .then((data) => {
          if (data.status == 200 && data.result.response == 'success') {
            mobileexists = data.result.data.mobile_exist;
            this.otp_expiry = data.result.data.otp_expiry;
            if (mobileexists == '1') {
              //alert("if");
              textvalue = data.result.data.enq_data;
              this.enquirydata = data.result.data.enq_data.model;
              this.enquiryvariant = data.result.data.enq_data.variant;
              this.newvechicledate = data.result.data.enq_data.newvechicledate;



              $('#mobileexists-modal').modal('show');
            } else {
              //alert("else");
              $('#pinModal').modal('show');
              this.TimeSet(this.otp_expiry)
            }

            // console.log("this.otp_expiry--->",this.otp_expiry)

            //  console.log(this.otp_expiry)
          } else if (data.result.status == 401 && data.result.response == 'failed') {
            this.router.navigateByUrl('');
          }
        })
    }

  }
  //==
  resendOtp() {
    this.resend_enable = false;
    this.sendmobileotp();
  }
  quotation_details() {

    LocalStorage.setValue('quote_emi_quote', '');
    let temp = '0';
    var regExp = /^([\w\.\+]{1,})([^\W])(@)([\w]{1,})(\.[\w]{1,})+$/;
    let tempvalue = this.enquiryform.controls['titleemail'].value;
    let titlename = this.enquiryform.controls['titlename'].value;
    let surname = this.enquiryform.controls['surname'].value;
    let modeltype = this.modelselected;
    let varianttype = this.variantselected;
    let mobileno = this.enquiryform.controls['mobileno'].value;
    let colorval = this.colorselected;
    let dse = this.selecteddse;

    //====For Coming Back ====

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


    let dateval1 = this.licensedate;
      let d11 = new Date(dateval1);
      var licensedatevalue='';
      licensedatevalue = moment(d11).format("YYYY-MM-DD");


    let req = {
      mobile: this.enquiryform.controls['mobileno'].value,
      mobileverification: this.verifiednumber,
      buyer_type: this.enquiryform.controls['firsttimebuyer'].value,
      title: this.enquiryform.controls['titletype'].value,
      gender: this.enquiryform.controls['genderval'].value,
      first_name: this.enquiryform.controls['titlename'].value,
      surname: this.enquiryform.controls['surname'].value,
      email: this.enquiryform.controls['titleemail'].value,
      address1: this.enquiryform.controls['address1'].value,
      company: this.enquiryform.controls['companytype'].value,
      communicate: this.enquiryform.controls['communicatetype'].value,
      model1: this.enquiryform.controls['modeltype'].value,
      variant1: this.enquiryform.controls['varianttype'].value,
      color1: this.enquiryform.controls['colorval'].value,
      source: this.enquiryform.controls['sourceval'].value,
      profession: this.enquiryform.controls['customerprofession'].value,
      custtype: this.enquiryform.controls['customertype'].value,
      custage: this.enquiryform.controls['customerage'].value,
      newvechicledate: dateinsertion,
      newvechicletime: this.enquiryform.controls['timeval'].value,
      newvechicletactionplan: this.enquiryform.controls['actionplan'].value,
      newvechicletpurpose: this.enquiryform.controls['purpose'].value,
      work_place_name: this.enquiryform.controls['others'].value,
      dse: this.enquiryform.controls['selecteddsefrm'].value,
      license_expiry:licensedatevalue,
      license:this.licenseno

    }
    LocalStorage.setValue('req', req);


    //    console.log("modeltype--->",modeltype)
    //    console.log("varianttype--->",varianttype)
    //   console.log("colorval--->",colorval)



    //    console.log('-->', regExp.test(tempvalue));
    if (tempvalue == '' || titlename == '' || modeltype == '' || varianttype == '' || colorval == '' || mobileno == '') {
      temp = '1';
    } else if (regExp.test(tempvalue) == false) {
      temp = '2';
    } else if (mobileno.length < 10) {
      temp = '3';
    } else if (this.selecteddse == '') {
      temp = '4';
    }
    else {
      temp = '0';
    }


    if (temp == '1') {
      this.toaster.show('Please enter name, contact no, email, model, variant, color');
    } else if (temp == '2') {
      this.toaster.show('Please provide a valid email');
    }
    else if (temp == '3') {
      this.toaster.show('Please enter 10 digit mobile number');
    }
    else if (temp == '4') {
      this.toaster.show('Please select DSE');
    }
    else if (temp == '0') {

      LocalStorage.setValue('currenturl', 'create-enquiry');
      LocalStorage.setValue('tempvalue', tempvalue);
      LocalStorage.setValue('surname', surname);
      LocalStorage.setValue('titlename', titlename);
      LocalStorage.setValue('mobileno', mobileno);
      LocalStorage.setValue('modeltype', modeltype);
      LocalStorage.setValue('varianttype', varianttype);
      LocalStorage.setValue('colorval', colorval);
      LocalStorage.setValue('dse', dse);


      this.router.navigate(['/dealer-quotation/data']);
    }
    else {

    }

  }



  emi_details() {
    let temp = '0';
    let modeltype = this.enquiryform.controls['modeltype'].value;
    let varianttype = this.enquiryform.controls['varianttype'].value;
    let colorval = this.enquiryform.controls['colorval'].value;

    let regexp = new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
    if ((modeltype == '') || (varianttype == '') || (colorval == '')) {
      // returns true if working locally
      temp = '1';
    } else {
      temp = '0';
    }
    if (temp == '1') {
      this.toaster.show('Please select model,variant,color');
    } else {
      LocalStorage.setValue('currenturl', 'create-enquiry');
      LocalStorage.setValue('modeltype', modeltype);
      LocalStorage.setValue('varianttype', varianttype);
      LocalStorage.setValue('colorval', colorval);
      LocalStorage.setValue('check_path', 'dealer-emi-calculator')

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

      let dateval1 = this.licensedate;
      let d11 = new Date(dateval1);
      var licensedatevalue='';
      licensedatevalue = moment(d11).format("YYYY-MM-DD");

      

      let req = {
        mobile: this.enquiryform.controls['mobileno'].value,
        mobileverification: this.verifiednumber,
        buyer_type: this.enquiryform.controls['firsttimebuyer'].value,
        title: this.enquiryform.controls['titletype'].value,
        gender: this.enquiryform.controls['genderval'].value,
        first_name: this.enquiryform.controls['titlename'].value,
        surname: this.enquiryform.controls['surname'].value,
        email: this.enquiryform.controls['titleemail'].value,
        address1: this.enquiryform.controls['address1'].value,
        company: this.enquiryform.controls['companytype'].value,
        communicate: this.enquiryform.controls['communicatetype'].value,
        model1: this.enquiryform.controls['modeltype'].value,
        variant1: this.enquiryform.controls['varianttype'].value,
        color1: this.enquiryform.controls['colorval'].value,
        source: this.enquiryform.controls['sourceval'].value,
        profession: this.enquiryform.controls['customerprofession'].value,
        custtype: this.enquiryform.controls['customertype'].value,
        custage: this.enquiryform.controls['customerage'].value,
        newvechicledate: dateinsertion,
        newvechicletime: this.enquiryform.controls['timeval'].value,
        newvechicletactionplan: this.enquiryform.controls['actionplan'].value,
        newvechicletpurpose: this.enquiryform.controls['purpose'].value,
        work_place_name: this.enquiryform.controls['others'].value,
        license_expiry:licensedatevalue,
        license:this.licenseno
  
      }

      LocalStorage.setValue('req', req)



      this.router.navigate(['/dealer-emi-calculator/web']);


    }
  }
  sharebrochure() {
    let temp = '0';
    let tempvalue = this.enquiryform.controls['titleemail'].value;
    let titlename = this.enquiryform.controls['titlename'].value;
    let modeltype = this.enquiryform.controls['modeltype'].value;
    let varianttype = this.enquiryform.controls['varianttype'].value;
    let regexp = new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
    if ((tempvalue.match(regexp)) || (titlename == '') || (modeltype == '') || (varianttype == '')) {
      // returns true if working locally
      temp = '1';
    } else {
      temp = '0';
    }

    if (tempvalue == '') {
      this.toaster.show('Please enter email,name,model,variant');
    } else if (temp == '0') {
      this.toaster.show('Please enter valid email');
    } else {
      this.server.post("dealerenquiry/sharebrochure/" + this.smpinselected + "", {
        email: tempvalue,
        name: titlename,
        model: modeltype,
        variant: varianttype
      })
        .then((data) => {
          $("#enquiry-modal").modal('hide');
          if (data.status == 200) {
            //   console.log("data-->", data);
            this.toaster.show(data.result.message);
          } else if (data.result.status == 406) {
            this.toaster.show(data.result.message);
          } else if (data.result.status == 404) {
            let result = [];
            // resultvalue.result=[];
            // resultvalue.result.mess=resultvalue.mess;
            // resultvalue.type='a';
            this.confirm_modal.showerrormodal(data);
          } else if (data.result.status == 401 && data.result.response == 'failed') { }
        });
    }

  }
  public onPageChange(event) {
    this.activeItem = -1;
    this.activePage = event;
    //  console.log('pagech', this.activePage)
  }
  //==
  public getServerData(event) {
    //  console.log(event)
    this.page_count = (event - 1);

    this.onPageChange(event);
  }
  //==
  onCloseModal() {

  }
  mobileexistsclick() {
    $('#mobileexists-modal').modal('hide');
    $('#pinModal').modal('show');
    this.TimeSet(this.otp_expiry)
  }
  selectdse() {
    LocalStorage.setValue("setdseselected", this.selecteddse);
    this.smpinselected = this.selecteddse;
    this.getcommondetails();
  }
  changetestride(e) {
    let tervalue = e.target.value;
    this.tervaluelicense=tervalue;
    (tervalue == 1) ? this.displaylicense = true : this.displaylicense = false;
  }

}

