import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { CONFIG } from '../../../app/config';
import { HyperService } from '../../core/services/http.service';
import { LocalStorage } from '../../core/services/local_storage.service';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { EnquirypopupManagerComponent } from '../../leadmodulemanager/enquirypopup-manager/enquirypopup-manager.component';
declare var $: any;
import { Subscription } from "rxjs";
import { Observable } from "rxjs/Observable";
import { Location } from '@angular/common';
import { TaskstatusManagerComponent } from "../taskstatus-manager/taskstatus-manager.component";


@Component({
  selector: 'app-dashboard-ho',
  templateUrl: './dashboard-ho.component.html',
  styleUrls: ['./dashboard-ho.component.scss']
})
export class DashboardHoComponent implements OnInit {

  setsmpin: any = [];

  zmlist: any = [];
  rmlist: any = [];
  amlist: any = [];
  dealerlist: any = [];
  dselist: any = [];

  enquiryform: FormGroup;
  selecteddse: any = '';
  commonsmpin: any;

  otpform1: FormGroup;
  today_personal_visit: any;
  today_personal_testride: any;
  today_personal_call: any;
  today_pending_visit: any;
  today_pending_testride: any;
  today_pending_call: any;
  pending_tasks: any;
  month_enquiry_target: any;
  month_enquiry_achieved: any;
  month_enquiry_month: any;
  month_enquiry_year: any;
  month_sales_target: any;
  month_sales_achieved: any;
  month_sales_month: any;
  month_sales_year: any;
  stage_testride: any;
  stage_booked: any;
  stage_invoiced: any;
  stage_delivered:any;
  stage_lost: any;
  status_hot: any;
  status_warm: any;
  status_cold: any;
  sales_date: any;
  date_now: any;
  barChartDataa: any = [];
  barchart_data: any = [];
  barChartOptions: any;
  user_dashboard: any;
  percentage_enquiry: any;
  percentage_sales: any;
  // sales_list: any = [];
  titleenquiry: any;
  titlesales: any;
  varstatus: any;
  otpform: FormGroup;
  mpin1: any = '';
  mpin2: any = '';
  mpin3: any = '';
  mpin4: any = '';
  otp1: any = '';
  otp2: any = '';
  otp3: any = '';
  otp4: any = '';
  mpin_error: boolean = false;
  mpin_error1: boolean = false;
  isGetOtp: boolean = false;
  new_pin: boolean = false;
  isGetOtpChange: boolean = false;
  new_pin_change: boolean = false;
  resend_enable: boolean = false;
  otp: any = '';
  create_mpin: string = '';
  confirm_mpin: string = '';
  loader: boolean;
  loader_timing: any;
  loader_delay: any;
  isTimerRunning: boolean = false;
  otp_expiry: number;
  stream$;
  sub: Subscription;
  countdown: any;
  walletpin: string = '';
  wallet_pin: string = '';
  pin_error: boolean = false;
  is_exist: any = '';
  passwordPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";
  page_per_size: number = 10;
  current_page: number;
  total_page: number;
  activeItem: number = -1;
  activePage: number = 1;
  page_count: number;
  smpinselected: any = '';
  selecteduserrole: any = '';
  //==
  selectedzm:any='';
  selectedrm:any='';
  selectedam:any='';
  selecteddealer:any='';

  dsevalue: any = '';
  mpin: string = '';
  current_amount: any;
  isForgotGetOtp: boolean = false;
  smpin_forgot: any = '';
  smpin_error: boolean = false;
  smpin_error1: boolean = false;
  otp_error_data: boolean = false;
  otp_error: boolean = false;
  pin_notmatch: boolean = false;
  old_pin: any = '';
  error_msg: string = ''
  yearvaluepresent='';
  monthvaluepresent='';


 



  //==


  @ViewChild(EnquirypopupManagerComponent) content_modal: EnquirypopupManagerComponent;

  @ViewChild(TaskstatusManagerComponent) taskmodal: TaskstatusManagerComponent;



  constructor(private server: HyperService, private router: Router, private formBuilder: FormBuilder, private _location: Location) {
    // this.wallet_pin = LocalStorage.getValue('enquiry_pin');
    // //  console.log(this.wallet_pin,"this.wallet_pin")
    // if (this.wallet_pin == "" || this.wallet_pin == undefined) {
    //   this.onClickForgotPin();
    // }

  }


  ngOnInit() {
    LocalStorage.setValue("activity_check",'');
    this.getzmlist();
    this.selecteduserrole = LocalStorage.getValue('selecteduserrole');
    let enquirymodulestatus = LocalStorage.getValue('enquirymodulestatus');
    let dsedropdown= LocalStorage.getValue('setdseselected');
    let dealerdropdown= LocalStorage.getValue('selecteddealervalue');
    let amdropdown= LocalStorage.getValue('selectedamvalue');
    let rmdropdown= LocalStorage.getValue('selectedrmvalue');
    let zmdropdown= LocalStorage.getValue('selectedzmvalue');

    // alert("rmdropdown-->"+rmdropdown);
    // alert("amdropdown-->"+amdropdown);
    // alert("dealerdropdown-->"+dealerdropdown);
    // alert("dsedropdown-->"+dsedropdown);

    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
      let tempcurr = moment().format("MMM YYYY")//current month and year
        this.date_now = moment(tempcurr, "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.yearvaluepresent=y;
      this.monthvaluepresent=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");
      LocalStorage.setValue('yearvalueinitial', y);
      LocalStorage.setValue('monthvalueinitial', m);
      this.yearvaluepresent=y;
      this.monthvaluepresent=m;
      
    }


    if((dsedropdown !='')&&(dsedropdown !=undefined)&&(dealerdropdown !='')&&(dealerdropdown !=undefined)&&(amdropdown !='')&&(amdropdown !=undefined)&&(rmdropdown !='')&&(rmdropdown !=undefined)&&(zmdropdown !='')&&(zmdropdown !=undefined)){
      this.selectedzm=zmdropdown;
      this.getrmlist('1');
      this.selectedrm=rmdropdown;
      this.getamlist('1');
      this.selectedam=amdropdown;
      this.getdealerlist('1');
      this.selecteddealer=dealerdropdown;
      this.getdselist('1');
      this.selecteddse=dsedropdown;   
      this.getdsedetails('1');
      this.getDashboardmonthbased(this.yearvaluepresent, this.monthvaluepresent)
     
    }else{
      this.selectedzm='';
      this.selectedam='';
      this.selectedrm='';
      this.selecteddealer='';
      this.selecteddse='';
      this.yearvaluepresent = LocalStorage.getValue('yearvalueinitial');
      this.monthvaluepresent = LocalStorage.getValue('monthvalueinitial')
      this.getDashboardmonthbased(this.yearvaluepresent, this.monthvaluepresent)
    }
  }
 
  //===
  todaysTask(tempvalue) {

    let dsedropdown= this.selecteddse;
    let dealerdropdown= this.selecteddealer;
    let amdropdown= this.selectedam;
    let rmdropdown= this.selectedrm;
    let zmdropdown= this.selectedzm;

   
    if((dsedropdown !='')&&(dsedropdown !=undefined)&&(dealerdropdown !='')&&(dealerdropdown !=undefined)&&(amdropdown !='')&&(amdropdown !=undefined)&&(rmdropdown !='')&&(rmdropdown !=undefined)&&(zmdropdown !='')&&(zmdropdown !=undefined)){
          if (tempvalue == 'testride') {
            this.router.navigateByUrl('manager-' + tempvalue);
          } else if ((tempvalue == 'hot') || (tempvalue == 'warm') || (tempvalue == 'cold')) {
            console.log("tempvalue--->", tempvalue)
            this.router.navigateByUrl('manager-enquiry-status/' + tempvalue);
          } else if ((tempvalue == 'booked') || (tempvalue == 'invoiced') || (tempvalue == 'lost') || (tempvalue == 'postponed')) {
            console.log("tempvalue--->", tempvalue)
            this.router.navigateByUrl('manager-enquiry-stage/' + tempvalue);
          } else  if(tempvalue == 'slot'){
            this.router.navigateByUrl('manager-activity-planner');
         }else{
    
         }
         
    } else {
      this.content_modal.homanagererrorpopup()
    }




    // let smpinvalue = LocalStorage.getValue("setdseselected");
    // // alert("smpinvalue--->"+smpinvalue);
    // if ((smpinvalue == '') || (smpinvalue == undefined) || (smpinvalue == null)) {
    //   this.content_modal.zonalmanagererrorpopup()
    // } else {
    //   //alert("tempvalue---->"+tempvalue)
    //   if (tempvalue == 'testride') {
    //     this.router.navigateByUrl('manager-' + tempvalue);
    //   } else if ((tempvalue == 'hot') || (tempvalue == 'warm') || (tempvalue == 'cold')) {
    //     console.log("tempvalue--->", tempvalue)
    //     this.router.navigateByUrl('manager-enquiry-status/' + tempvalue);
    //   } else if ((tempvalue == 'booked') || (tempvalue == 'invoiced') || (tempvalue == 'lost')|| (tempvalue == 'postponed')) {
    //     console.log("tempvalue--->", tempvalue)
    //     this.router.navigateByUrl('manager-enquiry-stage/' + tempvalue);
    //   } else  if(tempvalue == 'slot'){
    //     this.router.navigateByUrl('manager-activity-planner');
    //  }else{

    //  }
    // }
  }
 
  //==
  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);
      }
    });
  }
 
  //===
  getDashboardmonthbased( year, month) {
    this.loader = true;
    LocalStorage.setValue("temp_mth", month)
    LocalStorage.setValue("temp_yr", year)
   
  
    this.taskmodal.relaodtaskstatus()

   let req = {
    zmemail:this.selectedzm,
    rmemail:this.selectedrm,
    amemail:this.selectedam,
    dealer_code:this.selecteddealer,
    smpin:this.selecteddse
  }

    this.server.post("managerenquiry/enquirysales/"+ year + "/" + month + "", req).then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response != 'failed') {
        

          this.month_enquiry_target = data.result.data.enquiry.target;
          this.month_enquiry_achieved = data.result.data.enquiry.achieved;
          this.month_enquiry_month = data.result.data.enquiry.month;
          this.month_enquiry_year = data.result.data.enquiry.year;
          //==
          this.month_sales_target = data.result.data.sales.target;
          this.month_sales_achieved = data.result.data.sales.achieved;
          this.month_sales_month = data.result.data.sales.month;
          this.month_sales_year = data.result.data.sales.year;
          //==
          this.stage_testride = data.result.data.stage.testride;
          this.stage_booked = data.result.data.stage.booked;
          this.stage_invoiced = data.result.data.stage.invoiced;
          this.stage_delivered = data.result.data.stage.delivered;
          this.stage_lost = data.result.data.stage.lost;
          //==
          this.status_hot = data.result.data.status.hot;
          this.status_warm = data.result.data.status.warm;
          this.status_cold = data.result.data.status.cold;
          //==
          this.getPercentage();
          this.getPercentage_sales();
        } else if (data.result.status == 406) {
          //alert(data.result.message)
        }
        else if (data.result.status == 401 && data.result.response == 'failed') { }
      });
  }
  //==
  decreasMonth() {
      CONFIG.configyearval = '';
      CONFIG.configmonthval = '';
      this.sales_date = moment(this.sales_date, "MMM YYYY").add(-1, 'months').format("MMM YYYY"); //- one month
      let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
      let m = moment(this.sales_date, "MMM YYYY").format("MM");
      LocalStorage.setValue('yearvalueinitial', y);
      LocalStorage.setValue('monthvalueinitial', m);
      this.yearvaluepresent=y;
      this.monthvaluepresent=m;
      this.getDashboardmonthbased( y, m);
  }
  //==
  increasMonth() {
    let smpinvalue = LocalStorage.getValue("setdseselected");
    let now = moment(this.sales_date, "MMM YYYY").format("YYYY-MM-DD");
    let tdyDate = moment(new Date()).format('YYYY-MM-DD');
    // if (moment(now).isSame(tdyDate, 'month') == false && moment(now).isSameOrBefore(tdyDate, 'year') == true) {
    this.sales_date = moment(this.sales_date, "MMM YYYY").add(1, 'months').format("MMM YYYY"); //+ one month
    let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
    let m = moment(this.sales_date, "MMM YYYY").format("MM");
    LocalStorage.setValue('yearvalueinitial', y);
    LocalStorage.setValue('monthvalueinitial', m);
    this.yearvaluepresent=y;
    this.monthvaluepresent=m;
    this.getDashboardmonthbased( y, m);
    // }
  }
  //==
  getPercentage() {
    this.percentage_enquiry = Math.floor(this.month_enquiry_achieved / this.month_enquiry_target * 100);
    this.titleenquiry = this.month_enquiry_achieved + " / " + this.month_enquiry_target;
  }
  getPercentage_sales() {
    this.percentage_sales = Math.floor(this.month_sales_achieved / this.month_sales_target * 100);
    this.titlesales = this.month_sales_achieved + " / " + this.month_sales_target;

  }

  salesDetail() {

    let dsedropdown= this.selecteddse;
    let dealerdropdown= this.selecteddealer;
    let amdropdown= this.selectedam;
    let rmdropdown= this.selectedrm;
    let zmdropdown= this.selectedrm;
   
    if((dsedropdown !='')&&(dsedropdown !=undefined)&&(dealerdropdown !='')&&(dealerdropdown !=undefined)&&(amdropdown !='')&&(amdropdown !=undefined)&&(rmdropdown !='')&&(rmdropdown !=undefined)&&(zmdropdown !='')&&(zmdropdown !=undefined)){
      this.router.navigateByUrl('manager-sales'); 
    } else {
      this.content_modal.homanagererrorpopup()
    }
  }
  //==
  Enquiry() {

    let dsedropdown= this.selecteddse;
    let dealerdropdown= this.selecteddealer;
    let amdropdown= this.selectedam;
    let rmdropdown= this.selectedrm;
    let zmdropdown= this.selectedrm;
    if((dsedropdown !='')&&(dsedropdown !=undefined)&&(dealerdropdown !='')&&(dealerdropdown !=undefined)&&(amdropdown !='')&&(amdropdown !=undefined)&&(rmdropdown !='')&&(rmdropdown !=undefined)&&(zmdropdown !='')&&(zmdropdown !=undefined)){
      this.router.navigateByUrl('manager-enquiries'); 
    } else {
      this.content_modal.homanagererrorpopup()
    }
  }


  onCloseModal() {

  }

  enquiryList() {

    let sendData: any = {};
    this.content_modal.enquirylistModal('Result', { sendData }, (data) => {
    })
  }
  onClickCancel() {
    $('#pinModal').modal('hide'); this.otp_error = false;
    this.otp_error_data = false;
    // this.router.navigateByUrl('bulletin');
    this._location.back();
  }
  //==
  onClickCancelSMpin() {
    this.isForgotGetOtp = false;
  }
  //==
  onClickCancelOtp() {
    this.isGetOtp = false;
    this._location.back();
    $('#pinModal').modal('hide');
    // this.isForgotGetOtp=true;
  }
  //==
 

  //== get ZM list
  getzmlist() {

    this.rmlist=[];
    this.amlist=[];
    this.dealerlist=[];
    this.dselist=[];

    this.selectedam='';
    this.selecteddealer='';
    this.selecteddse='';
    this.selectedrm='';


    // LocalStorage.setValue('selectedrmvalue',this.selectedrm)
    // LocalStorage.setValue('setdseselected',this.selecteddse)
    // LocalStorage.setValue('selecteddealervalue',this.selecteddealer)
    // LocalStorage.setValue('selectedamvalue',this.selectedam)
    
  
    

    this.server.post("managerenquiry/getzmlist",{}).then((data) => {
      if (data.status == 200 && data.result.response != 'failed') {
        this.zmlist = data.result.data;
        
        this.loader = false;
      } else if (data.result.status == 406) {
        //alert(data.result.message)
      }
      else if (data.result.status == 401 && data.result.response == 'failed') {

      }
    });
  }

  //== get RM list
  getrmlist(args) {


    this.amlist=[];
    this.selectedam='';
    this.dealerlist=[];
    this.selecteddealer='';
    this.dselist=[];
    this.selecteddse='';
    this.selectedrm='';
    this.rmlist=[];

     LocalStorage.setValue('selectedzmvalue',this.selectedzm)
     LocalStorage.setValue('selectedrmvalue', this.selectedrm)
     LocalStorage.setValue('selectedamvalue', this.selectedam)
    LocalStorage.setValue('selecteddealervalue', this.selecteddealer)
    LocalStorage.setValue('setdseselected', this.selecteddse)

    let tempvar='';
    if((args !='1')&&(args !='')){
      tempvar = args.target.options[args.target.selectedIndex].text;
      LocalStorage.setValue("setzmselectedname",tempvar);
    }else{
      tempvar = LocalStorage.getValue("setzmselectedname");
    }
    let req = {
      zmemail: this.selectedzm
    }
    this.server.post("managerenquiry/getrmlist", req).then((data) => {
      if (data.status == 200 && data.result.response != 'failed') {
        this.rmlist = data.result.data;
        this.loader = false;
      } else if (data.result.status == 406) {
      }
      else if (data.result.status == 401 && data.result.response == 'failed') {

      }
      if((args !='1')&&(args !='')){
      this.reloadcurrentpage()
      }
    });

  }

  //== get AM list
  getamlist(args) {


    this.amlist=[];
    this.selectedam='';
    this.dealerlist=[];
    this.selecteddealer='';
    this.dselist=[];
    this.selecteddse='';

    LocalStorage.setValue('setdseselected',this.selecteddse)
    LocalStorage.setValue('selecteddealervalue',this.selecteddealer)
    LocalStorage.setValue('selectedamvalue',this.selectedam)
     LocalStorage.setValue('selectedrmvalue',this.selectedrm)
   

    
    if(this.selectedrm !=''){
    let tempvar ='';
    if((args !='1')&&(args !='')){
      tempvar = args.target.options[args.target.selectedIndex].text;
      LocalStorage.setValue("setrmselectedname",tempvar);
    }else{
      tempvar = LocalStorage.getValue("setrmselectedname");
    }
  
    let req = {
      zmemail: this.selectedzm,
      rmemail: this.selectedrm
    }
    this.server.post("managerenquiry/getamlist", req).then((data) => {
      if (data.status == 200 && data.result.response != 'failed') {
        this.amlist = data.result.data;
       
        this.loader = false;
      } else if (data.result.status == 406) {
        
        //alert(data.result.message)
      }
      else if (data.result.status == 401 && data.result.response == 'failed') {

      }
    });
  }
  if((args !='1')&&(args !='')){
    this.reloadcurrentpage();
    } 
  }

  //== get dealer list
  getdealerlist(args) {

    this.dealerlist=[];
    this.selecteddealer='';
    this.dselist=[];
    this.selecteddse='';
     LocalStorage.setValue('selectedamvalue', this.selectedam)
    LocalStorage.setValue('selecteddealervalue', this.selecteddealer)
    LocalStorage.setValue('setdseselected', this.selecteddse)
    // 
    if(this.selectedam !=''){
    let tempvar ='';
    if((args !='1')&&(args !='')){
      tempvar = args.target.options[args.target.selectedIndex].text;
     
      LocalStorage.setValue("setamselectedname",tempvar);
    }else{
      tempvar = LocalStorage.getValue("setamselectedname");
    }


    this.loader = true;
    let req = {
      zmemail: this.selectedzm,
      rmemail: this.selectedrm,
      amemail: this.selectedam
    }
    this.server.post("managerenquiry/getdealerlist", req).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response != 'failed') {
        this.dealerlist = data.result.data;  
      } else if (data.result.status == 406) {
      
      }
      else if (data.result.status == 401 && data.result.response == 'failed') {

      }
    });
  }
  if((args !='1')&&(args !='')){
    this.reloadcurrentpage();
    } 
  }

  //== get dealer list
  getdselist(args) {
    this.dselist=[];
    this.selecteddse='';
    LocalStorage.setValue('selecteddealervalue', this.selecteddealer)
    LocalStorage.setValue('setdseselected', this.selecteddse)

    

    if(this.selecteddealer !=''){
    let tempvar ='';
    if((args !='1')&&(args !='')){
      tempvar = args.target.options[args.target.selectedIndex].text;
     
      LocalStorage.setValue("setdealerselectedname",tempvar);
    }else{
      tempvar = LocalStorage.getValue("setdealerselectedname");
    }


    this.loader = true;
    let req = {
      zmemail: this.selectedzm,
      rmemail: this.selectedrm,
      amemail: this.selectedam,
      dealer_code:this.selecteddealer,
      history:'1'
    }
    this.loader = true;
    this.server.post("managerenquiry/getdselist", req).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response != 'failed') {
        this.dselist = data.result.data;
        // var finalArr = this.dselist.filter(function(val) { return val.userstatus != "2"; });
        //   this.dselist=finalArr;
     
      } else if (data.result.status == 406) {
      
      }
      else if (data.result.status == 401 && data.result.response == 'failed') {

      }
    });
  }
  if((args !='1')&&(args !='')){
    this.reloadcurrentpage();
    } 
  }

  //==
  getdsedetails(args){
    LocalStorage.setValue('setdseselected', this.selecteddse)

    if(args !='1'){
      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");
    LocalStorage.setValue('yearvalueinitial', y);
    LocalStorage.setValue('monthvalueinitial', m);
    this.yearvaluepresent=y;
    this.monthvaluepresent=m;
    }

    let tempvar ='';
    if((args !='1')&&(args !='')){
      tempvar = args.target.options[args.target.selectedIndex].text;
      // alert("tempvar--->"+tempvar);
      LocalStorage.setValue("setdseselectedname",tempvar);
    }else{
      tempvar = LocalStorage.getValue("setdseselectedname");
    }
    if((args !='1')&&(args !='')){
      this.reloadcurrentpage();
      } 

  }
  //==
  reloadcurrentpage(){
     this.getDashboardmonthbased(this.yearvaluepresent, this.monthvaluepresent)
     
   }
}
