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 { 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 { 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-emi-calculator-dealer',
  templateUrl: './emi-calculator-dealer.component.html',
  styleUrls: ['./emi-calculator-dealer.component.scss']
})
export class EmiCalculatorDealerComponent implements OnInit {
  loader: boolean = false;
  smpinselected: any = '';
  url: any = '';
  showroomprice: any = '';
  exshowroomprice: any = '';
  type: any = '';
  loanamt: any = '';
  downpaymentamt: any = '';
  previousurl: any = '';
  useridvalue: any = '';
  userData: any = {};
  user_role: number;
  downpayment: any = '';
  modelselected: any = '';
  variantselected: any = '';
  colorselected: any = '';
  onroadprice: any = 0;
  totalonroad_price: any = 0;
  modelarr: any;
  variantarr: any;
  colorarr: any;
  dseerr:boolean=false;
  modelerr: boolean = false;
  varianterr: boolean = false;
  colorerr: boolean = false;
  onroad_input: boolean = false;
  down_payment: boolean = false;
  downpayment_input_value: any = 0;
  onroad_input_value: any = 0;
  check_len_val: any = [];
  onroad_check: boolean = false;
  down_payment_check: boolean = false;
  is_enable_graph: boolean = false;
  is_checked: boolean = false;
  param_check: any;
  new_url: any;
  vardata_isable: boolean = false
  onroad_value: boolean = false;
  setsmpin:any='';
  selecteddse:any='';
  mobile_back:boolean=false;
  checkforreset:number=0;
  checkforresetvariant:number=0;

  constructor(private route: ActivatedRoute, public toaster: ToasterService, private formBuilder: FormBuilder, private server: HyperService, private router: Router, public elm: ElementRef, private sanitizer: DomSanitizer) { }

  ngOnInit() {
    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') {

      }
    });

    let param_userid = '';
    let param_model = '';
    let param_variant = '';
    let param_color = '';
    let param_token = '';
    let param_dse = '';
    

    this.route.params.subscribe(params => {
      this.type = params['type'];
      this.previousurl = params['type'];
      this.new_url = params['direct'];
      param_dse=params['smpin'];
      param_userid = params['userid'];
      param_model = params['model'];
      param_variant = params['variant'];
      param_color = params['color'];
      param_token = params['tokenvalue'];
      this.useridvalue = params['tokenvalue'];
    });


    if (this.previousurl == '' || this.previousurl == null || this.previousurl == undefined) {
      this.exshowroomprice = 0;
      LocalStorage.setValue('check_path', '');
      this.selecteddse='';
      this.modelselected = '';
      this.variantselected = '';
      this.colorselected = '';
      this.is_checked = true;
      this.down_payment = false;
      this.down_payment_check = false;
      this.is_enable_graph = true;
      this.exshowroomprice = 0;
      this.ex_showroomprice();

    } else if (this.previousurl == 'mobile' && this.new_url != 'new') {
      this.vardata_isable=true;
      // let smpinvalue = LocalStorage.getValue('setdseselected')
      // this.smpinselected = smpinvalue
      this.selecteddse=param_dse; 
     // console.log('selecteddse', this.selecteddse);
      this.smpinselected=param_dse; 
      LocalStorage.setValue('token', this.useridvalue);

      this.vardata_isable = true;
      this.onroad_value = true;
      this.modelselected = param_model;
      this.variantselected = param_variant;
      this.colorselected = param_color;
    //  console.log("modelselected", this.modelselected)

      let req = {
        model: this.modelselected

      }
      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);
          let tempvalue = data.result.data;
          let rest1 = this.variantselected;
          const found = tempvalue.find(element => element.variant_code == rest1);
          this.exshowroomprice = found.exsh_price;
          if(isNaN(this.exshowroomprice)||(this.exshowroomprice==undefined)){
            this.exshowroomprice =0;
            //this.totalonroad_price ='';
            this.toaster.show("No price available for the selcted variant");
          }

          this.onroadprice = Math.round(this.exshowroomprice);
          this.totalonroad_price = Math.round(this.exshowroomprice);
         // console.log("found--exsh_price-->", found);
          this.url = this.sanitizer.bypassSecurityTrustResourceUrl("https://hyper-m.cygnusa.in/emicalculator/quotation.html?loanamt=" + this.exshowroomprice);
        } else if (data.result.status == 401 && data.result.response == 'failed') {
          this.toaster.show(data.result.message);



        } else if (data.result.status == 406 && data.result.response == 'failed') {
          this.toaster.show(data.result.message);
        }
      });
      this.exshowroomprice = this.exshowroomprice;
      this.onroad_input_value = this.totalonroad_price;
      this.is_checked = true;
      this.down_payment = false;
      this.down_payment_check = false;
      this.is_enable_graph = true;
      this.ex_showroomprice();
      this.getuserdetails() //Get Authentication token 
    }
    else if (this.previousurl == 'web') {
      this.vardata_isable=true;
      let smpinvalue = LocalStorage.getValue('setdseselected')
      this.smpinselected = smpinvalue
      this.selecteddse=this.smpinselected; 
      this.vardata_isable = true;
      this.exshowroomprice = LocalStorage.getValue('exshowroomprice');
      this.showroomprice = LocalStorage.getValue('showroomprice');
      this.param_check = LocalStorage.getValue('check_path');
    //  console.log("this.param_check-->", this.param_check)
      this.colorselected = LocalStorage.getValue('colorval');
      this.variantselected = LocalStorage.getValue('varianttype');
      this.modelselected = LocalStorage.getValue('modeltype');
      this.is_checked = true;
      this.down_payment = true;
      this.down_payment_check = true;
      this.is_enable_graph = true;
      let req = {
        model: this.modelselected

      }
      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);
          let tempvalue = data.result.data;
          let rest1 = this.variantselected;
          const found = tempvalue.find(element => element.variant_code == rest1);
          this.exshowroomprice = found.exsh_price;
          this.onroadprice = Math.round(this.exshowroomprice);
          this.totalonroad_price = Math.round(this.exshowroomprice);
       //   console.log("found--exsh_price-->", found);
          if(isNaN(this.exshowroomprice)||(this.exshowroomprice==undefined)){
            this.exshowroomprice ='';
            this.toaster.show("No price available for the selcted variant");
          }
          this.url = this.sanitizer.bypassSecurityTrustResourceUrl("https://hyper-m.cygnusa.in/emicalculator/quotation.html?loanamt=" + this.exshowroomprice);
        } else if (data.result.status == 401 && data.result.response == 'failed') {
          this.toaster.show(data.result.message);



        } else if (data.result.status == 406 && data.result.response == 'failed') {
          this.toaster.show(data.result.message);
        }
      });

      //  else {
      //    this.modelselected = '';
      //    this.variantselected = '';
      //    this.colorselected = '';
      //    this.is_checked = true;
      //    this.down_payment = false;
      //    this.down_payment_check = false;
      //    this.is_enable_graph = true;
      //    this.exshowroomprice =0;
      //    this.ex_showroomprice();

      //  }
    }
    else if (this.previousurl == 'mobile' && this.new_url == 'new') {
      LocalStorage.setValue('token', this.useridvalue);
      this.getuserdetails() //Get Authentication token 
      this.selecteddse=''; 
      this.modelselected = '';
      this.variantselected = '';
      this.colorselected = '';
      this.is_checked = true;
      this.down_payment = false;
      this.down_payment_check = false;
      this.is_enable_graph = true;
      this.exshowroomprice = 0;
      if( param_userid==undefined){
        this.onroad_input_value=  LocalStorage.getValue('onroad_price')
      }
      
      // LocalStorage.setValue('onroad_price', this.totalonroad_price);
      this.ex_showroomprice();

    }
    else if (this.previousurl == 'quote-emi') {
   //   console.log("req-->", LocalStorage.getValue('quote_emi'));
      this.vardata_isable=true;
      this.onroad_value = true;
      this.vardata_isable = true;
      this.exshowroomprice = LocalStorage.getValue('quote_emi').exsh_price;
      this.onroad_input_value = LocalStorage.getValue('quote_emi').total_price;
      this.modelselected = LocalStorage.getValue('quote_emi').model;
      this.variantselected = LocalStorage.getValue('quote_emi').variant;
      this.colorselected = LocalStorage.getValue('quote_emi').color;
      this.selecteddse=LocalStorage.getValue('quote_emi').dse;
      this.is_checked = true;
      this.down_payment = false;
      this.down_payment_check = false;
      this.is_enable_graph = true;
      this.ex_showroomprice();
    } else if (this.previousurl == 'quote-emi-quote') {
   //   console.log("req-->", LocalStorage.getValue('quote_emi_quote'));
      this.onroad_value = true;
      this.vardata_isable = true;
      this.exshowroomprice = LocalStorage.getValue('quote_emi_quote').exsh_price;
      this.onroad_input_value = LocalStorage.getValue('quote_emi_quote').total_price;
      this.modelselected = LocalStorage.getValue('quote_emi_quote').model;
      this.variantselected = LocalStorage.getValue('quote_emi_quote').variant;
      this.colorselected = LocalStorage.getValue('quote_emi_quote').color;
      this.selecteddse=LocalStorage.getValue('quote_emi_quote').dse;
      this.is_checked = true;
      this.down_payment = false;
      this.down_payment_check = false;
      this.is_enable_graph = true;
      this.ex_showroomprice();
    }
    if(LocalStorage.getValue("mobile_url_check")== 'inner-emi'){
      this.mobile_back=true;
      this.selecteddse=param_dse; 
    //  console.log('selecteddse', this.selecteddse);
      this.smpinselected=param_dse; 
      LocalStorage.setValue('token', this.useridvalue);
    }

    if (this.colorselected == undefined || this.variantselected == undefined || this.modelselected == undefined) {
      this.modelselected = '';
      this.variantselected = '';
      this.colorselected = '';
    }

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


    this.getcommondetails();
    //  this.url = this.sanitizer.bypassSecurityTrustResourceUrl("https://hyper-m.cygnusa.in/emicalculator/quotation.html?loanamt=2000");
  }

  //==
  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;

      }
      else if (data.result.status == 401 && data.result.response == 'failed') {
        this.router.navigateByUrl('');
      }
      else {
        alert("Oops something happened!");
      }
    })
  }

  getcommondetails() {

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


    this.loader = true;
    this.server.get("enquiry/common/" + this.smpinselected)
      .then((data) => {

        if (data.status == 200 && data.result.response != 'failed') {
          this.loader = false;
          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) {
          this.toaster.show(data.result.message);
          //alert(data.result.message)
        }
        else if (data.result.status == 401 && data.result.response == 'failed') {

        }
      });
  }

  mobilereturn(){
    let param_ur=LocalStorage.getValue("mobile_url");
    this.router.navigateByUrl(param_ur);
    LocalStorage.setValue("mobile_value_return","mobile_back_url");
  }
  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() {
    let smpinvalue = LocalStorage.getValue('setdseselected')
    this.smpinselected = smpinvalue


    // 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.previousurl == '' || this.previousurl == null || this.previousurl == undefined) || (this.new_url == 'new')) {
      this.is_enable_graph = true;
      let req = {
        model: this.modelselected

      }
      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);
          let tempvalue = data.result.data;
          let rest1 = this.variantselected;
          const found = tempvalue.find(element => element.variant_code == rest1);
          this.exshowroomprice = found.exsh_price;
          if(isNaN(this.exshowroomprice)||(this.exshowroomprice==undefined)){
            this.exshowroomprice ='';
            this.toaster.show("No price available for the selcted variant");
          };
         // console.log("found--exsh_price-->", found);
          this.url = this.sanitizer.bypassSecurityTrustResourceUrl("https://hyper-m.cygnusa.in/emicalculator/quotation.html?loanamt=" + this.exshowroomprice);
        } else if (data.result.status == 401 && data.result.response == 'failed') {
          this.toaster.show(data.result.message);



        } else if (data.result.status == 406 && data.result.response == 'failed') {
          this.toaster.show(data.result.message);
        }
      });
    }


  }

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

    let req = {
      model: this.modelselected

    }
    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);
        let tempvalue = data.result.data;
        let rest1 = this.variantselected;
        const found = tempvalue.find(element => element.variant_code == rest1);



        this.exshowroomprice = found.exsh_price;
        this.onroadprice = Math.round(this.exshowroomprice);
        this.totalonroad_price = Math.round(this.exshowroomprice);
      //  console.log("found--exsh_price-->", found);

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



      } else if (data.result.status == 406 && data.result.response == 'failed') {
        this.toaster.show(data.result.message);
      }
    });
  }
  ex_showroomprice() {

    if (LocalStorage.getValue('check_path') == 'dealer-emi-calculator') {
      this.downpayment_input_value = 0;
      this.onroad_input = false;
      this.down_payment = true;
      this.onroad_check = false;
      this.down_payment_check = true;
      this.url = this.sanitizer.bypassSecurityTrustResourceUrl("https://hyper-m.cygnusa.in/emicalculator/quotation.html?loanamt=" + this.exshowroomprice);


    } else {
      this.onroad_input_value = 0;
      this.downpayment_input_value = 0;
      this.onroad_input = false;
      this.down_payment = true;
      this.onroad_check = false;
      this.down_payment_check = true;
      this.is_enable_graph = true;
      this.url = this.sanitizer.bypassSecurityTrustResourceUrl("https://hyper-m.cygnusa.in/emicalculator/quotation.html?loanamt=" + this.exshowroomprice);
    }


  }

  on_roadprice() {
    if (this.previousurl == 'quote-emi') {
      this.onroad_input_value= LocalStorage.getValue('onroad_price');
      this.downpayment_input_value = 0;
      this.onroad_input = true;
      this.down_payment = true;
      this.onroad_check = true;
      this.calculate();
    }
    else if (this.previousurl == 'quote-emi-quote') {
      this.onroad_input_value= LocalStorage.getValue('onroad_price');
      this.downpayment_input_value = 0;
      this.onroad_input = true;
      this.down_payment = true;
      this.onroad_check = true;
      this.calculate();
    } else if (this.previousurl == 'mobile' && this.new_url != 'new') {
  
      // console.log("this.new_url",this.new_url);
      // if(this.new_url == undefined){
      //   this.mobile_back=true;
      //   console.log("sdddd checkd");
      //   this.exshowroomprice= this.exshowroomprice;
      //   this.onroad_input_value= LocalStorage.getValue('onroad_price'); 
      //   this.downpayment_input_value = 0;
      //   this.onroad_input = true;
      //   this.down_payment = true;
      //   this.onroad_check = true;
      //   this.url = this.sanitizer.bypassSecurityTrustResourceUrl("https://hyper-m.cygnusa.in/emicalculator/quotation.html?loanamt=" + this.exshowroomprice);
      //   this.calculate();
      // }else{
      //   console.log("sdd");
      //   this.exshowroomprice= this.exshowroomprice;
      //   this.onroad_input_value=this.totalonroad_price; 
      //   this.downpayment_input_value = 0;
      //   this.onroad_input = true;
      //   this.down_payment = true;
      //   this.onroad_check = true;
      //   this.calculate();
      // }
      
      

      if(LocalStorage.getValue("mobile_url_check")== 'inner-emi'){
        this.mobile_back=true;
     //   console.log("sdddd checkd");
        this.exshowroomprice= this.exshowroomprice;
        this.onroad_input_value= LocalStorage.getValue('onroad_price'); 
        this.downpayment_input_value = 0;
        this.onroad_input = true;
        this.down_payment = true;
        this.onroad_check = true;
        this.url = this.sanitizer.bypassSecurityTrustResourceUrl("https://hyper-m.cygnusa.in/emicalculator/quotation.html?loanamt=" + this.exshowroomprice);
        this.calculate();
      }
      else{
     //   console.log("sdd");
        this.exshowroomprice= this.exshowroomprice;
        this.onroad_input_value=this.totalonroad_price; 
        this.downpayment_input_value = 0;
        this.onroad_input = true;
        this.down_payment = true;
        this.onroad_check = true;
        this.calculate();
      }

    }

    else {
      this.onroad_input_value = 0;
      this.downpayment_input_value = 0;
      this.onroad_input = true;
      this.down_payment = true;
      this.onroad_check = true;
      this.calculate();
    }

  }

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

  selectdse(){
    this.modelselected='';
    this.variantselected='';
    this.colorselected='';
    LocalStorage.setValue("setdseselected",this.selecteddse);
    this.smpinselected = this.selecteddse;
    this.getcommondetails();
   
  
  }
  calculate() {


    if (this.check_val() == true) {

      if (this.onroad_check == true) {
        // if (parseFloat(this.onroad_input_value) < parseFloat(this.exshowroomprice)) {
        //   console.log("this.onroad_input_value:-->", this.onroad_input_value)
        //   console.log("this.exshowroomprice:-->", this.exshowroomprice)
        //   //this.toaster.show("On Road price is should not less than exshowroom price");
        //   this.toaster.show(" On-road price can not be less than Ex-Showroom Price");   
        //   console.log("onroad_check if")
        // } else
         if (parseFloat(this.downpayment_input_value) > parseFloat(this.onroad_input_value)) {
          this.toaster.show("Down payment should  not greater than On Road price")
        }
        else if (parseFloat(this.downpayment_input_value) == parseFloat(this.onroad_input_value) &&  parseFloat(this.onroad_input_value)!=0) {
          this.toaster.show("Down payment should not equal to On Road price")
        } else {
        //  console.log("this.onroad_input_value:-->", this.onroad_input_value)
        //  console.log("this.exshowroomprice:-->", this.exshowroomprice)
          let ans;
          this.is_enable_graph = true;
          ans = this.onroad_input_value - this.downpayment_input_value;
        //  console.log("After dectution onroad-->", ans)
          this.url = this.sanitizer.bypassSecurityTrustResourceUrl("https://hyper-m.cygnusa.in/emicalculator/quotation.html?loanamt=" + ans);
        //  console.log("onroad_check else")
        }
      } else if (this.down_payment_check == true) {
        if (parseFloat(this.downpayment_input_value) > parseFloat(this.exshowroomprice)) {
          this.toaster.show("Down payment should not greater than exshowroom price")
        }
        else if (parseFloat(this.downpayment_input_value) == parseFloat(this.exshowroomprice)) {
          this.toaster.show("Down payment should not equal to exshowroom price")
        }

        else {
          let ans;
          this.is_enable_graph = true;
          ans = this.exshowroomprice - this.downpayment_input_value;
         // console.log("After dectution down_payment-->", ans)
          this.url = this.sanitizer.bypassSecurityTrustResourceUrl("https://hyper-m.cygnusa.in/emicalculator/quotation.html?loanamt=" + ans);
        }

      } else {
        this.is_enable_graph = false;
        this.toaster.show("Click any one Price Type")
      }

    } else {
    //  console.log("not_check")
    }
  }


  check_val() {
    if (this.selecteddse == '' || this.selecteddse == undefined) {
      this.dseerr = true;
    } else {
      this.dseerr = false;
    }

    if (this.modelselected == '' || this.modelselected == undefined) {
      this.modelerr = true;
    } else {
      this.modelerr = false;
    }
    if (this.variantselected == '' || this.variantselected == undefined) {
      this.varianterr = true;
    } else {
      this.varianterr = false;
    }
    if (this.colorselected == '' || this.colorselected == undefined) {
      this.colorerr = true;
    } else {
      this.colorerr = false;
    }
    if (this.modelerr || this.varianterr || this.colorerr) {
      return false
    } else {
      return true;
    }
  }
  //==
   //==resetextrafields===
   resetextrafields(){
    this.exshowroomprice='';
    this.onroad_input_value='';
    this.downpayment_input_value=''
  }
}

