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 { TaskstatusComponent } from "../taskstatus/taskstatus.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';
import { EnquirypopupComponent } from '../enquirypopup/enquirypopup.component';
declare var $: any;

@Component({
  selector: 'app-enquiry-stage',
  templateUrl: './enquiry-stage.component.html',
  styleUrls: ['./enquiry-stage.component.scss']
})
export class EnquiryStageComponent implements OnInit {
  displayactivelost:boolean=false;
  loader: boolean=false;
  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;
  displayactivehot:boolean=false;
  displayactivewarm:boolean=false;
  displayactivecold:boolean=false;
  displayactivepostponed: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;
  constructor(
    private server: HyperService, 
    private router: Router,
    private _eref: ElementRef,
    private route: ActivatedRoute
    ) {
      
        
    }
    @ViewChild(TaskstatusComponent) taskmodal: TaskstatusComponent;
    @ViewChild(EnquirypopupComponent) content_modal: EnquirypopupComponent;

  ngOnInit() {

    this.getDashboardstatic();
    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.current_page = 0;
    this.activePage = 0;
    this.total_item=0;
    this.taskslist=[];
    this.id='';
    

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

      let temp = params['id'];
      LocalStorage.setValue('sessionstatusvalue','enquiry-stage/'+temp);
        this.id=temp;
        if(temp=='booked'){
          this.displayactivehot=true;
          this.task_name='Booked';
        }else if(temp=='invoiced'){
          this.displayactivewarm=true;
          this.task_name='Invoiced';
        }else if(temp=='lost'){
          this.displayactivelost=true;
          this.task_name='Lost';
        }else if(temp=='postponed'){
          this.displayactivepostponed=true;
          this.task_name='Postponed';
        }
        
        
      
        // this.task_name=temp;
        this.pendingval='';
        this.getDashboardmonthbased(this.yearpresent, this.monthpresent);
        this.getalllists(this.yearpresent,this.monthpresent,0);
    });
      //console.log(this.id);



    
    
    this.getDashboardmonthbased(this.yearpresent, this.monthpresent);
    this.getalllists(this.yearpresent,this.monthpresent,0);
    
   
  }
  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.getalllists(this.yearpresent, this.monthpresent,0);
  }
  increasMonth() {
    // alert("aaasas")
    let yrval = LocalStorage.getValue('yearvalueinitial');
    let mhval =   LocalStorage.getValue('monthvalueinitial');
    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(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;
    // }
    
      
  //  }
  }
  //==
  // 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;
    var urlvalue='nonmyenquiries';
    this.taskmodal.getmonthbaseddetails(year,month,urlvalue)

    this.server.post("enquiry/listdata?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() {
    this.server.get("enquiry/dashboard")
    .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("enquiry/enquirysales/" + 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){
   // alert("tempvalue-->"+tempvalue);
    this.displayactivehot=false;
    this.displayactivewarm=false;
    this.displayactivecold=false;
    this.displayactivelost=false;
    this.displayactivepostponed=false;
    this.id='';

    if(tempvalue=='booked'){
      this.id='booked';
     
      this.displayactivehot=true;
    }else if(tempvalue=='invoiced'){
      this.id='invoiced';
      this.displayactivewarm=true;
    }else if(tempvalue=='lost'){
      this.id='lost';
      this.displayactivelost=true;
    }else if(tempvalue=='postponed'){
      this.displayactivepostponed=true;
      this.id='postponed';
    }else{
      
    }
    this.getalllists(this.yearpresent,this.monthpresent,0);
    this.router.navigateByUrl('enquiry-stage/'+tempvalue);
  }
  sendfollowupdetails(param){
    LocalStorage.setValue('selectedidvalue','')
      LocalStorage.setValue('selectedidvalue',param.id)
       this.router.navigateByUrl('action-history');
  }
  testridestatus(param,mobileno){
    LocalStorage.setValue("pagevalue",'enquiry-stage/');
    this.content_modal.testridepopup(param,mobileno);
  }

}
