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


import { DatepickerOptions } from 'ng2-datepicker';
import * as enLocale from 'date-fns/locale/en';
 import { ConfirmPopupComponent } from "../../sales_executive/confirm-popup/confirm-popup.component";
 import { LocalStorage } from '../../core/services/local_storage.service';


@Component({
  selector: 'app-enquirypopup-manager',
  templateUrl: './enquirypopup-manager.component.html',
  styleUrls: ['./enquirypopup-manager.component.scss']
})
export class EnquirypopupManagerComponent implements OnInit {
  @ViewChild(ConfirmPopupComponent) confirm_modal: ConfirmPopupComponent;

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

  is_modal_visible_regional_manager:boolean=false;
  is_modal_visible_zonal_manager:boolean=false;

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

 
 

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

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

  // }

  ngOnInit() {



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

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

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

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

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

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

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

  //==
  public dsepopup(){
    this.is_modal_visible_dse=true;
  }


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

  public dealerdseerrorpopup(){
    this.is_modal_visible_dealer_dse=true;
  }


  public regionalmanagererrorpopup(){
    this.is_modal_visible_regional_manager=true;
  }


  public zonalmanagererrorpopup(){
    this.is_modal_visible_zonal_manager=true;
  }
  public homanagererrorpopup(){
    this.is_modal_visible_ho_manager=true;
  }
  

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

  public oninitialCloseerrordealerdseModal(){
    this.is_modal_visible_dealer_dse=false;
    this.is_modal_visible_regional_manager=false;
    this.is_modal_visible_zonal_manager=false;
    this.is_modal_visible_ho_manager=false;
  }



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

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

  onCloseModal() {
    this.is_modal_visible = false;
    this.is_modal_visible_create_enquiry = false;
    this.is_modal_visible_enquirylist = false;
    this.is_modal_visible_dse = false;
    this.screen_callback(true);
    this.is_modal_visible_dealer=false;
  }
  //==
  getcreateenquirydetails() {
    this.server.get("enquiry/common")
        .then((data) => {
            if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
              this.model_list=data.result.data.model;
              this.title_list=data.result.data.title;
              this.company_list=data.result.data.company;
              this.communication_list=data.result.data.communicate;
              this.source_list=data.result.data.source;
              this.purpose_list=data.result.data.purpose;
              this.actionplan_list=data.result.data.modeofcontact;
              this.timing_list=data.result.data.time;
              this.customerage_list=data.result.data.custage;
              this.customertype_list=data.result.data.custtype;
              this.profession_list=data.result.data.profession;
           
              this.variantmodel_list=[];
            } else if (data.result.status == 401 && data.result.response == 'failed') {
                this.router.navigateByUrl('');
            }
        });
  }
  //==
  onChangeModel(ev){
    // this.variantcolor_list=[];
    this.variantmodel_list=[];
    this.variantcolor_list=[];
  //  this.enquiryForm.controls['colorselected'].setValue('');
    
   // console.log(this.enquiryForm.controls['variantselected'].setValue(''))
    let temp  = this.model_list.filter(data => data.title_code === ev);
    //console.log(temp);
    //this.enquiryForm.controls['variantselected'].setValue('');
    //temp.push()
    let select_temp=temp[0].variant;
   // select_temp["key3"] = "value3";
  //  console.log(select_temp);
    this.variantmodel_list=select_temp;
    
    //this.enquiryForm.controls['variantselected'].setValue('');
  }
  //==
  onChangeVariant(ev){
    this.variantcolor_list=[];
    let temp1  = this.variantmodel_list.filter(data => data.title_code === ev);
    this.variantcolor_list=temp1[0].color;
  }


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

