import { Component, OnInit, ViewChild, Output, ElementRef, EventEmitter, AfterViewInit, ChangeDetectorRef } from '@angular/core';
import { HyperService } from '../../core/services/http.service';
import { Router, RouterModule, Routes, ActivatedRoute } from '@angular/router';
import { LocalStorage } from '../../core/services/local_storage.service';
import { TaskstatusManagerComponent } from "../taskstatus-manager/taskstatus-manager.component";
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { DatePipe } from '@angular/common';
import * as moment from 'moment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { CONFIG } from '../../config';
declare var $: any;

@Component({
  selector: 'app-enquiry-status-dealer',
  templateUrl: './enquiry-status-manager.component.html',
  styleUrls: ['./enquiry-status-manager.component.scss']
})
export class EnquiryStatusManagerComponent implements OnInit {
  loader: boolean;
  is_modal_visible: boolean;
  screen_callback: any;
  sales_list: any = [];
  taskslist: any = [];
  CurrentTime: any;
  today: number = Date.now();
  sales_date: any;
  date_now: any;
  today_personal_visit: any;
  today_personal_testride: any;
  today_personal_call: any;
  today_pending_visit: any;
  today_pending_testride: any;
  today_pending_call: 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_lost: any;
  status_hot: any;
  status_warm: any;
  status_cold: any;
  id: any;
  pendingval: any;
  yearpresent: any;
  monthpresent: any;
  searchvalue: any;
  selecteddse:any='';
  displayactivehot: boolean = false;
  displayactivewarm: boolean = false;
  displayactivecold: boolean = false;
  displayactivelost: boolean = false;
  total_item: number;
  page_per_size: number = 10;
  current_page: number;
  total_page: number;
  activePage: number = 1;
  page_count: number;
  activeItem: number = -1;
  interval_time: any;
  task_name: any = '';
  page: any;
  smpinselected: any = '';
  smpinselectedname: any = '';
  selecteduserrole: any = '';
  selecteddealer:any='';
  dealerlist: any = [];
  dselist: any = [];
  setdealerselectednameobj:any='';
  setdseselectednameobj:any='';
  setamselectednameobj:any='';
  setrmselectednameobj:any='';
  selectedareamanager:any='';
  selectedregionalmanager:any='';
  setzmselectednameobj:any='';


  constructor(
    private server: HyperService,
    private router: Router,
    private _eref: ElementRef,
    private route: ActivatedRoute
  ) {


  }


  @ViewChild(TaskstatusManagerComponent) taskmodal: TaskstatusManagerComponent;
  ngOnInit() {
    this.getDashboardstatic();

  

  //==

  this.selecteduserrole = LocalStorage.getValue('selecteduserrole');
  let setdealerselectedname =  LocalStorage.getValue("setdealerselectedname");
  let setdseselectedname =  LocalStorage.getValue("setdseselectedname");
  let setamselectedname =  LocalStorage.getValue("setamselectedname");
  let setrmselectedname =  LocalStorage.getValue("setrmselectedname");
  let setzmselectedname =  LocalStorage.getValue("setzmselectedname");
  if(setzmselectedname ==undefined){
    this.setzmselectednameobj='';
  }else{
this.setzmselectednameobj=setzmselectedname;
 }

  if(setdealerselectedname ==undefined){
    this.setdealerselectednameobj='';
  }else{
    this.setdealerselectednameobj=setdealerselectedname;
  }

  if(setdseselectedname ==undefined){
    this.setdseselectednameobj='';
  }else{
    this.setdseselectednameobj=setdseselectedname;
  }

  if(setamselectedname ==undefined){
    this.setamselectednameobj='';
  }else{
    this.setamselectednameobj=setamselectedname;
  }

  if(setrmselectedname ==undefined){
    this.setrmselectednameobj='';
  }else{
    this.setrmselectednameobj=setrmselectedname;
  }

  //==



    console.log("setdealerselectedname---->",setdealerselectedname);
    console.log("setdseselectedname---->",setdseselectedname);

    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.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.smpinselected = LocalStorage.getValue('setdseselected');
    this.smpinselectedname = LocalStorage.getValue('setdseselectedname');
    console.log("setdseselected--->", this.smpinselected);
    let selecteduserrole = LocalStorage.getValue('selecteduserrole');
    this.selecteduserrole = LocalStorage.getValue('selecteduserrole');

    let smpinvalue=LocalStorage.getValue('setdseselected');
    let dealerselected=LocalStorage.getValue('selecteddealervalue');
    let areamanagerselected=LocalStorage.getValue('selectedamvalue');
    let regionalmanagerselected=LocalStorage.getValue('selectedrmvalue');

    if(areamanagerselected != undefined){
      this.selectedareamanager=areamanagerselected;
    }else{
      this.selectedareamanager='';
    }
   
    if(regionalmanagerselected != undefined){
      this.selectedregionalmanager=regionalmanagerselected;
    }else{
      this.selectedregionalmanager='';
    }
    
    this.current_page = 0;
    this.activePage = 0;
    this.total_item = 0;
    this.taskslist = [];
    this.displayactivehot = false;
    this.displayactivewarm = false;
    this.displayactivecold = false;
    this.displayactivelost = false;

    this.route.params.subscribe(params => {
      this.displayactivehot = false;
      this.displayactivewarm = false;
      this.displayactivecold = false;
      this.displayactivelost = false;


      let temp = params['id'];

      this.id = temp;
      LocalStorage.setValue('sessionstatusvalue', 'manager-enquiry-status/' + temp);
      if (temp == 'hot') {
        this.displayactivehot = true;
        this.task_name = 'HOT';
      } else if (temp == 'warm') {
        this.displayactivewarm = true;
        this.task_name = 'WARM';
      }
      else if (temp == 'cold') {
        this.displayactivecold = true;
        this.task_name = 'COLD';
      } else if (temp == 'lost') {
        this.displayactivelost = true;
        this.task_name = 'Lost';
      } else {

      }

      // this.task_name=temp;
      this.pendingval = '';
      this.getDashboardmonthbased(this.yearpresent, this.monthpresent);
      this.getalllists(this.yearpresent, this.monthpresent, 0);
      this.taskmodal.relaodtaskstatus();
    });
    //console.log(this.id);






    // if((LocalStorage.getValue('user_data')!=undefined)&&(LocalStorage.getValue('user_data')!=undefined)){
    //   this.yearpresent=LocalStorage.getValue('temp_yr');

    //   this.monthpresent=LocalStorage.getValue('temp_mth');
    // }
    this.getDashboardmonthbased(this.yearpresent, this.monthpresent);
    this.getalllists(this.yearpresent, this.monthpresent, 0);

    //  Role Based list

    if (selecteduserrole == '3') {
      // HO
      // this.getzmlist();
    } else if (selecteduserrole == '4') {
      // ZM
      // this.getrmlist();
      // this.getamlist();
      this.getdealerlist();
      this.getdselist();
    }
    else if (selecteduserrole == '6') {
      // RM
      // this.getamlist();
      this.getdealerlist();
      this.getdselist();
    }
    else if (selecteduserrole == '7') {
      //  AM
     // alert("AM");
      this.getdealerlist();
     /// this.getdselist();
    }else{
      
    }
  }


  decreasMonth() {


    let yrval = LocalStorage.getValue('yearvalueinitial');
    let mhval = LocalStorage.getValue('monthvalueinitial');
    if ((yrval != '' && mhval != '') && (yrval != undefined && mhval != undefined)) {
      this.sales_date = moment(mhval + "-25-" + yrval).add(-1, 'months').format("MMM YYYY");
      // 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.yearpresent = y;
      this.monthpresent = m;
    }
    else {
      this.sales_date = moment(this.sales_date, "MMM YYYY").add(-1, 'months').format("MMM YYYY"); //- one month
      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.yearpresent = y;
      this.monthpresent = m;
    }


    // this.sales_date = moment(this.sales_date, "MMM YYYY").add(-1, 'months').format("MMM YYYY"); //- one month
    // setTimeout(() => {
    // let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
    // let m = moment(this.sales_date, "MMM YYYY").format("MM");
    //  this.yearpresent=y;
    //  this.monthpresent=m;
    this.getalllists(this.yearpresent, this.monthpresent, 0);

    //  }, 1200);
  }
  increasMonth() {
    let now = moment(this.sales_date, "MMM YYYY").format("YYYY-MM-DD");
    let yrval = LocalStorage.getValue('yearvalueinitial');
    let mhval = LocalStorage.getValue('monthvalueinitial');
    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(mhval + "-25-" + yrval).add(1, 'months').format("MMM YYYY");
      // 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.yearpresent = y;
      this.monthpresent = m;
      this.getalllists(this.yearpresent, this.monthpresent, 0);
   // }
   // else {
      // this.sales_date = moment(this.sales_date, "MMM YYYY").add(1, 'months').format("MMM YYYY"); //- one month
      // 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.yearpresent = y;
      // this.monthpresent = m;
    //}
    // this.getDashboardmonthbased(y, m);
    

    //  }
  }
  //==
  // public getalllists(url: string = "", data: any = {}, callBack: any = null) {
  public getalllists(year, month, pagevalue: number = 0) {
    // alert("year-->"+year)
    //  alert("month-->"+month)
    this.loader = true;
    this.is_modal_visible = true;
    // this.screen_callback = callBack;
    let yval = LocalStorage.getValue('yearvalueinitial');
    let mval = LocalStorage.getValue('monthvalueinitial');
    LocalStorage.setValue("activity_check",'activity_check');
    var urlvalue = 'nonmyenquiries';
    this.taskmodal.relaodtaskstatus();

    this.server.post("managerenquiry/listdata/" + this.smpinselected + "?page=" + pagevalue + "&limit=10&filter=sort:1", {
      //  this.yearpresent=y;
      // this.monthpresent=m;
      listtype: this.id,
      date: '',
      pendingtype: this.pendingval,
      month: this.monthpresent,
      year: this.yearpresent,
      search: this.searchvalue
    }).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response != 'failed') {
        this.taskslist = data.result.data;
        this.total_item = Number(data.result.total);
        this.taskslist.forEach((element, index) => {
          let mobileno = element.mobile;
          let mobileno1 = mobileno.substring(0, 2)
          let mobileno2 = mobileno.substring(8, 11)
          this.taskslist[index].custmobile = "XXXXXXXX" + mobileno2;
        });
        // console.log("this.taskslist-->",this.taskslist);
      } else if (data.result.status == 406) { }
      else if (data.result.status == 401 && data.result.response == 'failed') { }
    });
    //====

  }
  onResetValue(valuepresent) {
    if (valuepresent == '') {
      this.current_page = 0;
      this.searchvalue = '';
      this.activePage = 0;
      this.getalllists(this.yearpresent, this.monthpresent, 0);
    }
  }
  onSearchChange() {
    this.current_page = 0;
    // this.searchvalue='';
    this.activePage = 0;
    this.getalllists(this.yearpresent, this.monthpresent, 0);
  }
  //==
  //===
  getDashboardstatic() {
    let smpinvalue = LocalStorage.getValue('setdseselected')
    this.smpinselected = smpinvalue
    this.server.get("managerenquiry/dashboard/" + this.smpinselected)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed') {
          //   console.log(data.result.data.today.visit)
          this.today_personal_visit = data.result.data.today.visit;
          this.today_personal_testride = data.result.data.today.testride;
          this.today_personal_call = data.result.data.today.call;
          //==
          this.today_pending_visit = data.result.data.pending.visit;
          this.today_pending_testride = data.result.data.pending.testride;
          this.today_pending_call = data.result.data.pending.call;


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

  }
  //===
  getDashboardmonthbased(year, month) {
    LocalStorage.setValue("temp_mth", month)
    LocalStorage.setValue("temp_yr", year)

    // this.server.get("enquiry/enquirysales/2019/02")
    this.server.get("managerenquiry/enquirysales/" + this.smpinselected + "/" + year + "/" + month + "")
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed') {
          //  this.pending_tasks=data.result.data;
          // console.log(this.pending_tasks.enquiry.target);

          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_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') { }
      });
  }
  //==

  public getServerData(event) {
    this.page_count = (event - 1);
    this.getalllists(this.yearpresent, this.monthpresent, this.page_count);
    this.onPageChange(event);
  }

  public onPageChange(event) {
    this.activeItem = -1;
    this.activePage = event;
  }

  // getPercentage() {
  //   throw new Error("Method not implemented.");
  // }
  // getPercentage_sales() {
  //   throw new Error("Method not implemented.");
  // }
  //===
  todaysTask(tempvalue) {
    this.displayactivehot = false;
    this.displayactivewarm = false;
    this.displayactivecold = false;
    this.displayactivelost = false;
    if (tempvalue == 'hot') {
      this.id = 'hot';

      this.displayactivehot = true;
    } else if (tempvalue == 'warm') {
      this.id = 'warm';
      this.displayactivewarm = true;
    } else if (tempvalue == 'cold') {
      this.id = 'cold';

      this.displayactivecold = true;
    } else if (tempvalue == 'lost') {
      this.id = 'lost';
      this.displayactivelost = true;
    } else {

    }
    this.getalllists('', '', 0);
    this.router.navigateByUrl('manager-enquiry-status/' + tempvalue);
  }
  sendfollowupdetails(param) {
    LocalStorage.setValue('selectedidvalue', '')
    LocalStorage.setValue('selectedidvalue', param.id)
    this.router.navigateByUrl('manager-action-history');
  }

    //== get dealer list
    getdealerlist() {
      this.loader = true;
      let req = {
        zmemail: "",
        rmemail: "",
        amemail: ""
      }
      this.server.post("managerenquiry/getdealerlist", req).then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response != 'failed') {
  
          
          this.dealerlist = data.result.data;
          this.dealerlist.unshift({name:'Select',value:''});
          this.selecteddealer='';
          // this.getDashboardmonthbased(this.yearvaluepresent, this.monthvaluepresent);
          
        } else if (data.result.status == 406) {
        }
        else if (data.result.status == 401 && data.result.response == 'failed') {
  
        }
      });
    }
  
    //== get dealer list
    getdselist() {
      this.loader = true;
      let req = {
        zmemail: "",
        rmemail: "",
        amemail: "",
        dealer_code:this.selecteddealer
      }
      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;
          //this.dealerlist.unshift({name:'Select',value:''});
          // this.selecteddse='';
        } else if (data.result.status == 406) {
          //alert(data.result.message)
        }
        else if (data.result.status == 401 && data.result.response == 'failed') {
  
        }
      });
    }
    //
    selectdse(event){

    }
    //=
    getdsedetails(event){

    }
      


}

