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 * 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';
declare var $: $;
import { CONFIG } from '../../config';
import { TaskstatusDealerComponent } from "../taskstatus-dealer/taskstatus-dealer.component";

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

  loader: boolean=false;
  @ViewChild(ConfirmPopupComponent) confirm_modal: ConfirmPopupComponent;
  @ViewChild(TaskstatusDealerComponent) taskmodal: TaskstatusDealerComponent;
  sales_date: any;
  date_now: any;
  yearpresent:any;
  monthpresent:any;
  enquirylist:any=[];
  enquirydata:any=[];
  nextfollowup:any=[];
  modeofcontact:any='';
  followupform: FormGroup;
  statuscheck:any='';
  followupdate:any='';
  timearr:any=[];
  modeofcontactarr:any=[];
  purposearr:any=[];
  submittedvalue:boolean=false;
  idvalue:any='';
  smpinselected:any='';
  smpinselectedname:any='';

  statuscheckvalue: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',
        
 };


 lostmodelarr:any=[];
 lostreasonarr:any=[];
 postponedreasonarr:any=[];

 subreasonarr:any=[];

 lostmodel:any='';
  lostreason:any='';
  postponedreason:any='';

  selectedtypearr:any=[];
  allmodelarr:any=[];




  constructor(
    private server: HyperService, 
    private router: Router,
    private _eref: ElementRef,
    private route: ActivatedRoute,
    private formBuilder: FormBuilder,
    private toaster: ToasterService
    ) {
      
        
    }

  ngOnInit() {
    this.statuscheck='';
    this.smpinselected=LocalStorage.getValue('setdseselected');
  //  console.log("setdseselected--->",this.smpinselected);
    this.smpinselectedname=LocalStorage.getValue('setdseselectedname');

    this.idvalue='';
    this.sales_date = moment().format("MMM YYYY")//current month and year
    this.date_now = moment(this.sales_date, "MMM YYYY").format("MMM YYYY");
    let m = moment(this.sales_date, "MMM YYYY").format("MM");
    let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
    this.yearpresent=y;
    this.monthpresent=m;

    let yrval = LocalStorage.getValue('yearvalueinitial');
    let mhval =   LocalStorage.getValue('monthvalueinitial');
    if((yrval !=''&& mhval!='')&&(yrval !=undefined&& mhval!=undefined)){
      this.sales_date = moment(mhval+"-25-"+yrval).format("MMM YYYY")//current month and year
      this.date_now = moment(this.sales_date, "MMM YYYY").format("MMM YYYY");
      let m = moment(this.sales_date, "MMM YYYY").format("MM");
      let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
      this.yearpresent=y;
      this.monthpresent=m;
    }
    else{
      this.sales_date = moment().format("MMM YYYY")//current month and year
    this.date_now = moment(this.sales_date, "MMM YYYY").format("MMM YYYY");
    let m = moment(this.sales_date, "MMM YYYY").format("MM");
    let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
    this.yearpresent=y;
    this.monthpresent=m;
    }

    this.submittedvalue=false;
    var date12 = new Date()
    this.idvalue=LocalStorage.getValue('selectedidvalue');
    //console.log("this.idvalue--->",this.idvalue);
    // Add a day
    var date29 =  date12.setDate(date12.getDate() + 1)
   
    var date30 =  new Date(date29);
    this.followupdate=date30;
   
    this.getcommondetails()
    this.formBuild();
    this.enquirylist=[];
    this.enquirydata=[];
    LocalStorage.setValue("activity_check",'activity_check');
    var urlvalue='nonmyenquiries';
    this.taskmodal.getmonthbaseddetails(this.yearpresent,this.monthpresent,urlvalue)
    this.getenquirydetails();
    this.followupform.controls['remarks'].setValue('');
    this.followupform.controls['modeofcontact'].setValue('');
    this.followupform.controls['nextfollowup'].setValue('');
    this.followupform.controls['timeval'].setValue('10:00');
    this.followupform.controls['followupdatefm'].setValue(date30);
    $('.selectpicker').selectpicker('refresh');
  }
  getenquirydetails(){
    this.statuscheckvalue='';
    this.loader = true;
    let tempvalue=this.idvalue;
    this.server.get("dealerenquiry/details/" +this.smpinselected+ "/" +tempvalue)
    .then((data) => {
      this.loader = false;
        if (data.status == 200 && data.result.response != 'failed') {
          this.enquirydata=data.result.data;
        //   console.log("this.enquirydata--->",this.enquirydata.created_on);


        let temp1 = this.enquirydata.newvechicledate;
        let temp2=temp1.split('-');
       let newvechicledate = temp2[2]+"-"+temp2[1]+"-"+temp2[0];
       this.enquirydata.newvechicledate=newvechicledate;
       
         
            let mobileno=this.enquirydata.mobile;
            let mobileno1 = mobileno.substring(0, 2)
            let mobileno2 = mobileno.substring(8, 11)
            this.enquirydata.custmobile="XXXXXXXX"+mobileno2;
          
            this.statuscheckvalue=this.enquirydata.status;
           

          this.enquirylist=this.enquirydata.history;
          let temp = this.enquirylist.find(element => element.status == 'Lost');
          console.log("temp--->",temp);
          if(temp == undefined){

          }else{
            this.statuscheckvalue='L';
          }
       
          
         
        }else if (data.result.status == 406 ) {
        }
         else if (data.result.status == 401 && data.result.response == 'failed') {}
    });
  }
  //==
  clear_insert(){
    this.ngOnInit();
  }
  insertfollowup(){
    // alert("222");
    if(this.statuscheck == 'L'){
      this.followupform.controls['modeofcontact'].setValue('0');
      this.followupform.controls['nextfollowup'].setValue('0');
    }
    this.submittedvalue=true;

    
    if (this.followupform.valid) {
      console.log("valid");
      let dateval=this.followupdate;
      let d1 = new Date(dateval);
      let dateinsertion = moment(d1).format("DD-MM-YYYY");

      

      let req={
        id:this.idvalue,
        newvechicledate:dateinsertion,
        newvechicletime:this.followupform.controls['timeval'].value,
        modeofcontact:this.followupform.controls['nextfollowup'].value,
        status:this.statuscheck,
        nextfollowup:this.followupform.controls['modeofcontact'].value,
        followup_remark:this.followupform.controls['remarks'].value,
        reason:this.followupform.controls['reason'].value,
        subreason:this.followupform.controls['subreason'].value,
        lostdealer:this.followupform.controls['dealervalue'].value,
        lostmodel:this.followupform.controls['allmodel'].value

      }
       //return false;
 
 
       this.server.post("dealerenquiry/followup/"+this.smpinselected, req).then((data) => {
           if (data.status == 200 && data.result.response != 'failed') {
             $("#follow-modal").modal("hide");
             this.confirm_modal.displaysuccessModal(data);
           } else if (data.result.status == 401 && data.result.response == 'failed') {
               this.router.navigateByUrl('');
           }else if (data.result.status == 406 && data.result.response == 'failed') {
            this.submittedvalue=false;
             this.confirm_modal.showerrormodal(data);
             
         }
       });
     }else{
       console.log("not valid ")
       this.validateAllFormFields(this.followupform);
     }
    
   }
  formBuild() {
    this.followupform = this.formBuilder.group({
      remarks: [''],
      modeofcontact:[''],
      nextfollowup:[''],
      followupdatefm: [''],
      timeval: [''],
      reason:[''],
      subreason:[''],
      allmodel:[''],
      dealervalue:['']
      

    });
  }
  backactionhistory(){
    let tempvalue=LocalStorage.getValue('sessionstatusvalue');
 //   console.log("tempvalue--->",tempvalue);
    this.router.navigateByUrl(tempvalue);
  }
  //==
 getcommondetails() {
    this.server.get("enquiry/followupcommon")
    .then((data) => {
        if (data.status == 200 && data.result.response != 'failed') {
     //   console.log("getcommondetails--->",data);
        this.timearr=data.result.data.time;
        this.modeofcontactarr=data.result.data.modeofcontact;
        this.purposearr=data.result.data.purpose;
        this.allmodelarr=data.result.data.lost_model;
        this.lostreasonarr=data.result.data.lostreason;
        this.postponedreasonarr=data.result.data.postponedreason;

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

         }
    });
  }
  updateclick(){
    var date12 = new Date()
    var date29 =  date12.setDate(date12.getDate() + 1)
   
    var date30 =  new Date(date29);
    this.followupdate=date30;
    this.submittedvalue=false;
    this.statuscheck='';
    this.followupform.controls['remarks'].setValue('');
    this.followupform.controls['modeofcontact'].setValue('');
    this.followupform.controls['nextfollowup'].setValue('');
    this.followupform.controls['reason'].setValue('');
    this.followupform.controls['subreason'].setValue('');
    this.followupform.controls['allmodel'].setValue('');
    this.followupform.controls['dealervalue'].setValue('');
    this.followupform.controls['timeval'].setValue('10:00');
    this.followupform.controls['followupdatefm'].setValue(date30);
  }
  //==
  createtestride(){
   // alert("3333")
    //this.router.navigateByUrl('create-enquiry');
    this.router.navigateByUrl('dealer-create-enquiry');
  }
  statusclick(temp){
    this.followupform.controls['reason'].setValue('');
    this.followupform.controls['subreason'].setValue('');
    this.followupform.controls['allmodel'].setValue('');
    this.followupform.controls['nextfollowup'].setValue('');
    this.followupform.controls['modeofcontact'].setValue('');
    this.followupform.controls['remarks'].setValue('');
    
    if(temp =='hot'){
      this.statuscheck='H';
    }else if(temp =='warm'){
      this.statuscheck='W';
    }else if(temp =='cold'){
      this.statuscheck='P';
    }else if(temp =='lost'){
      this.submittedvalue=false;
      this.statuscheck='L';
      this.selectedtypearr=this.lostreasonarr;
      this.followupform.controls['reason'].setValue('');
      this.followupform.controls['subreason'].setValue('');
      this.lostmodelarr=this.allmodelarr;
      this.followupform.controls['allmodel'].setValue('');
    }else if(temp =='postponed'){
      this.submittedvalue=false;
      this.statuscheck='E';
      this.selectedtypearr=this.postponedreasonarr;
      this.followupform.controls['reason'].setValue('');
      this.followupform.controls['subreason'].setValue('');
      this.lostmodelarr=this.allmodelarr;
      this.followupform.controls['allmodel'].setValue('');
    }else {
      this.statuscheck='';
    }
  }
  //==
  selectmodeofcontact(tempval){

  }
  //==
  selectpurpose(tempval){

  }
  selecttime(tempval){

  }
  selectreason(tempval){
    const found = this.selectedtypearr.find(element => element.title_code == this.followupform.controls['reason'].value);
    if(found == undefined){
      this.subreasonarr=[];
    }else{
      this.subreasonarr=found.subreason;
      this.followupform.controls['subreason'].setValue('');
    }
  }
  selectsubreason(tempval){

  }
  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);
        }
    });
  }
  sendtolist(tempvar){
  //  console.log("tempvar-->",tempvar);
    if(tempvar == 'list'){
      this.getenquirydetails();
     // this.router.navigateByUrl('action-history');
    }else{

    }
  }





}

