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 { EnquirypopupComponent } from '../enquirypopup/enquirypopup.component';
declare var $: any;
import { Subscription } from "rxjs";
import { Observable } from "rxjs/Observable";
import { Location } from '@angular/common';
import { TaskstatusComponent } from "../taskstatus/taskstatus.component";


@Component({
  selector: 'app-my-enquiries',
  templateUrl: './my-enquiries.component.html',
  styleUrls: ['./my-enquiries.component.scss']
})
export class MyEnquiriesComponent implements OnInit {
  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;
  //==

  stage_postponed: 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 = ''
  //==


  @ViewChild(EnquirypopupComponent) content_modal: EnquirypopupComponent;

  @ViewChild(TaskstatusComponent) taskmodal: TaskstatusComponent;



  constructor(private server: HyperService, private router: Router, private formBuilder: FormBuilder, private _location: Location) {
    this.wallet_pin = LocalStorage.getValue('enquiry_pin');
    //  console.log(this.wallet_pin,"this.wallet_pin")
    if (this.wallet_pin == "" || this.wallet_pin == undefined) {
      this.onClickForgotPin();
    }

  }


  ngOnInit() {

    let yrval = LocalStorage.getValue('yearvalueinitial');
    let mhval = LocalStorage.getValue('monthvalueinitial');

    //  console.log("yrval----->",yrval);
    //  console.log("mhval----->",mhval);

    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.getDashboardmonthbased(y, 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.getDashboardmonthbased(y, m);
    }



    let enquirymodulestatus = LocalStorage.getValue('enquirymodulestatus');

   // let enquirymodulestatus = '0';
    let selecteduserrole = LocalStorage.getValue('selecteduserrole');
   // alert(selecteduserrole)
    //console.log("enquirymodulestatus->", enquirymodulestatus)
    if (enquirymodulestatus == '0') {

      if (selecteduserrole == '14') {
        this.content_modal.showinitalfailurepop();
      } else {
        this.content_modal.dsepopup();
      }
    } else {

      let pinpopup = LocalStorage.getValue('pinvalue');
    
      this.mpin1 = '';
      this.mpin2 = '';
      this.mpin3 = '';
      this.mpin4 = '';
      this.close();

      this.getDashboardstatic();
      //  console.log()



      // CONFIG.configyearval=y;
      // CONFIG.configmonthval=m;

      if ((pinpopup != undefined) && (pinpopup != '')) {
        // console.log("value present");
        $('#pinModal').modal('hide');
      } else {

        // console.log("value absent");
        $('#pinModal').modal('show');
      }

      this.formBuild()
      this.formBuildOtp()

    }

  }
  //===
  todaysTask(tempvalue) {
    if (tempvalue == 'testride') {
      this.router.navigateByUrl('/' + tempvalue);
    } else if ((tempvalue == 'hot') || (tempvalue == 'warm') || (tempvalue == 'cold')) {
      //  console.log("tempvalue--->",tempvalue)
      this.router.navigateByUrl('enquiry-status/' + tempvalue);
    } else if ((tempvalue == 'booked') || (tempvalue == 'invoiced') || (tempvalue == 'lost') || (tempvalue == 'postponed')) {
      //   console.log("tempvalue--->",tempvalue)
      this.router.navigateByUrl('enquiry-stage/' + tempvalue);
    } else if (tempvalue == 'slot') {
      this.router.navigateByUrl('activityplanner');
    } else {

    }

  }
  test(i) {
    setTimeout(() => {
    }, 1000);
  }
  //==
  close() {
    var i = 0;
    for (i = 0; i < 3; i++) {
      this.test(i)
    }
  }
  //==
  onInputChange() {
    $('input.password').on('keyup', function (e) {
      if ($(this).val() != '' && e.keyCode != 8) {
        if ($(this).val()) {
          $(this).next().focus();
        }
      } else {
        if (e.keyCode == 8) {
          // console.log($(this).val(),"$(this).val()sdf")
          $(this).prev().focus();
        }
      }

    });
  }
  //==
  formBuild() {
    this.otpform = this.formBuilder.group({
      mpin1: [null, Validators.compose([Validators.required])],
      mpin2: [null, Validators.compose([Validators.required])],
      mpin3: [null, Validators.compose([Validators.required])],
      mpin4: [null, Validators.compose([Validators.required])]
    });
  }
  formBuildOtp() {
    this.otpform1 = this.formBuilder.group({
      otp1: [null, Validators.compose([Validators.required])],
      otp2: [null, Validators.compose([Validators.required])],
      otp3: [null, Validators.compose([Validators.required])],
      otp4: [null, Validators.compose([Validators.required])]
    });
  }

  //==
  onClickForgotPin() {
    // $('#pinModalCenter').modal('show');
    // this.wallet_pin='';
    this.otp = '';
    this.create_mpin = '';
    this.confirm_mpin = '';
    this.new_pin = false;
    this.isGetOtp = true;
    this.server.get("user/mpin_otp")
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed') {
          this.loader = false;
          this.resend_enable = false;
          this.TimeSet(data.result.data.otp_expiry)
        } else if (data.result.status == 401 && data.result.response == 'failed') {
          this.router.navigateByUrl('');
        }
      });
  }
  //===
  TimeSet(Time) {
    this.loader_timing = Time * 60;
    this.loader_delay = this.loader_timing / 2;
    const interval = 1000;
    const duration = 10 * 6000 * Time;
    this.stream$ = Observable.timer(0, interval)
      .finally(() => this.onclose())
      .takeUntil(Observable.timer(duration + interval))
      .map(value => duration - value * interval);
    this.sub = this.stream$.subscribe(value => this.formatMin(value));
  }
  //==
  formatMin(s) {
    let ms = s % 1000;
    s = (s - ms) / 1000;
    let secs = s % 60;

    s = (s - secs) / 60;
    let mins = s % 60;
    let hrs = (s - mins) / 60;
    if (hrs > 0) {
      this.countdown = hrs + ':' + mins + ':' + secs;
    } else {
      this.countdown = mins + ':' + secs;
    }
  }
  resend: boolean;
  resendOtp() {
    this.resend = true;
    this.resend_enable = false;
    this.onClickForgotPin();
  }
  //==
  onclose() {
    this.countdown = ''
    this.resend_enable = true;
  }
  //==
  onSubmitOtp() {
    // alert("3333");
    this.walletpin = (this.mpin1.toString()) + (this.mpin2.toString()) + (this.mpin3.toString()) + (this.mpin4.toString());
    if (this.otpform.valid) {
      if (this.walletpin == this.wallet_pin) {
        this.mpin_error = false;
        this.mpin_error1 = false;
        this.loader = true
        this.server.post("dashboard/changeepin", { epin: this.walletpin })
          .then((data) => {
            //  console.log(data)
            if (data.status == 200 && data.result.response == 'success') {
              this.loader = false;
              LocalStorage.setValue("pinvalue", '1')
              // LocalStorage.setValue("enquiry_pin", this.walletpin)
              $('#pinModal').modal('hide');
            } else if (data.result.status == 401 && data.result.response == 'failed') {
              this.router.navigateByUrl('');
            } else if (data.result.response == "failed") {
              this.mpin_error = true;
              this.mpin_error1 = false;
              // this.mpin_error1 =  data.result.message;
            }
          })
      } else {
        this.mpin_error = true;
        this.mpin_error1 = false;
      }

    } else {
      this.mpin_error1 = true;
      this.mpin_error = false;
      this.validateAllFormFields(this.otpform);
    }
  }
  //==
  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);
      }
    });
  }
  //==
  onSubmitPin() {

    //   console.log("epin",this.confirm_mpin)
    if (this.confirm_mpin != '' && this.confirm_mpin.length == 4 && this.confirm_mpin == this.create_mpin) {
      this.pin_error = false;
      this.loader = true
      this.server.post("dashboard/changeepin", { epin: this.confirm_mpin })
        .then((data) => {
          if (data.status == 200 && data.result.response != 'failed') {
            this.loader = false;
            $('#pinModal').modal('hide');
            LocalStorage.setValue('wallet_pin', this.confirm_mpin);
          } else if (data.result.status == 401 && data.result.response == 'failed') {
            this.router.navigateByUrl('');
          }
        });
    } else {
      this.pin_error = true;
    }
  }
  onSubmitPinChange() {
    //  console.log("mpin",this.confirm_mpin,this.wallet_pin,this.old_pin,this.create_mpin)
    if ((this.confirm_mpin != '') && (this.confirm_mpin.length == 4) && (this.confirm_mpin == this.create_mpin) && (this.wallet_pin == this.old_pin)) {
      this.pin_error = false;
      this.loader = true
      this.server.post("dashboard/changeepin", { epin: this.confirm_mpin })
        .then((data) => {
          if (data.status == 200 && data.result.response != 'failed') {
            this.loader = false;
            this.old_pin = '';
            this.new_pin_change = false;
            this.error_msg = '';
            this.pin_notmatch = false;
            $('#pinModal').modal('hide');
            LocalStorage.setValue('wallet_pin', this.confirm_mpin);
          } else if (data.result.status == 401 && data.result.response == 'failed') {
            this.router.navigateByUrl('');
          }
        });
    } else if (this.old_pin == '' && this.create_mpin == '' && this.confirm_mpin == '') {
      this.error_msg = '';
      this.pin_notmatch = true;
      this.error_msg = 'Please enter all fields';
    } else if (this.old_pin == '') {
      this.error_msg = '';
      this.pin_notmatch = true;
      this.error_msg = 'Enter Old PIN';
    } else if ((this.wallet_pin != this.old_pin) && this.old_pin != '') {
      this.error_msg = '';
      this.pin_notmatch = true;
      this.error_msg = 'Old PIN not matched';
    } else if (this.create_mpin == '') {
      this.error_msg = '';
      this.pin_notmatch = true;
      this.error_msg = 'Enter Create PIN';
    } else if (this.confirm_mpin == '') {
      this.error_msg = '';
      this.pin_notmatch = true;
      this.error_msg = 'Enter Confirm PIN';
    } else if (this.create_mpin == '') {
      this.error_msg = '';
      this.pin_notmatch = true;
      this.error_msg = 'Enter Create PIN';
    } else if (this.confirm_mpin != this.create_mpin) {
      this.error_msg = '';
      this.pin_notmatch = true;
      this.error_msg = 'Entered new PIN has not matched';
    } else {
      this.error_msg = 'error';
      this.pin_notmatch = true;
    }
  }
  //==
  onSubmitGetOtp() {

    // if(this.otp!=''){
    //     this.otp_error_data=false;
    //     this.otp_error=false;
    //     this.isGetOtp=true;
    //     this.loader = true;
    // this.server.post("user/otp_validation",{ type: 'mpin',otp: this.otp})
    //     .then((data) => {
    //         if (data.status == 200 && data.result.response != 'failed' ) {
    //             this.loader = false;
    //              this.isGetOtp=false;
    //              this.new_pin=true;
    //         } else if(data.result.status == 406 && data.result.response == 'failed'){
    //             this.loader = false;
    //             this.otp_error_data=true;
    //             this.otp_error=false;
    //         }else if (data.result.status == 401 && data.result.response == 'failed') {
    //             this.router.navigateByUrl('');
    //         }
    //     });
    //     }else{
    //         this.otp_error=true;
    //         this.otp_error_data=false;
    //     }
    if (this.otpform1.valid) {
      this.otp_error_data = false;
      this.otp_error = false;
      this.isGetOtp = true;
      this.loader = true;
      this.server.post("user/otp_validation", { type: 'epin', otp: (this.otp1.toString()) + (this.otp2.toString()) + (this.otp3.toString()) + (this.otp4.toString()) })
        .then((data) => {
          if (data.status == 200 && data.result.response != 'failed') {
            this.loader = false;
            this.isGetOtp = false;
            this.new_pin = true;
          } else if (data.result.status == 406 && data.result.response == 'failed') {
            this.loader = false;
            this.otp_error_data = true;
            this.otp_error = false;
          } else if (data.result.status == 401 && data.result.response == 'failed') {
            this.router.navigateByUrl('');
          }
        });
    } else {
      this.otp_error = true;
      this.otp_error_data = false;
      this.validateAllFormFields(this.otpform);
    }
  }
  //===
  onSubmitGetOtpChange() {
    if (this.otpform1.valid) {
      this.otp_error_data = false;
      this.otp_error = false;
      this.isGetOtp = false;
      this.isGetOtpChange = true;
      this.loader = true;
      this.server.post("user/otp_validation", { type: 'epin', otp: (this.otp1.toString()) + (this.otp2.toString()) + (this.otp3.toString()) + (this.otp4.toString()) })
        .then((data) => {
          if (data.status == 200 && data.result.response != 'failed') {
            this.loader = false;
            this.isGetOtpChange = false;
            this.otp = '';
            this.isGetOtp = false;
            this.new_pin_change = true;
          } else if (data.result.status == 406 && data.result.response == 'failed') {
            this.loader = false;
            this.otp_error_data = true;
            this.isGetOtp = false;
            this.otp_error = false;
          } else if (data.result.status == 401 && data.result.response == 'failed') {
            this.router.navigateByUrl('');
          }
        });
    } else {
      this.otp_error = true;
      this.otp_error_data = false;
      this.validateAllFormFields(this.otpform1);
    }
  }

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

  //===
  getDashboardmonthbased(year, month) {
    this.loader = true;
    LocalStorage.setValue("temp_mth", month)
    LocalStorage.setValue("temp_yr", year)
    var urlvalue = 'myenquiries';
    this.taskmodal.getmonthbaseddetails(year, month, urlvalue)
    this.server.get("enquiry/enquirysales/" + year + "/" + month + "")
      .then((data) => {
        this.loader = false;
        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_delivered = data.result.data.stage.delivered;
          this.stage_postponed = 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') { }
      });
  }
  //==
  decreasMonth() {
    CONFIG.configyearval = '';
    CONFIG.configmonthval = '';
    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");
    LocalStorage.setValue('yearvalueinitial', y);
    LocalStorage.setValue('monthvalueinitial', m);

    this.getDashboardmonthbased(y, m);

    //  }, 1200);
  }
  //==
  increasMonth() {
    // alert("aaasas")
    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.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() {
    // alert("333");
    // let sendData:any={};
    // this.content_modal.salesdetailModal('Result', {sendData}, (data) => {

    // })
    this.router.navigateByUrl('sales-dse');
  }
  //==
  Enquiry() {
    // let sendData:any={};
    // this.content_modal.enquirylistModal('Result', {sendData}, (data) => {
    // })
    this.router.navigateByUrl('enquiry-dse');
  }

  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;
  }
  //==
  createtestride() {
    //  alert("333")
    //routerLink="/create-enquiry"
    this.server.get("enquiry/checkunsave").then((data) => {
      if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
        console.log("data.status---->", data);
        this.is_exist = data.result.data.is_exist;
        this.router.navigateByUrl('create-enquiry');
        // console.log("this.is_exist---->",temp);
      } else if (data.result.status == 401 && data.result.response == 'failed') {
        this.router.navigateByUrl('');
      } else if (data.result.status == 406 && data.result.response == 'failed') {

      }
    });
  }
  //==
  // public onPageChange(event) {
  //   this.activeItem = -1;
  //   this.activePage = event;
  //   console.log('pagech', this.activePage)
  // }
  // //==
  // public getServerData(event) {
  //   let mvalue = LocalStorage.getValue("temp_mth")
  //   let yearvalue = LocalStorage.getValue("temp_yr")
  //   console.log(event)
  //   this.page_count = (event - 1);
  //   this.getDashboardmonthbased(yearvalue,mvalue)
  //   this.onPageChange(event);
  // }

}
