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-regional-manager',
  templateUrl: './dashboard-regional-manager.component.html',
  styleUrls: ['./dashboard-regional-manager.component.scss']
})
export class DashboardRegionalManagerComponent 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) {
  }


  ngOnInit() {
    LocalStorage.setValue("activity_check",'');

    this.getamlist('');
    this.selecteduserrole = LocalStorage.getValue('selecteduserrole');
    let dsedropdown= LocalStorage.getValue('setdseselected');
    let dealerdropdown= LocalStorage.getValue('selecteddealervalue');
    let amdropdown= LocalStorage.getValue('selectedamvalue');
    let enquirymodulestatus = LocalStorage.getValue('enquirymodulestatus');
    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");

      console.log("this.sales_date-->", this.sales_date)
      console.log("this.date_now-->", this.date_now)
      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)){
     
      this.selectedam=amdropdown;
      this.getdealerlist('1');
      this.selecteddealer=dealerdropdown;
      this.getdselist('1');
      this.selectedam=amdropdown;
      this.selecteddealer=dealerdropdown;
      this.selecteddse=dsedropdown;   
      this.getdsedetails('1');
      this.getDashboardmonthbased(this.yearvaluepresent, this.monthvaluepresent)
     
    }else{               
      this.selectedam='';
      this.selectedrm='';
      this.selecteddealer='';
      this.selecteddse='';
      this.yearvaluepresent = LocalStorage.getValue('yearvalueinitial');
      this.monthvaluepresent = LocalStorage.getValue('monthvalueinitial')
     
    }
    
  }

  //===
  todaysTask(tempvalue) {


    let dsedropdown= this.selecteddse;
    let dealerdropdown= this.selecteddealer;
    let amdropdown= this.selectedam;

   
    if((dsedropdown !='')&&(dsedropdown !=undefined)&&(dealerdropdown !='')&&(dealerdropdown !=undefined)&&(amdropdown !='')&&(amdropdown !=undefined)){
          //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{
    
         }
         
    } else {
      this.content_modal.regionalmanagererrorpopup()
    }
  }

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

    let req = {
      zmemail: '',
      rmemail: '',
      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.postponed;
        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) {
      }
      else if (data.result.status == 401 && data.result.response == 'failed') { }
    });
  }
  //==
  decreasMonth() {
    let smpinvalue = LocalStorage.getValue("setdseselected");
    // if ((smpinvalue == '') || (smpinvalue == undefined) || (smpinvalue == null)) {
    //   this.content_modal.dealererrorpopup()
    // } else {
      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");
    // if ((smpinvalue == '') || (smpinvalue == undefined) || (smpinvalue == null)) {
    //   this.content_modal.dealererrorpopup()
    // } else {
      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;

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

   
    if((dsedropdown !='')&&(dsedropdown !=undefined)&&(dealerdropdown !='')&&(dealerdropdown !=undefined)&&(amdropdown !='')&&(amdropdown !=undefined)){
      this.router.navigateByUrl('manager-enquiries');
    } else {
      this.content_modal.regionalmanagererrorpopup()
    }
  }


  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 AM list
  getamlist(args) {

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


    this.loader = true;
    let req = {
      zmemail: "",
      rmemail: ""
    }
    this.server.post("managerenquiry/getamlist", req).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response != 'failed') {
        this.amlist = data.result.data;
      } else if (data.result.status == 406) {
        //alert(data.result.message)  
      }
      else if (data.result.status == 401 && data.result.response == 'failed') {
      }
      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: "",
        rmemail: "",
        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;
        // alert("tempvar--->"+tempvar);
        LocalStorage.setValue("setdealerselectedname", tempvar);
      } else {
        tempvar = LocalStorage.getValue("setdealerselectedname");
      }


      this.loader = true;
      let req = {
        zmemail: "",
        rmemail: "",
        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) {
          //alert(data.result.message)
        }
        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;
    }else{

    }
    let tempvar = '';
    if (args != '1') {
      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)
    
  }

}
