import { Component, OnInit, ViewChild, ElementRef } 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 { AmazingTimePickerService } from 'amazing-time-picker';
import { FormGroup, FormBuilder, Validators } 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 * as enLocale from 'date-fns/locale/en';
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';

declare var $: $;

@Component({
  selector: 'app-quotation-dealer',
  templateUrl: './quotation-dealer.component.html',
  styleUrls: ['./quotation-dealer.component.scss']
})
export class QuotationDealerComponent implements OnInit {
  loader: boolean;
  modelarr: any = [];
  variantarr = [];
  colorarr = [];
  modelselected = '';
  variantselected = '';
  colorselected = '';
  contactno: any = '';
  emailvalue: any = '';
  customername: any = '';
  previousurl: any = '';
  datevalue: any = '';
  selecteddeaelername: any = '';
  selecteddsephone: any = '';
  selecteddsecity: any = '';
  selecteddsecountry: any = '';
  selecteddsestate: any = '';
  type: any = '';
  userData: any = {};

  exshowroomprice: any = '';
  exshowroompriceremarks: any = '';


  selecteddealermail: any = '';
  selecteddealeraddress: any = '';


  selecteddealersmpin: any = '';


  roadtax: any = '';
  roadtax_remarks: any = '';

  insurance: any = '';
  insurance_remarks: any = '';

  accessories: any = '';
  accessories_remarks: any = '';

  extendedwarranty: any = '';
  extendedwarranty_remarks: any = '';
  useridvalue: any = '';
  others
  others_remarks: any = '';

  onroadprice: any = 0;
  onroadprice_remarks: any = '';
  followupdate: any = '';
  totalprice: any = 0;
  total: any = 0;
  road_tax: any = 0;
  ins_urance: any = 0;
  access_ories: any = 0;
  extended_warranty: any = 0;
  others_: any = 0;
  user_role: number;
  err_dse: boolean = false
  err_cusname: boolean = false;
  err_email: boolean = false;
  err_contactno: boolean = false;
  err_model: boolean = false;
  err_varient: boolean = false;
  err_color: boolean = false;
  totalonroad_price: any;
  new_url: any = '';
  vardata_isable: boolean = false;
  returnvalue: any;
  smpinselected: any = '';
  smpin: any = '';


  checkforreset: number = 0;
  checkforresetvariant: number = 0;



  selecteddse: any = '';
  setsmpin: any = '';
  price_after_discount: any;
  offer_price: any = '';
  offer_ischeck: boolean = false;
  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 route: ActivatedRoute, public toaster: ToasterService, private formBuilder: FormBuilder, private server: HyperService, private router: Router, private atp: AmazingTimePickerService, public elm: ElementRef, private sanitizer: DomSanitizer) {



    // console.log("LocalStorage.getValue('previous_Url')--->",LocalStorage.getValue('previous_Url'));
    // return false;
















    //console.log("email-->",LocalStorage.getValue('tempvalue'))
  }

  ngOnInit() {

    var date12 = new Date()
    //  console.log(date12, "dd-MM-yyyy"); //output : 2018-02-13
    let tempvaluedate = moment(date12).format("DD-MM-YYYY")

    var date29 = date12.setDate(date12.getDate() + 1)

    var date30 = new Date(date29);
    //   console.log("date30---->", date30);

    this.followupdate = date30;
    this.datevalue = this.followupdate;

    let param_customername = '';
    let param_userid = '';
    let param_email = '';
    let param_modal = '';
    let param_variant = '';
    let param_color = '';
    let param_contact = '';
    let param_token = '';
    let param_dealername = '';
    let param_dealeraddress = '';
    let param_dealermobile = '';
    let param_dealeremail = '';
    let param_smpin = '';


    this.selecteddeaelername = LocalStorage.getValue('selecteddsename');
    this.selecteddsephone = LocalStorage.getValue('selecteddsephone');
    this.selecteddsecity = LocalStorage.getValue('selecteddsecity');
    this.selecteddsecountry = LocalStorage.getValue('selecteddsecountry');
    this.selecteddsestate = LocalStorage.getValue('selecteddsestate');
    this.selecteddealeraddress = LocalStorage.getValue('selecteduseraddress');
    this.selecteddealermail = LocalStorage.getValue('selecteduseremail')

    if (this.selecteddealeraddress == undefined || this.selecteddealeraddress == '' || this.selecteddealeraddress == null) {
      this.selecteddealeraddress = this.selecteddsecity + " " + this.selecteddsestate + " " + this.selecteddsecountry
    }

    this.route.params.subscribe(params => {
      this.useridvalue = params['tokenvalue'];
      this.previousurl = params['type'];
      this.type = params['type'];
      //  alert("params['smpin']"+params['smpin'])
      param_smpin = params['smpin'];
      this.smpin = params['smpin'];
      this.new_url = params['direct'];

      //  console.log("this.new_url", this.new_url);
      param_customername = params['customername'];
      param_userid = params['userid'];
      param_email = params['email'];
      param_modal = params['model'];
      param_variant = params['variant'];
      param_color = params['color'];
      param_contact = params['contactno'];
      param_dealername = params['dealername'];
      param_dealeraddress = params['dealeraddress'];
      param_dealermobile = params['dealermobile'];
      param_dealeremail = params['dealeremail'];
      ///important
      if (this.previousurl == 'mobile' && this.new_url != 'new') {
        this.selecteddealersmpin = param_userid;
        this.selecteddse = params['smpin'];
        LocalStorage.setValue("setdseselected", this.selecteddse)
      } else {
        this.selecteddealersmpin = params['smpin'];
      }


      //  console.log("this.param_modal", param_modal);
      //   console.log("this.param_variant", param_variant);
      //   console.log("this.param_color", param_color);

      setTimeout(() => {
        this.getaddressfromsmpin();
      }, 2000);




    });

    if (this.previousurl == '' || this.previousurl == null || this.previousurl == undefined) {
      this.emailvalue = '';
      this.contactno = '';
      this.colorselected = '';
      this.variantselected = '';
      this.modelselected = '';
      this.customername = '';
      this.selecteddse = '';
      // this.selecteddeaelername = LocalStorage.getValue('selecteddsename');
      // this.selecteddsephone = LocalStorage.getValue('selecteddsephone');
      // this.selecteddsecity = LocalStorage.getValue('selecteddsecity');
      // this.selecteddsecountry = LocalStorage.getValue('selecteddsecountry');
      // this.selecteddsestate = LocalStorage.getValue('selecteddsestate');
    
      if (param_dealeraddress == '' || param_dealeraddress == undefined) {        
        this.selecteddealersmpin = LocalStorage.getValue('selecteddealercode');     
        } else {
        this.selecteddealersmpin = param_dealeraddress;
      }



      this.selecteddeaelername = LocalStorage.getValue('selecteddsename');
      this.selecteddsephone = LocalStorage.getValue('selecteddsephone');
      this.selecteddsecity = LocalStorage.getValue('selecteddsecity');
      this.selecteddsecountry = LocalStorage.getValue('selecteddsecountry');
      this.selecteddsestate = LocalStorage.getValue('selecteddsestate');
      this.selecteddealeraddress = LocalStorage.getValue('selecteduseraddress');
      this.selecteddealermail = LocalStorage.getValue('selecteduseremail')

      if (this.selecteddealeraddress == undefined || this.selecteddealeraddress == '' || this.selecteddealeraddress == null) {
        this.selecteddealeraddress = this.selecteddsecity + " " + this.selecteddsestate + " " + this.selecteddsecountry
      }



      this.smpinselected = '';
      this.getdselist();

    } else if (this.previousurl == 'data') {
      this.returnvalue = LocalStorage.getValue('quote_emi_quote');

      LocalStorage.setValue("returnvalue", this.returnvalue);

      //  console.log("this.returnvalue-->",this.returnvalue)
      //  console.log("this.returnvalue-->",this.returnvalue.total_price)
      //  console.log("this.total_cash-->",this.returnvalue.exsh_price)
      //  console.log("dse-->",LocalStorage.getValue('dse'));

      //  console.log("get-->",LocalStorage.getValue("total_cash"))

      // let smpinvalue =  LocalStorage.getValue("setdseselected");
      //this.smpinselected = this.selecteddse;
      if (param_dealeraddress == '' || param_dealeraddress == undefined) {        
        this.selecteddealersmpin = LocalStorage.getValue('selecteddealercode');     
        } else {
        this.selecteddealersmpin = param_dealeraddress;
      }
      this.offer_price = this.returnvalue.offer_price;
      this.price_after_discount = this.returnvalue.after_discount;

      this.vardata_isable = true;

      this.selecteddealermail = LocalStorage.getValue('selecteduseremail');
      this.selecteddealeraddress = LocalStorage.getValue('selecteduseraddress');
      this.selecteddeaelername = LocalStorage.getValue('selecteddsename');
      this.selecteddsephone = LocalStorage.getValue('selecteddsephone');
      this.selecteddsecity = LocalStorage.getValue('selecteddsecity');
      this.selecteddsecountry = LocalStorage.getValue('selecteddsecountry');
      this.selecteddsestate = LocalStorage.getValue('selecteddsestate');
      setTimeout(() => {
        this.selecteddse = LocalStorage.getValue('dse');    
        //alert(this.selecteddse)  
        this.emailvalue = LocalStorage.getValue('tempvalue');
        this.contactno = LocalStorage.getValue('mobileno');
        this.colorselected = LocalStorage.getValue('colorval');
        this.variantselected = LocalStorage.getValue('varianttype');
        this.modelselected = LocalStorage.getValue('modeltype');
        this.customername = LocalStorage.getValue('titlename');
        this.exshowroomprice = this.returnvalue.exsh_price;
        this.exshowroompriceremarks = this.returnvalue.exsh_remark;
        this.roadtax = this.returnvalue.rto_price;
        this.roadtax_remarks = this.returnvalue.rto_remark;
        this.insurance = this.returnvalue.insurance_price;
        this.insurance_remarks = this.returnvalue.insurance_remark;
        this.accessories = this.returnvalue.access_price;
        this.accessories_remarks = this.returnvalue.access_remark;
        this.extendedwarranty = this.returnvalue.exwarr_price;
        this.extendedwarranty_remarks = this.returnvalue.exwarr_remark;
        this.others = this.returnvalue.other_price;
        this.others_remarks = this.returnvalue.other_remark;
        if (this.returnvalue.total_price == undefined) {
          let req = {
            model: this.modelselected

          }
          this.loader = true;
          this.server.post("dealerenquiry/pricelist/" + this.smpinselected, req).then((data) => {
            if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
              //   console.log("data.getprice---->", data);
              this.loader = false;
              let tempvalue = data.result.data;
              let rest1 = this.variantselected;
              const found = tempvalue.find(element => element.variant_code == rest1);
              this.totalonroad_price = Math.round(found.exsh_price);
              this.offer_price = '';
              this.price_after_discount = Math.round(this.totalonroad_price);
            }
          });
        } else {
          this.totalonroad_price = this.returnvalue.total_price;
        }


        //   console.log("this. this.totalonroad_price-->", this.totalonroad_price)
      }, 200);
      this.loader = true;
      setTimeout(() => {
        this.loader = false;
      }, 400);
      this.getdselist();
    }

    else if (this.previousurl == 'mobile' && this.new_url != 'new' && LocalStorage.getValue('mobile_value_return') == 'mobile_back_url') {
      LocalStorage.setValue('token', this.useridvalue);
      this.getuserdetails() //Get Authentication token 
      this.getdselist();
      setTimeout(() => {
        this.vardata_isable = true;

        this.returnvalue = LocalStorage.getValue('quote_emi_mobile');

        //  console.log("this.returnvalue",this.returnvalue)

        var date12 = new Date(this.returnvalue.valid_date)
        let tempvaluedate = moment(date12).format("DD-MM-YYYY")
        var date29 = date12.setDate(date12.getDate())
        var date30 = new Date(date29);
        this.followupdate = date30;

        this.customername = this.returnvalue.name;
        this.modelselected = this.returnvalue.model;
        this.variantselected = this.returnvalue.variant;
        this.colorselected = this.returnvalue.color;
        this.emailvalue = this.returnvalue.email;
        this.contactno = this.returnvalue.mobile;
        this.exshowroomprice = this.returnvalue.exsh_price;
        this.exshowroompriceremarks = this.returnvalue.exsh_remark;
        this.roadtax = this.returnvalue.rto_price;
        // this.calc_road(this.roadtax,1);
        this.roadtax_remarks = this.returnvalue.rto_remark;
        this.insurance = this.returnvalue.insurance_price;
        // this.calc_road(this.insurance,2);
        this.insurance_remarks = this.returnvalue.insurance_remark;
        this.accessories = this.returnvalue.access_price;
        // this.calc_road(this.accessories,3);
        this.accessories_remarks = this.returnvalue.access_remark;
        this.extendedwarranty = this.returnvalue.exwarr_price;
        // this.calc_road(this.extendedwarranty,4);
        this.extendedwarranty_remarks = this.returnvalue.exwarr_remark;
        this.others = this.returnvalue.other_price;
        // this.calc_road(this.others,5);
        this.others_remarks = this.returnvalue.other_remark;
        this.totalonroad_price = LocalStorage.getValue('onroad_price');

        this.onroadprice_remarks = this.returnvalue.total_remark;
        this.onroadprice = this.totalonroad_price;
        this.datevalue = this.followupdate;
        this.offer_price = this.returnvalue.offer_price;
        this.price_after_discount = this.returnvalue.after_discount;


        //   console.log("this.roadtax-->", this.roadtax);
        //  console.log("this.insurance-->", this.insurance);
        //   console.log("this.accessories-->", this.accessories);
        //   console.log("this.extendedwarranty-->", this.extendedwarranty);
        //   console.log("this.others-->", this.others);
        //   console.log("totalonroad_price-->", this.totalonroad_price);
        //   console.log("price_after_discount-->", this.price_after_discount);

        this.road_tax = this.roadtax;
        this.ins_urance = this.insurance;
        this.access_ories = this.accessories;
        this.extended_warranty = this.extendedwarranty;
        this.others_ = this.others;



        this.loader = true;
        setTimeout(() => {
          this.loader = false;
        }, 500);
      }, 1200)
    } else if (this.previousurl == 'mobile' && this.new_url != 'new' && LocalStorage.getValue('mobile_value_return') != 'mobile_back_url') {
      LocalStorage.setValue('token', this.useridvalue);
      this.getuserdetails() //Get Authentication token 
      this.getdselist();

      setTimeout(() => {
        this.vardata_isable = true;
        this.emailvalue = param_email;
        this.contactno = param_contact;
        this.colorselected = param_color;
        this.variantselected = param_variant;
        this.modelselected = param_modal;
        this.customername = param_customername;

        // this.selecteddeaelername = LocalStorage.getValue('selecteddsename');
        // this.selecteddsephone = LocalStorage.getValue('selecteddsephone');
        // this.selecteddsecity = LocalStorage.getValue('selecteddsecity');
        // this.selecteddsecountry = LocalStorage.getValue('selecteddsecountry');
        // this.selecteddsestate = LocalStorage.getValue('selecteddsestate');

      }, 200);
    } else if (this.previousurl == 'mobile' && this.new_url == 'new' && LocalStorage.getValue('mobile_value_return') != 'mobile_back_url') {

      LocalStorage.setValue('token', this.useridvalue);
      this.getuserdetails() //Get Authentication token  
      this.getdselist();
      setTimeout(() => {
        this.modelselected = '';
        this.variantselected = '';
        this.colorselected = '';
        this.customername = '';
        this.emailvalue = '';
        this.contactno = '';
        this.selecteddse = '';
        // this.selecteddeaelername = LocalStorage.getValue('selecteddsename');
        // this.selecteddsephone = LocalStorage.getValue('selecteddsephone');
        // this.selecteddsecity = LocalStorage.getValue('selecteddsecity');
        // this.selecteddsecountry = LocalStorage.getValue('selecteddsecountry');
        // this.selecteddsestate = LocalStorage.getValue('selecteddsestate');
      }, 200);
    } else if (this.previousurl == 'back') {
      this.getdselist();
      this.checkforreset = 0;
      this.checkforresetvariant = 0;


      this.selecteddeaelername = LocalStorage.getValue('selecteddsename');
      this.selecteddsephone = LocalStorage.getValue('selecteddsephone');
      this.selecteddsecity = LocalStorage.getValue('selecteddsecity');
      this.selecteddsecountry = LocalStorage.getValue('selecteddsecountry');
      this.selecteddsestate = LocalStorage.getValue('selecteddsestate');
      this.selecteddealeraddress = LocalStorage.getValue('selecteduseraddress');
      this.selecteddealermail = LocalStorage.getValue('selecteduseremail')

      if (this.selecteddealeraddress == undefined || this.selecteddealeraddress == '' || this.selecteddealeraddress == null) {
        this.selecteddealeraddress = this.selecteddsecity + " " + this.selecteddsestate + " " + this.selecteddsecountry
      }
      if (param_dealeraddress == '' || param_dealeraddress == undefined) {        
        this.selecteddealersmpin = LocalStorage.getValue('selecteddealercode');     
        } else {
        this.selecteddealersmpin = param_dealeraddress;
      }
      // this.vardata_isable = true;
      //  console.log("req-->", LocalStorage.getValue('quote_emi'));
      this.returnvalue = LocalStorage.getValue('quote_emi');

      var date12 = new Date(this.returnvalue.valid_date)
      let tempvaluedate = moment(date12).format("DD-MM-YYYY")
      var date29 = date12.setDate(date12.getDate())
      var date30 = new Date(date29);
      this.followupdate = date30;

      this.customername = this.returnvalue.name;
      this.modelselected = this.returnvalue.model;
      this.variantselected = this.returnvalue.variant;
      this.colorselected = this.returnvalue.color;
      this.emailvalue = this.returnvalue.email;
      this.contactno = this.returnvalue.mobile;
      this.selecteddse = this.returnvalue.dse;
      this.exshowroomprice = this.returnvalue.exsh_price;
      this.exshowroompriceremarks = this.returnvalue.exsh_remark;
      this.roadtax = this.returnvalue.rto_price;
      // this.calc_road(this.roadtax,1);
      this.roadtax_remarks = this.returnvalue.rto_remark;
      this.insurance = this.returnvalue.insurance_price;
      // this.calc_road(this.insurance,2);
      this.insurance_remarks = this.returnvalue.insurance_remark;
      this.accessories = this.returnvalue.access_price;
      // this.calc_road(this.accessories,3);
      this.accessories_remarks = this.returnvalue.access_remark;
      this.extendedwarranty = this.returnvalue.exwarr_price;
      // this.calc_road(this.extendedwarranty,4);
      this.extendedwarranty_remarks = this.returnvalue.exwarr_remark;
      this.others = this.returnvalue.other_price;
      // this.calc_road(this.others,5);
      this.others_remarks = this.returnvalue.other_remark;
      this.totalonroad_price = this.returnvalue.total_price;
      this.onroadprice_remarks = this.returnvalue.total_remark;
      this.datevalue = this.followupdate;
      this.smpinselected = param_smpin;
      this.offer_price = this.returnvalue.offer_price;
      this.price_after_discount = Math.round(this.returnvalue.after_discount);

      //  console.log("this.roadtax-->", this.roadtax);
      //   console.log("this.insurance-->", this.insurance);
      //  console.log("this.accessories-->", this.accessories);
      //  console.log("this.extendedwarranty-->", this.extendedwarranty);
      //  console.log("this.others-->", this.others);
      //  console.log("this.othersprice-->", this.offer_price);
      //  console.log("this.price_after_discount-->", this.price_after_discount);
      // this.road_tax=this.roadtax;
      // this.ins_urance=this.insurance;
      // this.access_ories=this.accessories;
      // this.extended_warranty=this.extendedwarranty;
      // this.others_=this.others;

      this.loader = true;
      setTimeout(() => {
        this.loader = false;
      }, 500);

    } else if (this.previousurl == 'mobile' && this.new_url == 'new' && (LocalStorage.getValue('mobile_value_return') == 'mobile_back_url')) {
      LocalStorage.setValue('token', this.useridvalue);
      this.getuserdetails() //Get Authentication token 
      this.getdselist();
      this.returnvalue = LocalStorage.getValue('quote_emi_mobile');
      //  console.log("this.returen",this.returnvalue)
      this.checkforreset = 0;
      this.checkforresetvariant = 0;
      var date12 = new Date(this.returnvalue.valid_date)

      let tempvaluedate = moment(date12).format("DD-MM-YYYY")
      var date29 = date12.setDate(date12.getDate())
      var date30 = new Date(date29);
      this.followupdate = date30;
      this.selecteddse = LocalStorage.getValue('quote_emi_dse');
      this.customername = this.returnvalue.name;
      this.modelselected = this.returnvalue.model;
      this.variantselected = this.returnvalue.variant;
      this.colorselected = this.returnvalue.color;
      this.emailvalue = this.returnvalue.email;
      this.contactno = this.returnvalue.mobile;
      this.exshowroomprice = this.returnvalue.exsh_price;
      this.exshowroompriceremarks = this.returnvalue.exsh_remark;
      this.roadtax = this.returnvalue.rto_price;
      // this.calc_road(this.roadtax,1);
      this.roadtax_remarks = this.returnvalue.rto_remark;
      this.insurance = this.returnvalue.insurance_price;
      // this.calc_road(this.insurance,2);
      this.insurance_remarks = this.returnvalue.insurance_remark;
      this.accessories = this.returnvalue.access_price;
      // this.calc_road(this.accessories,3);
      this.accessories_remarks = this.returnvalue.access_remark;
      this.extendedwarranty = this.returnvalue.exwarr_price;
      // this.calc_road(this.extendedwarranty,4);
      this.extendedwarranty_remarks = this.returnvalue.exwarr_remark;
      this.others = this.returnvalue.other_price;
      // this.calc_road(this.others,5);
      this.others_remarks = this.returnvalue.other_remark;
      this.totalonroad_price = LocalStorage.getValue('onroad_price');
      this.onroadprice_remarks = this.returnvalue.total_remark;
      this.onroadprice = this.totalonroad_price;
      this.datevalue = this.followupdate;
      this.offer_price = this.returnvalue.offer_price;
      this.price_after_discount = this.returnvalue.after_discount;


      // console.log("this.roadtax-->", this.roadtax);
      // console.log("this.insurance-->", this.insurance);
      // console.log("this.accessories-->", this.accessories);
      // console.log("this.extendedwarranty-->", this.extendedwarranty);
      // console.log("this.others-->", this.others);
      // console.log("totalonroad_price-->", this.totalonroad_price);
      // console.log("price_after_discount-->", this.price_after_discount);

      this.road_tax = this.roadtax;
      this.ins_urance = this.insurance;
      this.access_ories = this.accessories;
      this.extended_warranty = this.extendedwarranty;
      this.others_ = this.others;




      this.loader = true;
      setTimeout(() => {
        this.loader = false;
      }, 500);
    }

    this.getcommondetails();
  
  }
  getdselist() {
    let spin = '';
    this.server.get("dealer/userlist")
      .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') {

        }
      });
  }
  selectdse() {
    LocalStorage.setValue("setdseselected", this.selecteddse);
    this.smpinselected = this.selecteddse;
    if (this.previousurl == 'mobile' && this.new_url == 'new') {
      this.modelselected = '';
      this.variantselected = '';
      this.colorselected = '';
      this.resetextrafields();
    }
    this.getcommondetails();
  }
  getuserdetails() {
    this.server.get("user/profile").then((data) => {
      if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
        this.userData = data.result.data;
        LocalStorage.setValue('user_data', this.userData)
        this.user_role = this.userData.role;
        LocalStorage.setValue('selecteddsename', data.result.data.dealer.dealer_name);
        LocalStorage.setValue('selecteddsephone', data.result.data.dealer.phone);
        LocalStorage.setValue('selecteddsecity', data.result.data.dealer.city);
        LocalStorage.setValue('selecteddsecountry', data.result.data.dealer.country);
        LocalStorage.setValue('selecteddsestate', data.result.data.dealer.state);

      }
      else if (data.result.status == 401 && data.result.response == 'failed') {
        this.router.navigateByUrl('');
      }
      else {
        alert("Oops something happened!");
      }
    })
  }
  check_number(event) {
    //  console.log(event)
    // let temp: any[];
    // temp = event.target.value;
    const charCode = (event.which) ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false;
    }
    return true;
  }

  getcommondetails() {
    let smpinvalue = LocalStorage.getValue('setdseselected')
console.log("this.setsmpin",this.setsmpin)
    if (smpinvalue == '' || smpinvalue == undefined) {
      this.smpinselected=this.setsmpin[0].smpin;
    } else {   
      this.smpinselected = smpinvalue;
    }

    this.server.get("dealerenquiry/common/" + this.smpinselected)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed') {
          this.modelarr = data.result.data.model;
          if (this.modelselected != '' && this.modelselected != undefined) {
            this.selectmodel()
          }
          if (this.modelselected != '' && this.modelselected != undefined && this.variantselected != '' && this.variantselected != undefined) {
            this.selectvariant()
          }
        } else if (data.result.status == 406) {
          //alert(data.result.message)
        }
        else if (data.result.status == 401 && data.result.response == 'failed') {

        }
      });
  }

  numberOnly(event): boolean {
    //  console.log(event)
    let temp: any[]
    temp = event.target.value
    if (temp.length >= 10) {
      return false;
    }

    const charCode = (event.which) ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false;
    }
    return true;
  }



  //==
  selectmodel() {
    // this.displaystockval=''
    let rest = this.modelselected;
    const found = this.modelarr.find(element => element.title_code == rest);
    let variantvalue = found.variant;
    this.variantarr = variantvalue;
    if (this.checkforreset != 0) {
      this.resetextrafields();
      this.variantselected = '';
      this.colorselected = '';
    }
    this.checkforreset = 1;
    this.colorarr = [];
  }
  //===
  selectvariant() {
    // 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;
    this.getprice();
    if (this.checkforresetvariant != 0) {
      this.resetextrafields();
      this.colorselected = '';
    }
    this.checkforresetvariant = 1;
    // if (this.previousurl == '' || this.previousurl == null || this.previousurl == undefined || this.previousurl == 'new') {
    //   this.roadtax = '';
    //   this.insurance = '';
    //   this.accessories = '';
    //   this.extendedwarranty = '';
    //   this.others = '';
    // } 

  }

  selectcolor() {
    // this.displaystockval=''
    let req = {
      model: this.modelselected,
      variant: this.variantselected,
      color: this.colorselected
    }
    //this.loader = true;
    // this.server.post("dealerenquiry/stockavailability", req).then((data) => {
    //   if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
    //     this.loader = false;
    //     // console.log("verifyvariant--->",data)
    //     // this.getprice();
    //     //  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);
    //   }
    // });
  }
  getprice() {

    let smpinvalue = LocalStorage.getValue('setdseselected')

    this.smpinselected = smpinvalue

    //  alert("this.smpinselected--->"+this.smpinselected);
    let req = {
      model: this.modelselected

    }
    this.loader = true;
    this.server.post("dealerenquiry/pricelist/" + this.smpinselected + "", req).then((data) => {
      if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
        this.loader = false;
        //  console.log("data.getprice---->", data);
        let tempvalue = data.result.data;
        let rest1 = this.variantselected;
        const found = tempvalue.find(element => element.variant_code == rest1);
        this.exshowroomprice = found.exsh_price;
        var s = Math.round(this.exshowroomprice)
        //  this.onroadprice = parseInt(s);
        // alert("s---->"+s)
        this.onroadprice = s;
        this.offer_ischeck = true;

        // this.onroadprice = parseInt(this.exshowroomprice);
        if (this.previousurl == '' || this.previousurl == null || this.previousurl == undefined || this.previousurl == 'new') {
          this.totalonroad_price = s;
          // this.totalonroad_price = parseInt(this.exshowroomprice);
          this.price_after_discount = s;
        } else if (this.type == 'mobile') {
          //this.totalonroad_price = parseInt(this.exshowroomprice);
          this.totalonroad_price = s;
          this.price_after_discount = this.onroadprice;
        }
        // alert("this.price_after_discount---->"+this.price_after_discount);
        if (isNaN(this.price_after_discount)) {
          this.price_after_discount = '';
          this.toaster.show("No price available for the selcted variant");
        }

        if ((LocalStorage.getValue('mobile_value_return') == 'mobile_back_url')) {
          this.totalonroad_price = LocalStorage.getValue('onroad_price');
          this.price_after_discount = LocalStorage.getValue('quote_emi_mobile').after_discount;
          //  console.log(" this.price_after_discount-->", this.price_after_discount);

        }
        //  console.log("found--exsh_price-->", found);

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




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

      }
    });
  }

  price_clear() {
    this.roadtax = '';
    this.insurance = '';
    this.accessories = '';
    this.extendedwarranty = '';
    this.others = '';
    this.totalonroad_price = '';
    this.offer_price = '';
    this.offer_ischeck = false;
    this.exshowroomprice = '';
    this.price_after_discount = '';
  }


  calc_road(searchValue, i) {

    // if (this.road_tax == true && searchValue != '') {
    //   alert("after")
    //   this.roadtax = 0;
    //   this.road_tax = 0;
    // }

    if (i == 1) {
      if (searchValue == '') {
        this.road_tax = 0;
      } else {
        this.road_tax = Number(searchValue)
        //  console.log("roadtax-->", this.road_tax);
      }

    }
    else if (i == 2) {
      if (searchValue == '') {
        this.ins_urance = 0;

      } else {
        this.ins_urance = Number(searchValue)
        //  console.log("ins_urance-->", this.ins_urance);
      }
      // this.ins_urance = parseInt(searchValue)
      // console.log("ins_urance-->", this.ins_urance);

    }
    else if (i == 3) {
      if (searchValue == '') {
        this.access_ories = 0;

      } else {
        this.access_ories = Number(searchValue)
        //  console.log("access_ories-->", this.access_ories);
      }

      // this.access_ories = parseInt(searchValue)
      // console.log("access_ories-->", this.access_ories);

    }
    else if (i == 4) {
      if (searchValue == '') {
        this.extended_warranty = 0;

      } else {
        this.extended_warranty = Number(searchValue)
        //  console.log("extended_warranty-->", this.extended_warranty);
      }
      // this.extended_warranty = parseInt(searchValue)
      // console.log("extended_warranty-->", this.extended_warranty);

    }
    else if (i == 5) {
      if (searchValue == '') {
        this.others_ = 0;

      } else {
        this.others_ = Number(searchValue)
        //   console.log("others_-->", this.others_);
      }
      // this.others_ = parseInt(searchValue)
      // console.log("others_-->", this.others_);

    }
    else if (i == 0) {
      this.totalprice = Number(this.road_tax) + Number(this.ins_urance) + Number(this.access_ories) + Number(this.extended_warranty) + Number(this.others_);

    } else {
      this.totalprice = Number(this.road_tax) + Number(this.ins_urance) + Number(this.access_ories) + Number(this.extended_warranty) + Number(this.others_);
    }

    this.totalprice = Number(this.road_tax) + Number(this.ins_urance) + Number(this.access_ories) + Number(this.extended_warranty) + Number(this.others_);

    console.log("total-------->,", this.totalprice);
    this.gettotalonroadprice()

  }
  gettotalonroadprice() {
    let temp = this.onroadprice;
    this.totalonroad_price = temp + this.totalprice;
    if (this.totalonroad_price == NaN) {
      this.totalonroad_price = 0
    } else {
      this.totalonroad_price = temp + this.totalprice;
      this.offer_calc();
    }
    //  console.log("total onroadprice-------->,", this.totalonroad_price);
  }
  offer_calc() {
    //  console.log("thisoffer", this.offer_price, this.totalonroad_price)




    if (Number(this.offer_price) < Number(this.totalonroad_price)) {
      let vals = this.offer_price;
      if (vals == '' || vals == undefined || this.totalonroad_price == undefined) {
        this.price_after_discount = this.totalonroad_price;
      } else {
        this.price_after_discount = this.totalonroad_price - vals;
      }
    }
    else {
      this.offer_price='';
     // this.offer_calc();
     this.price_after_discount =  this.totalonroad_price;
      this.toaster.show("Discount amount should not exceed total on road price");
    }


  }
  shareemail() {


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

    if (this.previousurl == 'back' || this.previousurl == 'data') {
      this.road_tax = this.roadtax;
      this.ins_urance = this.insurance;
      this.access_ories = this.accessories;
      this.extended_warranty = this.extendedwarranty;
      this.others_ = this.others;
    }



    var regExp = /^([\w\.\+]{1,})([^\W])(@)([\w]{1,})(\.[\w]{1,})+$/;
    if (this.validation()) {
      if (this.contactno.length < 10) {
        this.toaster.show("Please enter 10 digit mobile number");
      } else if (regExp.test(this.emailvalue) == false) {
        this.toaster.show("Please provide a valid email");
      }
      else if ((isNaN(this.totalonroad_price)) || (this.totalonroad_price == '') || (this.totalonroad_price == undefined) || (this.totalonroad_price == null)) {
        this.price_after_discount = '';
        this.toaster.show("No price available for the selcted variant");
      }
      else {
        this.loader = true;
        let date_val = this.datevalue;
        let d1 = new Date(date_val);
        let dateinsertion = moment(d1).format("YYYY-MM-DD");
        let req = {
          name: this.customername,
          email: this.emailvalue,
          mobile: this.contactno,
          variant: this.variantselected,
          exsh_price: this.exshowroomprice,
          exsh_remark: this.exshowroompriceremarks,
          rto_price: this.roadtax,
          rto_remark: this.roadtax_remarks,
          insurance_price: this.insurance,
          insurance_remark: this.insurance_remarks,
          access_price: this.accessories,
          access_remark: this.accessories_remarks,
          exwarr_price: this.extendedwarranty,
          exwarr_remark: this.extendedwarranty_remarks,
          other_price: this.others,
          other_remark: this.others_remarks,
          model: this.modelselected,
          total_price: this.totalonroad_price,
          total_remark: this.onroadprice_remarks,
          color: this.colorselected,
          valid_date: dateinsertion,
          offer_price: this.offer_price,
          after_discound: this.price_after_discount
        }
        //  console.log(req)

        this.server.post("dealerenquiry/sharequotation/" + this.smpinselected, req).then((data) => {
          if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
            this.loader = false;
            this.toaster.show(data.result.message);
          } else if (data.result.status == 401 && data.result.response == 'failed') {
            this.loader = false;
            this.toaster.show(data.result.message);
          } else if (data.result.status == 406 && data.result.response == 'failed') {
            this.loader = false;
            this.toaster.show(data.result.message);
          }
        });

      }
    } else {
      this.toaster.show("Please enter and select the mandatory details");
    }

  }


  validation() {
    this.err_dse = (this.selecteddse == '' || this.selecteddse == undefined) ? true : false;
    this.err_cusname = (this.customername == '' || this.customername == undefined) ? true : false;
    this.err_model = (this.modelselected == '' || this.modelselected == undefined) ? true : false;
    this.err_varient = (this.variantselected == '' || this.variantselected == undefined) ? true : false;
    this.err_color = (this.colorselected == '' || this.colorselected == undefined) ? true : false;
    this.err_contactno = (this.contactno == '' || this.contactno == undefined) ? true : false;
    this.err_email = (this.emailvalue == '' || this.emailvalue == undefined) ? true : false;



    if (!this.err_dse && !this.err_cusname && !this.err_model && !this.err_varient && !this.err_color && !this.err_email && !this.err_contactno) {
      return true;
    } else {
      return false;
    }

  }

  emicalculation() {
    if (this.modelselected == '' || this.variantselected == '' || this.colorselected == '') {
      this.toaster.show("Please select model, varient & color");
    } else if ((isNaN(this.totalonroad_price)) || (this.totalonroad_price == '') || (this.totalonroad_price == undefined) || (this.totalonroad_price == null)) {
      this.price_after_discount = '';
      this.toaster.show("No price available for the selcted variant");
    } else {
      let date_val = this.datevalue;
      let d1 = new Date(date_val);
      let dateinsertion = moment(d1).format("YYYY-MM-DD");
      let req = {
        name: this.customername,
        email: this.emailvalue,
        mobile: this.contactno,
        variant: this.variantselected,
        exsh_price: this.exshowroomprice,
        exsh_remark: this.exshowroompriceremarks,
        rto_price: this.roadtax,
        rto_remark: this.roadtax_remarks,
        insurance_price: this.insurance,
        insurance_remark: this.insurance_remarks,
        access_price: this.accessories,
        access_remark: this.accessories_remarks,
        exwarr_price: this.extendedwarranty,
        exwarr_remark: this.extendedwarranty_remarks,
        other_price: this.others,
        other_remark: this.others_remarks,
        model: this.modelselected,
        total_price: this.totalonroad_price,
        total_remark: this.onroadprice_remarks,
        color: this.colorselected,
        valid_date: dateinsertion,
        dse: this.selecteddse,
        offer_price: this.offer_price,
        after_discount: this.price_after_discount
      }
      LocalStorage.setValue('quote_emi', req)
      LocalStorage.setValue('exshowroomprice', this.exshowroomprice);
      LocalStorage.setValue('onroad_price', this.totalonroad_price);
      LocalStorage.setValue('after_discount', this.price_after_discount);
      LocalStorage.setValue('quote_emi_model', this.modelselected);
      LocalStorage.setValue('quote_emi_varient', this.variantselected);
      LocalStorage.setValue('quote_emi_color', this.colorselected);
      LocalStorage.setValue('quote_emi_dse', this.selecteddse);




      this.router.navigateByUrl("dealer-emi-calculator/quote-emi");

    }

  }

  emicalculationdirect() {
    if (this.modelselected == '' || this.variantselected == '' || this.colorselected == '') {
      this.toaster.show("Please select model, varient & color");
    } else if ((isNaN(this.totalonroad_price)) || (this.totalonroad_price == '') || (this.totalonroad_price == undefined) || (this.totalonroad_price == null)) {
      this.price_after_discount = '';
      this.toaster.show("No price available for the selcted variant");
    } else {
      let date_val = this.datevalue;
      let d1 = new Date(date_val);
      let dateinsertion = moment(d1).format("YYYY-MM-DD");
      let req = {
        name: this.customername,
        email: this.emailvalue,
        mobile: this.contactno,
        variant: this.variantselected,
        exsh_price: this.exshowroomprice,
        exsh_remark: this.exshowroompriceremarks,
        rto_price: this.roadtax,
        rto_remark: this.roadtax_remarks,
        insurance_price: this.insurance,
        insurance_remark: this.insurance_remarks,
        access_price: this.accessories,
        access_remark: this.accessories_remarks,
        exwarr_price: this.extendedwarranty,
        exwarr_remark: this.extendedwarranty_remarks,
        other_price: this.others,
        other_remark: this.others_remarks,
        model: this.modelselected,
        total_price: this.totalonroad_price,
        total_remark: this.onroadprice_remarks,
        color: this.colorselected,
        valid_date: dateinsertion,
        dse: this.selecteddse,
        offer_price: this.offer_price,
        after_discount: this.price_after_discount
      }
      LocalStorage.setValue('quote_emi_quote', req)
      LocalStorage.setValue('exshowroomprice', this.exshowroomprice);
      LocalStorage.setValue('onroad_price', this.totalonroad_price);
      LocalStorage.setValue('after_discount', this.price_after_discount);
      LocalStorage.setValue('quote_emi_model', this.modelselected);
      LocalStorage.setValue('quote_emi_varient', this.variantselected);
      LocalStorage.setValue('quote_emi_color', this.colorselected);
      LocalStorage.setValue('quote_emi_dse', this.selecteddse);
      LocalStorage.setValue('after_discount', this.price_after_discount);

      this.router.navigateByUrl("dealer-emi-calculator/quote-emi-quote");
    }
  }

  emicalculationmobile() {
    let param_customername = '';
    let param_userid = '';
    let param_email = '';
    let param_modal = '';
    let param_variant = '';
    let param_color = '';
    let param_contact = '';
    let param_token = '';

    this.route.params.subscribe(params => {
      //  console.log("params",params)
      this.previousurl = params['type'];
      this.type = params['type'];
      this.new_url = params['direct'];
      //  console.log("this.new_url", this.new_url);
      param_customername = params['customername'];
      param_userid = params['userid'];
      param_email = params['email'];
      param_modal = params['model'];
      param_variant = params['variant'];
      param_color = params['color'];
      param_contact = params['contactno'];
      this.useridvalue = params['tokenvalue'];
    });
    if (this.modelselected == '' || this.variantselected == '' || this.colorselected == '') {
      this.toaster.show("Please select model, varient & color");
    } else if ((isNaN(this.totalonroad_price)) || (this.totalonroad_price == '') || (this.totalonroad_price == undefined) || (this.totalonroad_price == null)) {
      this.price_after_discount = '';
      this.toaster.show("No price available for the selcted variant");
    } else {
      let date_val = this.datevalue;
      let d1 = new Date(date_val);
      let dateinsertion = moment(d1).format("YYYY-MM-DD");
      let req = {
        name: this.customername,
        email: this.emailvalue,
        mobile: this.contactno,
        variant: this.variantselected,
        exsh_price: this.exshowroomprice,
        exsh_remark: this.exshowroompriceremarks,
        rto_price: this.roadtax,
        rto_remark: this.roadtax_remarks,
        insurance_price: this.insurance,
        insurance_remark: this.insurance_remarks,
        access_price: this.accessories,
        access_remark: this.accessories_remarks,
        exwarr_price: this.extendedwarranty,
        exwarr_remark: this.extendedwarranty_remarks,
        other_price: this.others,
        other_remark: this.others_remarks,
        model: this.modelselected,
        total_price: this.totalonroad_price,
        total_remark: this.onroadprice_remarks,
        color: this.colorselected,
        valid_date: dateinsertion,
        dse: this.selecteddse,
        offer_price: this.offer_price,
        after_discount: this.price_after_discount
      }


      LocalStorage.setValue('quote_emi_mobile', req)
      LocalStorage.setValue('exshowroomprice', this.exshowroomprice);
      LocalStorage.setValue('onroad_price', this.totalonroad_price);
      LocalStorage.setValue('quote_emi_model', this.modelselected);
      LocalStorage.setValue('quote_emi_varient', this.variantselected);
      LocalStorage.setValue('quote_emi_color', this.colorselected);
      LocalStorage.setValue('quote_emi_dse', this.selecteddse);
      LocalStorage.setValue('after_discount', this.price_after_discount);







      if (this.previousurl == 'mobile' && this.new_url == 'new') {

        LocalStorage.setValue("mobile_url", this.router.url);
        LocalStorage.setValue("mobile_url_check", 'inner-emi');
        let param_local = 'inner-emi';
        this.router.navigateByUrl("dealer-emi-calculator/" + this.type + '/' + this.selecteddse + '/' + param_local + '/' + this.modelselected + '/' + this.variantselected + '/' + this.colorselected + '/' + this.useridvalue);
      } else if (this.previousurl == 'mobile' && this.new_url != 'new') {
        LocalStorage.setValue("mobile_url_check", 'inner-emi');
        LocalStorage.setValue("mobile_url", this.router.url);
        let param_local = 'inner-emi';
        this.router.navigateByUrl("dealer-emi-calculator/" + this.type + '/' + this.selecteddse + '/' + param_local + '/' + this.modelselected + '/' + this.variantselected + '/' + this.colorselected + '/' + this.useridvalue);

      }

      else {
        this.router.navigateByUrl("dealer-emi-calculator/" + this.type + '/' + this.selecteddse + '/' + param_customername + '/' + param_modal + '/' + param_variant + '/' + param_color + '/' + this.useridvalue);
      }
    }
  }
  //==
  resetextrafields() {

    //  alert("bbbbbb");

    this.exshowroomprice = '';
    this.exshowroompriceremarks = '';
    this.roadtax = '';
    this.roadtax_remarks = '';
    this.insurance = '';
    this.insurance_remarks = '';
    this.accessories = '';
    this.accessories_remarks = '';
    this.extendedwarranty = '';
    this.extendedwarranty_remarks = '';
    this.others = '';
    this.others_remarks = '';
    this.totalonroad_price = '';
    this.offer_price = '';
    this.price_after_discount = '';

  }
  //==
  getaddressfromsmpin() {
    this.loader = true;
    this.server.get("enquiry/dealer/" + this.selecteddealersmpin)
      .then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response != 'failed') {
          //   console.log("data-->",data);
          this.selecteddeaelername = data.result.data[0].dealer_name
          var address = data.result.data[0].address;
          this.selecteddealermail = data.result.data[0].email;
          if (address != '') {
            this.selecteddealeraddress = address;
          } else {
            this.selecteddealeraddress = data.result.data[0].city + " " + data.result.data[0].state;
          }

        } else if (data.result.status == 406) {

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



}
