import { Component, OnInit, ViewChild, ElementRef, NgModule } from '@angular/core';
import { HyperService } from '../../core/services/http.service';
import { Router, RouterModule, Routes, ActivatedRoute } from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { DatePipe } from '@angular/common';
import * as moment from 'moment';
import { LocalStorage } from '../../core/services/local_storage.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { DatepickerOptions } from 'ng2-datepicker';

import * as enLocale from 'date-fns/locale/en';
import { ConfirmPopupComponent } from '../../sales_executive/confirm-popup/confirm-popup.component';
// declare var $: any;
import { Subscription } from "rxjs";
import { Observable } from "rxjs/Observable";
import { Location } from '@angular/common';
import { ToasterService } from '@service/toaster.service';
import $ from 'jquery';
import 'rxjs/add/observable/combineLatest';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { IDayCalendarConfig, DatePickerComponent } from "ng2-date-picker";
declare var $: $;


@Component({
  selector: 'app-regional-enquiry-report',
  templateUrl: './regional-enquiry-report.component.html',
  styleUrls: ['./regional-enquiry-report.component.scss']
})
export class RegionalEnquiryReportComponent implements OnInit {

  @ViewChild("dateFromDp") public dateFromDp: DatePickerComponent; 
  @ViewChild("dateToDp") public dateToDp: DatePickerComponent; 

  public filterForm: FormGroup;
  public displayDate;
 

  public dayPickerConfig = <IDayCalendarConfig>{
    // locale: "en",
    // format: "MMM-YYYY",
    // monthFormat: "MMMM, YYYY",
    // firstDayOfWeek: "mo",
    // max:'2021'
  };
  public dayPickerConfig_end = <IDayCalendarConfig>{
    // locale: "en",
    // format: "MMM-YYYY",
    // monthFormat: "MMMM, YYYY",
    // firstDayOfWeek: "mo",
    // max:'2021'
  };

  enquiry_percentage:any='';
  selecteddealer:any='';
  dealerlist:any=[];
  amlist:any=[];
  selectedam:any='';
  isselected:any='';

  userData: any = {};
  usertoken:any='';
  typevalue:any='';
  user_role: number;
  
  selectedfromdate:any='';
  selectedtodate:any='';
  datedisplay:boolean=false;
  conversion_percentage:any='';
  conversion_percentage_zero:any='';
  sales_percentage:any='';
  sales_percentage_zero:any='';
  periodicsort:any='';
  segment:any='';
  sales_convertion_ratio:any='';
  targeted_enquiry:any='';
  acheived_enquiry:any='';
  targeted_sales:any='';
  acheived_sales:any='';
  leaddata:any=[];
  startdate:any='';
  enddate:any='';
  startdatevalue:any='';
  enddatevalue:any='';
  labelname:any=[];
  labelvalues_enquiry:any=[];
  labelvalues_sales:any=[];
  calculatemax:any=[];
  calculatemaxbar:any=[];
  dbstartdate:any='';
  dbenddate:any='';
  dselist:any=[];
  selecteddse:any='';
  smpin:any='';
  url:any='';
  urlSafe:any='';
  downloadexcel:boolean=false;
  leadconversion_display:boolean=false;
  enquirystatus_display:boolean=false;
  enquiryacheived_display:boolean=false;
  salesacheived_display:boolean=false;
  productivity_display:boolean=false;
  convertion_display:boolean=false;
  loader: boolean = false;
  historychecked:any='1';
  production_percentage: any = '';
  zerproduction_percentage: any = '';
  //====
  options_date: DatepickerOptions = {
    minYear: 2000,
  //  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',

  };

 
  //==bar chart ==
  public barChartOptions = {
    
  };

  public barChartLabels = ['1', '2', '3', '4', '5', '6', '7'];
  public barChartType = 'bar';
  public barChartLegend = false;

  public barChartData = [];
  public barChartColors: {}[] = [
    { backgroundColor: '#92D050',},
    { backgroundColor: '#FFC000',}
 ];
  //===

  //===Doughnut chart===
  public doughnutChartLabels = ['Hot', 'Warm', 'Cold', 'Postponed','Lost'];
  public doughnutChartData_enquirystatus = [];
  public doughnutChartType = 'doughnut';
  doughnutColors: any[] = [{ backgroundColor: ['#005826', '#00A652', '#F7941D', '#ffc107', '#C00000'] }];
  //==

  //===Doughnut chart1===
  public doughnutChartLabels1 = [];
  public doughnutChartData1_enquiry = [];
  doughnut1Colors:any[] = [];
  //==

  //===Doughnut chart2===
  public doughnutChartLabels2 = [];
  public doughnutChartData2_sales = [];
  doughnut2Colors:any[] = [];

  public doughnutChartLabels3 = [];
  public doughnutChartData3_convertion = [];
  doughnut3Colors:any[] = [];

  
  options: any = {
    legend: false,
    tooltips: {enabled: false},
    hover: {mode: null},
    animation:{},plugins: {
      datalabels: {
        formatter: () => {
          return null;
        },
      },
    }
   }
  //==

  //==Pie chart ===
  public pieChartLabels = ['Productive DSE', 'Zero Productive DSE'];
  public pieChartData_productivity = [80, 10];
  public pieChartType = 'pie';
  piechartColors:any[] = [{ backgroundColor: ['#92D050', '#F15D22'] },];

  //==
  // public doughnutChartPlugins2: PluginServiceGlobalRegistrationAndOptions[] = [{
  //   beforeDraw(chart) {
  //     const ctx = chart.ctx;
  //     const txt = this.display_central;

  //     //Get options from the center object in options
  //     const sidePadding = 60;
  //     const sidePaddingCalculated = (sidePadding / 100) * (chart.options.circumference / Math.PI)

  //     ctx.textAlign = 'center';
  //     ctx.textBaseline = 'middle';
  //     const centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
  //     const centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);

  //     //Get the width of the string and also the width of the element minus 10 to give it 5px side padding
  //     const stringWidth = ctx.measureText(txt).width;
  //     const elementWidth = (chart.options.circumference / Math.PI) - sidePaddingCalculated;

  //     // Find out how much the font can grow in width.
  //     const widthRatio = elementWidth / stringWidth;
  //     const newFontSize = Math.floor(30 * widthRatio);
  //     const elementHeight = (chart.options.circumference / Math.PI);

  //     // Pick a new font size so it will not be larger than the height of label.
  //     const fontSizeToUse = Math.min(newFontSize, elementHeight);

  //     ctx.font = 'Arial';
  //     ctx.fillStyle = 'black';

  //     // Draw text in center
  //     ctx.fillText("Hai Hello", centerX, centerY);
  //   }
  // }];
  // public doughnutChartPlugins1: PluginServiceGlobalRegistrationAndOptions[] = [{
  //   beforeDraw(chart) {
  //     const ctx = chart.ctx;
  //     const txt = "Hai Hello";

  //     //Get options from the center object in options
  //     const sidePadding = 60;
  //     const sidePaddingCalculated = (sidePadding / 100) * (chart.options.circumference / Math.PI)

  //     ctx.textAlign = 'center';
  //     ctx.textBaseline = 'middle';
  //     const centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
  //     const centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);

  //     //Get the width of the string and also the width of the element minus 10 to give it 5px side padding
  //     const stringWidth = ctx.measureText(txt).width;
  //     const elementWidth = (chart.options.circumference / Math.PI) - sidePaddingCalculated;

  //     // Find out how much the font can grow in width.
  //     const widthRatio = elementWidth / stringWidth;
  //     const newFontSize = Math.floor(30 * widthRatio);
  //     const elementHeight = (chart.options.circumference / Math.PI);

  //     // Pick a new font size so it will not be larger than the height of label.
  //     const fontSizeToUse = Math.min(newFontSize, elementHeight);

  //     ctx.font = 'Arial';
  //     ctx.fillStyle = 'black';

  //     // Draw text in center
  //     ctx.fillText(this.display_central, centerX, centerY);
  //   }
  // }];

  constructor(
    private server: HyperService,
    private router: Router,
    private _eref: ElementRef,
    private route: ActivatedRoute,
    private formBuilder: FormBuilder,
    private toaster: ToasterService,
    public sanitizer: DomSanitizer,
    private fb: FormBuilder,
    private datePipe: DatePipe
    
  ) {

    this.createForm();
  }

  ngOnInit() {

    this.periodicsort='currentmonth';
    this.segment='1';
    const months = ["JAN", "FEB", "MAR","APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
    let current_datetime = new Date()
    let formatted_date = months[current_datetime.getMonth()] + "-" + current_datetime.getFullYear();
    this.selectedfromdate= formatted_date;
    this.selectedtodate= formatted_date;
    // this.changeperiodic();
   // this.datedisplay=true;
    this.filterForm.controls['dateFrom'].setValue(this.selectedfromdate);
    this.filterForm.controls['dateTo'].setValue(this.selectedtodate)
    this.godateval();

    let d = new Date();
    const yearval = (d.getFullYear()).toString();
    const monthval = d.toLocaleString('default', { month: 'short' });
    //console.log("month-->",monthval);
    this.dayPickerConfig = {
      locale: "en",
      format: "MMM-YYYY",
      monthFormat: "MMMM, YYYY",
      firstDayOfWeek: "mo",
      max:monthval+"-"+yearval,
      
    };


    this.filterForm.get("dateFrom").valueChanges.subscribe(value => {
     // console.log("value----->",value)
      // this.dateToDp.displayDate = value; // DateTo
      this.dayPickerConfig = {
        min: value,
        ...this.dayPickerConfig
      }
    });



    this.leadconversion_display=false;
    this.enquirystatus_display=false;
    this.enquiryacheived_display=false;
    this.salesacheived_display=false;
    this.convertion_display =false;
    this.productivity_display=false;


    var t1 = new Date(); 
    var year = new Date().getFullYear();
    year = Number (year)+1;
    this.options_date={
        minYear: 2000,
        maxYear: year,
        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', 
    }
    this.leadconversion_display=false;
    this.enquirystatus_display=false;
    this.enquiryacheived_display=false;
    this.salesacheived_display=false;
    this.productivity_display=false;
    
    //==function call==
    this.route.params.subscribe(params => {
      console.log(params)
      this.typevalue = params['type'];
      this.usertoken = params['tokenvalue'];
    });
    if(this.typevalue =='mobile'){
      LocalStorage.setValue('token', this.usertoken);
      this.userlogin();
      this.getamlist('');
    }else{
      this.getamlist('');
    }
   
  }

  private createForm(): void {
    this.filterForm = this.fb.group({
      dateFrom: new FormControl(),
      dateTo: new FormControl(),
    });
  }
   //==Authentication Login===
   userlogin() {
    this.server.get("user/profile").then((data) => {
      if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
        this.userData = data.result.data;
        LocalStorage.setValue('user_data', this.userData)
        this.user_role = this.userData.role;
     

      }
      else if (data.result.status == 401 && data.result.response == 'failed') {
        this.router.navigateByUrl('');
      }
      else {
        alert("Oops something happened!");
      }
    })
  }
  //==get AM list
  getamlist(args) {

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


  
    let req = {
      zmemail: "",
      rmemail: ""
    }
    this.server.post("managerenquiry/getamlist", req).then((data) => {
    
      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.getdashboarddetails();
    });
  }

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

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


    let spin = '';
    let req = {
      zmemail: "",
      rmemail: "",
      amemail: this.selectedam
    }
    this.server.post("managerenquiry/getdealerlist", req).then((data) => {
      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') {

      }
    });
    this.getdashboarddetails();
  }


  getdselist(args) {
    this.dselist=[];
    this.selecteddse='';
   // LocalStorage.setValue('setdseselected',this.selecteddse);
    let tempvar ='';
    if(args !=''){
      tempvar = args.target.options[args.target.selectedIndex].text;
     // LocalStorage.setValue("setdealerselectedname",tempvar);
    }else{
    //  tempvar = LocalStorage.getValue("setdealerselectedname");
    }
    let req = {
      zmemail: "",
      rmemail: "",
      amemail: this.selectedam,
      dealer_code:this.selecteddealer,
      segment:this.segment,
      history:this.historychecked
    }
  //  this.loader = true;
  //  LocalStorage.setValue("selecteddealervalue",this.selecteddealer)
    if(this.selecteddealer !=''){
      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') {

        }
      });
    }
      //    let dseselected=LocalStorage.getValue('setdseselected');
      //  if ((dseselected != '') && (dseselected != undefined) && (dseselected != null)) {
      //   this.selecteddse=dseselected;
      // }else{
      //   this.selecteddse='';
      // }
    this.getdsedetails('');
    this.getdashboarddetails();
  }

  
  
  //==
  getdsedetails(args){
    let tempvar ='';
    if(args !=''){
      tempvar = args.target.options[args.target.selectedIndex].text;
     // LocalStorage.setValue("setdseselectedname",tempvar);
    }else{
    //  tempvar = LocalStorage.getValue("setdseselectedname");
    }
  }

  getuserlist(){
    let spin = '';
    this.server.get("dealer/userlist")
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed') {
        this.dselist = data.result.data;
        spin = data.result.data[0].smpin;
       // spin.push({smpin:'select',fname:'Select',lname:''})
     //   console.log("this.setsmpin in the api list --->",this.setsmpin)
        this.dselist.unshift({smpin:'',fname:'Select',lname:''})
    //    console.log("this.setsmpin----222->",this.setsmpin);
      //  this.loader = false;
      } else if (data.result.status == 406) {
        //alert(data.result.message)
      }
      else if (data.result.status == 401 && data.result.response == 'failed') {

      }
    });
    
  }



  selectfromdate() {
    this.filterForm.controls['dateTo'].setValue('')
    let startdate = this.filterForm.controls['dateFrom'].value;

    // console.log("dateFrom--->",this.filterForm.controls['dateFrom'].value);
    let ssplit = (new Date(Date.parse(startdate)).getMonth() + 1);
    let startyear = startdate.split("-");
    let startmonthval = startyear[0];
    let startyearval = startyear[1];
    let startyearvalint = parseInt(startyearval)
    let calculateddate = this.addMonths(new Date(startyearvalint, ssplit, 20), 4);
    let aftercalculation = this.datePipe.transform(calculateddate, 'yyyy/MMM/dd');
    let sendvaluedate: any;
    let sendvalueyear: any = '';
    let sendvaluemonth: any = '';
    if (new Date(aftercalculation).getTime() > new Date().getTime()) {
      let d = new Date();
      sendvalueyear = (d.getFullYear()).toString();
      sendvaluemonth = d.toLocaleString('default', { month: 'short' });
    } else {
      sendvaluedate = aftercalculation.split('/');
      sendvalueyear = sendvaluedate[0];
      sendvaluemonth = sendvaluedate[1];
      // console.log("sendvalueyear --->",sendvalueyear);
      // console.log("sendvaluemonth --->",sendvaluemonth);
    }
    this.dayPickerConfig_end = {
      locale: "en",
      format: "MMM-YYYY",
      monthFormat: "MMMM, YYYY",
      firstDayOfWeek: "mo",
      min: startmonthval + "-" + startyearval,
      max: sendvaluemonth + "-" + sendvalueyear,

    };
  }
  selecttodate() {
    let fromdate = this.filterForm.controls['dateFrom'].value;
    if ((fromdate == null) || (fromdate == undefined)) {
      this.toaster.show("Please select start date");
      let d = new Date();
      let sendvalueyear = (d.getFullYear()).toString();
      let sendvaluemonth = d.toLocaleString('default', { month: 'short' });
      this.dayPickerConfig_end = {
        locale: "en",
        format: "MMM-YYYY",
        monthFormat: "MMMM, YYYY",
        firstDayOfWeek: "mo",
        max: sendvaluemonth + "-" + sendvalueyear,

      };
      
    }else if((fromdate == '')){

    }
  }
  resetdate() {
    //this.createForm();
    let d = new Date();
    const yearval = (d.getFullYear()).toString();
    const monthval = d.toLocaleString('default', { month: 'short' });
    this.dayPickerConfig_end, this.dayPickerConfig = {
      locale: "en",
      format: "MMM-YYYY",
      monthFormat: "MMMM, YYYY",
      firstDayOfWeek: "mo",
      max: monthval + "-" + yearval,

    };
    this.filterForm.controls['dateFrom'].setValue('');
    this.filterForm.controls['dateTo'].setValue('')
  }
  //==
  changestartdate(tempvalue){

    var monthvalueshown = tempvalue.getUTCMonth() + 1; //months from 1-12
    var dayvalueshown = tempvalue.getUTCDate()+1;
    var yearvalueshown = tempvalue.getUTCFullYear();
    var caldate= this.addMonths(new Date(yearvalueshown,monthvalueshown,dayvalueshown),6);
    // var startvalue= new Date(tempvalue);
    this.startdatevalue=tempvalue;
    this.enddatevalue=caldate;
   // console.log("tempvalue---changestartdate--->"+tempvalue);
  //  console.log("caldate--->"+caldate);
  }
  //==
  changeenddate(tempvalue){
   // console.log("tempvalue---changeenddate--->"+tempvalue);
    

  }
  godateval(){

    this.dbstartdate='';
    this.dbenddate='';
    let startdate= this.filterForm.controls['dateFrom'].value;
    let endate= this.filterForm.controls['dateTo'].value;
    if((startdate !='')&&(endate !='')&&(startdate !=null)&&(endate !=null)){
    let ssplit= (new Date(Date.parse(startdate)).getMonth()+1).toString();
    let ssplitval=ssplit.length;
    if(ssplitval == 1){
      ssplit = '0'+ssplit;
    }
    let startyear=startdate.split("-");
    let startyearval=startyear[1];
    //==
   
    let esplit= (new Date(Date.parse(endate)).getMonth()+1).toString();
    let esplitval=esplit.length;
    if(esplitval == 1){
      esplit = '0'+esplit;
    }
    let endyear=endate.split("-");
    let endyearval=endyear[1];
   
    let startdatesend= startyearval+"-"+ssplit+"-01";
    let enddatesend= endyearval+"-"+esplit+"-01";

    this.dbstartdate=startdatesend;
    this.dbenddate=enddatesend;

    this.getdashboarddetails();
  }else{
    this.toaster.show("Please select start date and end date");
  }
   
  }
  changesegment(){
    if(this.selecteddealer !=''){
      this.getdselist('');
    }else{
      this.getdashboarddetails();
    }
  }
  // changehistory(event){
  //   if(event.target.checked==true){
  //     this.historychecked='0';
  //   }else{
  //     this.historychecked='1';
  //   }
  //   this.getdashboarddetails();
  // }
  //==
  changeperiodic() {
    if (this.periodicsort == 'other') {
      this.datedisplay = true;
      const months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
      let current_datetime = new Date()
      let formatted_date = months[current_datetime.getMonth()] + "-" + current_datetime.getFullYear();
      this.selectedfromdate = formatted_date;
      this.selectedtodate = formatted_date;
      // this.changeperiodic();
      //this.datedisplay=true;
      this.filterForm.controls['dateFrom'].setValue(this.selectedfromdate);
      this.filterForm.controls['dateTo'].setValue(this.selectedtodate)
      
    }else if (this.periodicsort == 'currentmonth') {
      this.datedisplay = false;
      this.getdashboarddetails();
    } else {
      this.datedisplay = false;
      this.getdashboarddetails();
    }

  }
  getdatebased(){
    
  }
  //==
  addMonths(date, months) {
    var d = date.getDate();
    date.setMonth(date.getMonth() + +months);
    if (date.getDate() != d) {
      date.setDate(0);
    }
    return date;
  }

  getdashboarddetails(){

    this.leadconversion_display=false;
    this.enquirystatus_display=false;
    this.enquiryacheived_display=false;
    this.salesacheived_display=false;
    this.productivity_display=false;

    let periodvalue = '';
    let startdate ='';
    if (this.periodicsort == 'currentmonth') {
      let d = new Date();
      let startyearval = (d.getFullYear()).toString();
      let startmonthval = d.toLocaleString('default', { month: '2-digit' });
      let startdatestart = startyearval + "-" + startmonthval + "-01";
      this.dbstartdate=startdatestart;
      this.dbenddate=startdatestart;
      periodvalue='other'
    } else {
      periodvalue = this.periodicsort;
    }


    let req = {
      period:periodvalue,
      from:this.dbstartdate,
      to:this.dbenddate,
      segment:this.segment,
      history: this.historychecked,
      smpin:this.selecteddse,
      zmemail: "",
      rmemail: "",
      amemail: this.selectedam,
      dealer_code:this.selecteddealer

    }
    this.loader = true;
    this.server.post("enquiryreport/dashboard", req).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
        let valuedata=data.result.data;
        this.sales_convertion_ratio=valuedata.sale_ratio;
        this.targeted_enquiry=valuedata.target_enquiry;
        this.acheived_enquiry=valuedata.achieved_enquiry;
        this.targeted_sales=valuedata.target_sales;
        this.acheived_sales=valuedata.achieved_sales;

        this.bargraph(valuedata.graph);

        this.conversion_percentage=valuedata.conversion_percentage.percentage
        this.conversion_percentage_zero=valuedata.conversion_percentage.zero
        
        this.sales_percentage=valuedata.sales_percentage.percentage
        this.sales_percentage_zero=valuedata.sales_percentage.percentage;

        this.enquiry_percentage = valuedata.enquiry_percentage.percentage;

        this.production_percentage = valuedata.productivity.productivity
        this.zerproduction_percentage = valuedata.productivity.zero
        
        this.leaddata=valuedata.leaddata;
        this.enquirystatus_graph(valuedata.leaddata)
        this.enquiry_graph(valuedata.enquiry_percentage);
        this.sales_graph(valuedata.sales_percentage)
        this.convertion_graph(valuedata.conversion_percentage)
        this.productivity_graph(valuedata.productivity)

      //  console.log("leaddata--->",this.leaddata);

     //   console.log("valuedata--->",valuedata);
      } else if (data.result.status == 401 && data.result.response == 'failed') {
       // this.router.navigateByUrl('');
      } else if (data.result.status == 406 && data.result.response == 'failed') {
        let result = [];
       
      }
    });
  }
  //==
  enquirystatus_graph(paramvalue){
    console.log("paramvalue-->",paramvalue)
    this.enquirystatus_display=false;
    let hotval=paramvalue.hot;
    let warmval=paramvalue.warm;
    let coldval=paramvalue.cold;
    let lostval=paramvalue.lost;
    let postponedval=paramvalue.postponed
    this.doughnutChartData_enquirystatus=[hotval,warmval,coldval,postponedval,lostval]
    this.enquirystatus_display=true;
  }
  enquiry_graph(paramvalue){
    this.enquiryacheived_display=false;
    let percentvalue=paramvalue.percentage;
    let remondervalue=paramvalue.zero;
    this.doughnutChartLabels1 = ['Enquiry Acheived','Target'];
    this.doughnutChartData1_enquiry=[percentvalue,remondervalue];
    this.doughnut1Colors= [{ backgroundColor: ['#FFC000', '#D9D9D9']}];
    this.enquiryacheived_display=true;

  }
  sales_graph(paramvalue){
    this.salesacheived_display=false;
    let percentvalue=paramvalue.percentage;
    let remondervalue=paramvalue.zero;
    this.doughnutChartLabels2 = ['Sales Achieved','Target'];
    this.doughnutChartData2_sales=[percentvalue,remondervalue];
    this.doughnut2Colors= [{ backgroundColor: ['#FFC000', '#D9D9D9']},];
    this.salesacheived_display=true;
  }
  convertion_graph(paramvalue){
    this.convertion_display=false;
    let percentvalue=paramvalue.percentage;
    let remondervalue=paramvalue.zero;
    this.doughnutChartLabels3 = ['Total Sales','Total Enquiry'];
    this.doughnutChartData3_convertion=[percentvalue,remondervalue];
    this.doughnut3Colors= [{ backgroundColor: ['#FFC000', '#D9D9D9']}];
    this.convertion_display=true;
  }
  productivity_graph(paramvalue){
    this.productivity_display=false;
    let percentvalue=paramvalue.productivity;
    let remondervalue=paramvalue.zero;
    this.pieChartLabels = ['Productive DSE','Zero Productive DSE'];
    this.pieChartData_productivity=[percentvalue,remondervalue];
    this.productivity_display=true;
  }
  bargraph(paramvalue){
    this.labelname=[];
    this.labelvalues_enquiry=[];
    this.labelvalues_sales=[];
    this.calculatemax=[];
    this.barChartOptions={};

    this.leadconversion_display=false;
    paramvalue.forEach(element => {
      this.labelname.push(element.label);
      this.labelvalues_enquiry.push(element.value);
      this.labelvalues_sales.push(element.salesvalue);
      this.calculatemax.push(element.value);
      this.calculatemax.push(element.salesvalue);
    });
    //==
    // ==Calcluation for Max===Start Of max calcualtions
    if(this.calculatemax.length>0){
      this.calculatemaxbar = this.calculatemax.reduce(function(a, b) {
        return Math.max(a, b);
      })
    }else{
      this.calculatemaxbar=0;
    }
   
    // console.log("this.calculatemaxbar--->",this.calculatemaxbar)
   // console.log("this.calculatemaxbar--calculatemaxbar->",this.calculatemaxbar)
   if (this.calculatemaxbar > 100 && this.calculatemaxbar <= 1000) {
    // var temp = Math.ceil(this.calculatemaxbar / 100) * 100
    this.calculatemaxbar = Math.ceil(this.calculatemaxbar / 100) * 100
    this.calculatemaxbar = this.calculatemaxbar + 100;
  } else if (this.calculatemaxbar > 1000) {
    this.calculatemaxbar = Math.ceil(this.calculatemaxbar / 100) * 100
    this.calculatemaxbar = this.calculatemaxbar + 1000;
  }else if ((this.calculatemaxbar > 0)&&(this.calculatemaxbar <= 20)) {
    this.calculatemaxbar = 30
    //this.calculatemaxbar = this.calculatemaxbar + 20;
  }else if ((this.calculatemaxbar > 30)&&(this.calculatemaxbar <= 50)) {
    this.calculatemaxbar = 70
    //this.calculatemaxbar = this.calculatemaxbar + 20;
  }else if((this.calculatemaxbar > 50)&&(this.calculatemaxbar <= 80)){
    this.calculatemaxbar = 100;
  }else if((this.calculatemaxbar > 80)&&(this.calculatemaxbar <= 100)){
    this.calculatemaxbar = 120;
   } else {
    this.calculatemaxbar = 50;
  }

    // ==Calculation of max ends here ..
    // this.barChartOptions = {
    //   responsive: true,
    //   scaleShowValues: true,
    //   maintainAspectRatio: false,
    //   legend: {
    //     display: false
    //   },
    //   // We use these empty structures as placeholders for dynamic theming.
    //   scaleOverride:true,
    //   scales: { xAxes: [{}], 
    //   yAxes: [{ticks: {
    //     min: 0,
    //     max: this.calculatemaxbar
    //     },
    //     scaleLabel: {
    //       display: true,
    //       labelString: 'Counts'
    //    }
    //   }] },
    //   plugins: {
    //     datalabels: {
    //       anchor: 'end',
    //       align: 'end',
    //       font: {
    //         size: 5,
    //       }
    //     }
       
        
    //   }
    
    //  };
    this.barChartOptions = {
      scaleShowVerticalLines: false,
      responsive: true,
      events: [''],
      maintainAspectRatio: false,
      legend: {
            display: false
           },
      scaleShowValues: true,
     // scaleValuePaddingX: 3,
    //  scaleValuePaddingY: 3,
      scales: { xAxes: [{}], 
      yAxes: [{ticks: {
        min: 0,
        max: this.calculatemaxbar
        },
            scaleLabel: {
              display: true,
              labelString: 'Counts'
           }
      }] },
       animation: {
                 onComplete: function () {
                     var chartInstance = this.chart,
                     ctx = chartInstance.ctx;
                     ctx.textAlign = 'center';
                     ctx.textBaseline = 'bottom';
                     this.data.datasets.forEach(function (dataset, i) {
                         var meta = chartInstance.controller.getDatasetMeta(i);
                         meta.data.forEach(function (bar, index) {
                             var data = dataset.data[index];
                             ctx.fillText(data, bar._model.x, bar._model.y - 5);
                         });
                     });
                 }
             }
      };
   //  console.log("this.barChartOptions-->",this.barChartOptions);
    this.barChartData =[
      {data:this.labelvalues_enquiry , label: 'Enquiry'},
      {data: this.labelvalues_sales, label: 'Sales'}
    ]
    this.leadconversion_display=true;

  }
  //=
  public chartHovered(e:any):void {
    //console.log(e);
  }
  changedse(param){
    this.getdashboarddetails();
  }
  //===
  excelreport(){

    let periodvalue = '';
    let startdate ='';
    if (this.periodicsort == 'currentmonth') {
      let d = new Date();
      let startyearval = (d.getFullYear()).toString();
      let startmonthval = d.toLocaleString('default', { month: '2-digit' });
      let startdatestart = startyearval + "-" + startmonthval + "-01";
      this.dbstartdate=startdatestart;
      this.dbenddate=startdatestart;
      periodvalue='other'
    } else {
      periodvalue = this.periodicsort;
    }

    let req = {
      period:periodvalue,
      from:this.dbstartdate,
      to:this.dbenddate,
      segment:this.segment,
      history:this.historychecked,
      smpin:this.selecteddse,
      zmemail: "",
      rmemail: "",
      amemail: this.selectedam,
      dealer_code:this.selecteddealer
    }
    this.server.post("enquiryreport/export", req).then((data) => {
      if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
        this.downloadexcel=true;
        this.url=data.result.data;
      this.urlSafe= this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
      setTimeout(() => this.url = "", 1000);
      } else if (data.result.status == 401 && data.result.response == 'failed') {
       // this.router.navigateByUrl('');
      } else if (data.result.status == 406 && data.result.response == 'failed') {
        let result = [];
       
      }
    });
  }
  //==
  checkValue(event: any){
    this.historychecked=event;
    if(this.selecteddealer !=''){
      this.getdselist('');
    }else{
      this.getdashboarddetails();
    }
 }



}

