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 { TaskstatusDealerComponent } from "../taskstatus-dealer/taskstatus-dealer.component";
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { DatePipe } from '@angular/common';
import * as moment from 'moment';
import { DatepickerOptions } from 'ng2-datepicker';
import * as enLocale from 'date-fns/locale/en';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { CONFIG } from '../../config';
declare var $: any;
import { EnquirypopupDealerComponent } from '../enquirypopup-dealer/enquirypopup-dealer.component';


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

  daytask_tomorrow: boolean = false;
  loader: boolean = false;
  daytask_today: boolean = false;
  followupdate: any = '';
  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;
  displaytitle; any = '';
  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 = '';
  dateinsertion: any = '';
  page: any;
  tempobj: any = '';
  displayactivetoday_visit: boolean = false;
  displayactivetoday_ride: boolean = false;
  displayactivetoday_call: boolean = false;
  todaytype: any = '';
  displayactivepending_visit: boolean = false;
  displayactivepending_ride: boolean = false;
  displayactivepending_call: boolean = false;
  displaytodayblock: boolean = false;
  smpinselected: any = '';
  smpinselectedname: any = '';

  displayactivetomorrow_visit: boolean = false;
  displayactivetomorrow_ride: boolean = false;
  displayactivetomorrow_call: boolean = false;

  daytask_customdate: boolean = false;

  testridecount:any='';

  @ViewChild(TaskstatusDealerComponent) taskmodal: TaskstatusDealerComponent;
  // total_item: number;
  // page_per_size: number = 10;
  // current_page: number;
  // total_page: number;
  // activePage: number = 1;
  // page_count: number;
  // activeItem: number = -1;

  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',

  };

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

    var date12 = new Date()
  //  console.log("day12-->", date12);
    var date29 = date12.setDate(date12.getDate())
  //  console.log("day29-->", date29);
    var date30 = new Date(date29);
    this.followupdate = date30;
  }


  @ViewChild(EnquirypopupDealerComponent) content_modal: EnquirypopupDealerComponent;

  ngOnInit() {
    this.displaytodayblock = false;
    this.smpinselected = LocalStorage.getValue('setdseselected');
    this.smpinselectedname = LocalStorage.getValue('setdseselectedname');
   // console.log("setdseselected--->", this.smpinselected);
    LocalStorage.setValue("activity_check", 'activity_check');
    let s = LocalStorage.getValue("activity_check");
    // alert(s)
    //  this.daytask('today');
    var date12 = new Date()
  //  console.log("day12-->", date12);
    var date29 = date12.setDate(date12.getDate())
  //  console.log("day29-->", date29);
    var date30 = new Date(date29);
    this.followupdate = date30;


    this.displaytodayblock = false;
    this.current_page = 0;
    this.activePage = 0;
    this.tempobj = '';

    this.displayactivetoday_visit = false;
    this.displayactivetoday_ride = false;
    this.displayactivetoday_call = false;

    this.displayactivepending_visit = false;
    this.displayactivepending_ride = false;
    this.displayactivepending_call = false;

    this.displayactivetomorrow_visit = false;
    this.displayactivetomorrow_ride = false;
    this.displayactivetomorrow_call = false;

    this.route.params.subscribe(params => {
      this.tempobj = params['id'];
      if ((this.tempobj == 'pending-call') || (this.tempobj == 'pending-testride') || (this.tempobj == 'pending-visit') || (this.tempobj == 'today-call') || (this.tempobj == 'today-visit') || (this.tempobj == 'today-testride') || (this.tempobj == 'tomorrow-testride') || (this.tempobj == 'tomorrow-visit') || (this.tempobj == 'tomorrow-call') || (this.tempobj == 'datevalentered')) {
        LocalStorage.setValue('sessionstatusvalue','dealer-task/'+this.tempobj);
        //console.log("inside if");
        let toArray = this.tempobj.split("-");
        this.displaytitle = toArray[0];
        this.id = this.displaytitle;
      //  console.log("----->", this.displaytitle);
        if (this.displaytitle == 'pending') {
          this.displaytodayblock = false;
          this.displaytitle = 'PENDING';
          this.pendingval = toArray[1];
          let temp1 = toArray[1];
          // alert("temp1-->"+temp1);
          if (temp1 == 'testride') {
            this.pendingval = 'test drive';
          }

        } else if (this.displaytitle == 'today') {
          //  this.daytask('today');
          this.displaytodayblock = true;
          this.displaytitle = 'TODAY';
          this.pendingval = '';
          let temp1 = toArray[1];
          if (temp1 == 'call') {
            this.todaytype = 'call';
          } else if (temp1 == 'visit') {
            this.todaytype = 'visit';
          } else if (temp1 == 'testride') {
            this.todaytype = 'test drive';
          } else {

          }
        } else if (this.displaytitle == 'tomorrow') {
          //  this.daytask('tomorrow');
        //  console.log("inside if----->", this.displaytitle);
          this.displaytodayblock = true;
          this.displaytitle = 'TOMORROW';
          this.pendingval = '';
          let temp1 = toArray[1];
          if (temp1 == 'call') {
            this.todaytype = 'call';
          } else if (temp1 == 'visit') {
            this.todaytype = 'visit';
          } else if (temp1 == 'testride') {
            this.todaytype = 'test drive';
          } else {

          }
        } else {
          this.displaytitle = '';
        }
        //  alert("this.pendingval--->"+this.pendingval);
        // if((this.tempobj =='pending-testride')||(this.tempobj =='today-testride')){
        //  // this.displaytitle=toArray[0];
        //   this.pendingval='test drive';
        //   //this.id=this.displaytitle;
        // }
        //  console.log("this.displaytitle--->",this.displaytitle);
        //  console.log("this.pendingval--->",this.pendingval);
      } else {

      }


      // console.log("this.tempobj ---->",this.tempobj);
      this.displayactivetoday_visit = false;
      this.displayactivetoday_ride = false;
      this.displayactivetoday_call = false;

      this.displayactivepending_visit = false;
      this.displayactivepending_ride = false;
      this.displayactivepending_call = false;

      this.displayactivetomorrow_visit = false;
      this.displayactivetomorrow_ride = false;
      this.displayactivetomorrow_call = false;

      this.daytask_today = false;
      this.daytask_tomorrow = false;
      this.daytask_customdate = false;


    //  console.log("temp---->", this.tempobj);
      if (this.tempobj == 'pending-call') {
        this.displayactivepending_call = true;
      } else if (this.tempobj == 'pending-testride') {
        this.displayactivepending_ride = true
      } else if (this.tempobj == 'pending-visit') {
        this.displayactivepending_visit = true
      } else if (this.tempobj == 'today-testride') {
        this.daytask_today = true;
        this.displayactivetoday_ride = true
      } else if (this.tempobj == 'today-visit') {
        this.daytask_today = true;
        this.displayactivetoday_visit = true
      } else if (this.tempobj == 'today-call') {
        this.daytask_today = true;
        this.displayactivetoday_call = true
      } else if (this.tempobj == 'tomorrow-testride') {
        this.displayactivetomorrow_ride = true;
        this.daytask_tomorrow = true;
      } else if (this.tempobj == 'tomorrow-visit') {
        this.daytask_tomorrow = true;
        this.displayactivetomorrow_visit = true;
        this.displayactivetomorrow_visit = true
      } else if (this.tempobj == 'tomorrow-call') {
        this.daytask_tomorrow = true;
        this.displayactivetomorrow_call = true
      } else if (this.tempobj == 'datevalentered') {
        /// alert("33333");


        this.displaytitle = 'TODAY';
        this.displaytodayblock = true;
        this.displayactivetoday_call = true;
        this.daytask_customdate = true;
        this.todaytype = 'call';

      } else {

      }

      this.getDashboardstatic();
      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.getDashboardmonthbased(this.yearpresent, this.monthpresent);
      this.getalllists(this.yearpresent, this.monthpresent, 0);
    });



  }
  //==
  // 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;
    LocalStorage.setValue("activity_check", 'activity_check');
    let urlvalue = 'notmyenquiry';
    this.taskmodal.getmonthbaseddetails(year, month, urlvalue)
    this.server.post("dealerenquiry/listdata/" + this.smpinselected + "?page=" + pagevalue + "&limit=10&filter=sort:1", {
      // this.server.post("enquiry/listdata", {
      // page: '0',
      // limit: '10',
      // filter: 'sort:1',
      listtype: this.id,
      date: this.dateinsertion,
      pendingtype: this.pendingval,
      month: '',
      year: '',
      todaytype: this.todaytype
    }).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') { }
    });
    //====

  }
  //===
  getDashboardstatic() {
    this.server.get("dealerenquiry/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("dealerenquiry/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.postponed;
          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) {

  //  console.log("tempvalue--->", tempvalue);
    this.tempobj = '';
    this.tempobj = tempvalue;
  //  console.log("this.tempobj--->", this.tempobj);
    this.displayactivetoday_visit = false;
    this.displayactivetoday_ride = false;
    this.displayactivetoday_call = false;

    this.displayactivepending_visit = false;
    this.displayactivepending_ride = false;
    this.displayactivepending_call = false;


    this.displayactivetomorrow_visit = false;
    this.displayactivetomorrow_ride = false;
    this.displayactivetomorrow_call = false;


    if (this.tempobj == 'pending-call') {
      this.displayactivepending_call = true;
    } else if (this.tempobj == 'pending-testride') {
      this.displayactivepending_ride = true;
    } else if (this.tempobj == 'pending-visit') {
      this.displayactivepending_visit = true;

    } else if (this.tempobj == 'today-testride') {
      //this.daytask('today');
      this.displayactivetoday_ride = true;
    } else if (this.tempobj == 'today-visit') {
      //this.daytask('today');
      this.displayactivetoday_visit = true;
    } else if (this.tempobj == 'today-call') {
      //this. daytask('today');
      this.displayactivetoday_call = true
    } else if (this.tempobj == 'tomorrow-testride') {
      //this.daytask('tomorrow');
      this.displayactivetomorrow_ride = true;
    } else if (this.tempobj == 'tomorrow-vist') {
      //this.daytask('tomorrow');
      this.displayactivetomorrow_visit = true;
    } else if (this.tempobj == 'tomorrow-call') {
      // this. daytask('tomorrow');
      this.displayactivetomorrow_call = true
    } else {

    }

    // let toArray =  this.tempobj.split("-");
    // this.displaytitle=toArray[0];
    // this.pendingval=toArray[1];
    // this.id=this.displaytitle;
    // //this.id='pending';
    // if(this.displaytitle =='pending'){
    //   this.displaytitle='PENDING';
    // }else if(this.displaytitle =='today'){
    //   this.displaytitle='TODAY';
    // }else{
    //   this.displaytitle='';
    // }
    // if((this.tempobj =='pending-testride')||(this.tempobj =='today-testride')){
    //   // this.displaytitle=toArray[0];
    //    this.pendingval='test drive';
    //    //this.id=this.displaytitle;
    //  }
    this.router.navigateByUrl('dealer-task/' + this.tempobj);
    //this.getDashboardmonthbased(this.yearpresent, this.monthpresent);
    //this.getalllists(this.yearpresent, this.monthpresent,0);

  }
  //==
  // daytask(temp){ 

  //   this.daytask_tomorrow=false;
  //   if(temp == 'today'){
  //     this.daytask_today=true;
  //     this.id='today';
  //     this.todaytype='';
  //     // this.followupdate='';
  //     this.dateinsertion=''; 
  //     this.daytask_tomorrow=false;
  //   }else if(temp == 'tomorrow'){
  //     this.id='tomorrow';
  //     this.todaytype='';
  //     // this.followupdate='';
  //     this.dateinsertion='';
  //     this.daytask_tomorrow=true;
  //     this.daytask_today=false;
  //   }else if(temp == 'dateval'){
  //     this.id='date';
  //     let dateval=this.followupdate;
  //     let d1 = new Date(dateval);
  //     this.dateinsertion = moment(d1).format("YYYY-MM-DD");
  //     this.todaytype=temp;
  //   }else{

  //   }
  //   this.getalllists(this.yearpresent, this.monthpresent,0);
  // }
  daytaskdateval() {
    this.daytask_customdate = true;
    this.daytask_today = false;
    this.daytask_tomorrow = false;
  }
  calulatedatebased() {
    this.id = 'date';
    let dateval = this.followupdate;
    let d1 = new Date(dateval);
    this.dateinsertion = moment(d1).format("YYYY-MM-DD");
    this.getalllists('', '');


  }
  daytask(paramvalue) {
    this.daytask_customdate = false;
    let paramsendvalue = '';
    if (paramvalue == 'today') {
      if (this.tempobj == 'tomorrow-testride') {
        this.displayactivetomorrow_ride = true;
        this.daytask_tomorrow = true;
        paramsendvalue = 'today-testride';
      } else if (this.tempobj == 'tomorrow-visit') {
        this.daytask_tomorrow = true;
        this.displayactivetomorrow_visit = true;
        this.displayactivetomorrow_visit = true
        paramsendvalue = 'today-visit';
      } else if (this.tempobj == 'tomorrow-call') {
        this.daytask_tomorrow = true;
        this.displayactivetomorrow_call = true
        paramsendvalue = 'today-call';
      } else if(this.tempobj == 'datevalentered'){
        this.daytask_tomorrow = true;
        this.displayactivetomorrow_call = true
        paramsendvalue = 'today-call';
      }else {

      }

    } else if (paramvalue == 'tomorrow') {
      if (this.tempobj == 'today-testride') {
        this.daytask_today = true;
        this.displayactivetoday_ride = true;
        paramsendvalue = 'tomorrow-testride';
      } else if (this.tempobj == 'today-visit') {
        this.daytask_today = true;
        this.displayactivetoday_visit = true
        paramsendvalue = 'tomorrow-visit';
      } else if (this.tempobj == 'today-call') {
        this.daytask_today = true;
        this.displayactivetoday_call = true;
        paramsendvalue = 'tomorrow-call';
      } else if(this.tempobj == 'datevalentered'){
        this.daytask_tomorrow = true;
        this.displayactivetomorrow_call = true
        paramsendvalue = 'tomorrow-call';
      }else {

      }
    } else {

    }
    // alert("333-->"+paramsendvalue);
    this.router.navigateByUrl('dealer-task/' + paramsendvalue);
  }
  sendfollowupdetails(param) {
    LocalStorage.setValue('selectedidvalue', '')
    LocalStorage.setValue('selectedidvalue', param.id)
    this.router.navigateByUrl('dealer-action-history');
  }
  testridestatus(param, mobileno) {
    //    LocalStorage.setValue("pagevalue",'enquiry-stage/');
    this.content_modal.testridepopup(param, mobileno);
  }
}

