import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { CommonFunctionService } from '../services/commonfunctions.service';
import { RouterModule, Routes, Router } from '@angular/router';
import { Subject } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';




@Component({
  selector: 'dvr-entry',
  templateUrl: './dvrentry.component.html',
  styleUrls: ['./dvrentry.component.css']
})
export class DvrEntryComponent implements OnInit, OnDestroy {
  allowOnlyNumber(event: KeyboardEvent) {
    const charCode = event.charCode;
    if (charCode < 48 || charCode > 57) {
      event.preventDefault();
    }
  }
  public contactEntryForm !: FormGroup;
  public xmlItems: any;

  username: any;
  login_id: any;
  logindata: any = [];
  last_login_date: any;
  cust_data: any = [];
  contact_data: any = [];
  secondContact_Details: any = [];
  stage_data: any = [];
  currentDateData: any = [];
  currentDateData_flag: boolean = false;
  currentSecondContact: boolean = false;
  cust_name: any;
  messages: any;
  cust_id: any;
  formControlName: any;
  current_date: any;
  mincurrent_date: any;
  dtOptions: any = {};
  dtTrigger: Subject<any> = new Subject();
  displayStyle = "none";
  error_msg: any;
  success_msg: any;
  status_msg: any;
  cont_id: any;
  dvrupdate = [];
  visit_date: any;
  customer_name: any;
  contact_name: any;
  message: any;
  updation_msg: any;
  stage_des: any;
  stage_id: any;
  checkstage_id: any;
  dvr_id: any;
  role: any;
  check_date: any;
  est_Date: any;
  objective: any;
  deal: any;
  nextstep: any;
  postion: any;
  person: any;
  funcDetails: any = [];
  personDetails: any = [];

  checkupdatedelete: boolean;
  saveautoData = [];
  autofillData = [];

  checkoperationflag: boolean = false;
  checkdataflag: boolean;
  entry_successflag: boolean = false;
  second_contact: any;

  constructor(private commonservice: CommonFunctionService, private router: Router, private http: HttpClient) {



    console.log("in contact");
    console.log(this.router.url);
    var url = this.router.url;
    console.log("url------->", url);
    var myArray = url.split(":");
    //console.log("myArray", myArray);
    this.cont_id = myArray[2];
    var res = myArray[1];
    console.log("res========>", res);

    // getdvrDetailscheck

    if (res) {
      this.dvr_id = res;
      this.checkoperationflag = true;
      console.log("in updation");

      $(document).ready(function () {
        $(".textarea").css("height", "207px");
      });

      this.commonservice.getAllData(this.commonservice.projectpath + "/getdvrdetails?dvrid=" + res).subscribe(response => {
        // console.log("getdvrdetails response----------------> ", response.data);
        // console.log("getdvrdetails response----------------> ", response.data[0].contact_name);

        this.dvrupdate = response.data;
        console.log("this.dvrupdate", this.dvrupdate);
        this.visit_date = response.data[0].visit_date;
        this.customer_name = response.data[0].customer_name;
        this.contact_name = response.data[0].contact_name;
        this.updation_msg = response.data[0].mesasge;
        this.stage_des = response.data[0].stage_desc;
        this.stage_id = response.data[0].stage_id;
        this.check_date = response.data[0].created_on;
        this.nextstep = response.data[0].nextstep;
        this.second_contact = response.data[0].second_contact;
        this.est_Date = response.data[0].est_Date;
        this.objective = response.data[0].objective;
        this.deal = response.data[0].deal;
        this.postion = response.data[0].func;
        this.person = response.data[0].person;
        console.log("functinon::::::::::::::::::", this.contact_name)


        //this.visit_date = datePipetransform(this.visit_date.now(),'dd/MM/yyyy');
        this.visit_date = this.formatDate(this.visit_date);
        this.check_date = this.formatDate(this.check_date);
        this.est_Date = this.formatDate(this.est_Date);


        this.visit_date = String(this.visit_date)
        console.log(" this.visit_date", this.visit_date, this.customer_name, this.contact_name, this.stage_des);
        console.log("in updatation");
        this.est_Date = String(this.est_Date)


        this.contactEntryForm = new FormGroup({
          date: new FormControl(this.visit_date, Validators.required),
          message: new FormControl(this.updation_msg, Validators.required),
          contactName: new FormControl(this.contact_name, Validators.required),
          custName: new FormControl(this.customer_name, Validators.required),
          stageName: new FormControl(this.stage_des, Validators.required),
          ph_meet: new FormControl('yes', Validators.required),
          nextstep: new FormControl(this.nextstep, Validators.required),
          secondContact: new FormControl(this.second_contact, Validators.required),
          estDate: new FormControl(this.est_Date, Validators.required),
          objective: new FormControl(this.objective, Validators.required),
          deal: new FormControl(this.deal, Validators.required),
          postion: new FormControl(this.postion, Validators.required),
          personData: new FormControl(this.person, Validators.required),





        });
        console.log("this.check_date", this.check_date);

        var date1 = new Date(this.check_date);
        var date2 = new Date();

        // To calculate the time difference of two dates
        var Difference_In_Time = date2.getTime() - date1.getTime();

        // To calculate the no. of days between two dates
        var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

        console.log("Difference_In_Days---->", Math.round(Difference_In_Days));

        if (Math.round(Difference_In_Days) <= 1) {
          console.log("differnt in one days");
          this.checkupdatedelete = true;

        } else {
          console.log("difference is longer");
          this.checkupdatedelete = false;
          // this.FormControl['name'].disable();


        }

      });




    } else {
      this.checkoperationflag = false;
      console.log("in insert");
    }

    if (this.checkoperationflag == false) {
      console.log("in insert");
      this.contactEntryForm = new FormGroup({
        date: new FormControl(null, Validators.required),
        message: new FormControl(null, Validators.required),
        contactName: new FormControl(null, Validators.required),
        custName: new FormControl(null, Validators.required),
        stageName: new FormControl(null, Validators.required),
        ph_meet: new FormControl('yes', Validators.required),
        nextstep: new FormControl(null, Validators.required),
        secondContact: new FormControl(null, Validators.required),
        estDate: new FormControl(null, Validators.required),
        objective: new FormControl(null, Validators.required),
        deal: new FormControl(null, Validators.required),
        postion: new FormControl(null, Validators.required),
        personData: new FormControl(null, Validators.required),

      });

    }
  }

  ngOnInit() {

    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 15,
      processing: true,
      order: [],
      lengthMenu: [15, 25, 35],
      ordering: false,
      dom: 'Blfrtip',
      buttons: [
        'csv', 'excel', 'print'
      ]


    }

    this.logindata.push(JSON.parse(localStorage.getItem("loginData")));
    this.username = this.logindata[0]["user_name"];
    this.last_login_date = this.logindata[0]["last_loginDate"];
    this.login_id = this.logindata[0]["user_id"];
    this.role = this.logindata[0]["role"];
    console.log(" this.logindata=========>", this.login_id, this.role);



    this.current_date = new Date();
    // console.log(this.current_date);
    // console.log(this.current_date - 7);
    var dd = this.current_date.getDate();
    // console.log(this.current_date.getDate())
    // console.log(dd);
    var mm = this.current_date.getMonth() + 1;
    // console.log(this.current_date.getMonth());
    // console.log(mm);
    var yyyy = this.current_date.getFullYear();
    // console.log(dd);
    // console.log(mm);
    if (dd < 10) {
      dd = '0' + dd
    }
    if (mm < 10) {
      mm = '0' + mm
    }
    this.current_date = yyyy + '-' + mm + '-' + dd;
    console.log("max date------>", this.current_date);

    document.getElementById("Date").setAttribute("max", this.current_date);

    //max date
    var dd1;
    //console.log("dddddddd------->", this.current_date.getDate() - 7);

    // var date = dd - 7;
    var date = dd;
    this.mincurrent_date = new Date();
    var min_mm = this.mincurrent_date.getMonth();

    // console.log(min_mm);
    if (min_mm < 10) {
      min_mm = '0' + min_mm;
    }
    console.log("date====>", date);

    // if (date < 10) {
    //   dd1 = '0' + date;
    // } else {
    //   dd1 = date;
    // }

    console.log(yyyy - 1);

    if (min_mm == "00") {
      min_mm = 11;
      yyyy = yyyy - 1;
    }

    // this.mincurrent_date = yyyy + '-' + mm + '-' + dd1;
    // this.mincurrent_date = yyyy + '-' + min_mm + '-' + dd1;
    this.mincurrent_date = yyyy + '-' + min_mm + '-' + date;

    console.log(this.role);
    if (this.role == 'admin') {
      this.mincurrent_date = '2024-01-01'; // Temporary fix, min date reset
    }

    console.log("min date------>", this.mincurrent_date);
    document.getElementById("Date").setAttribute("min", this.mincurrent_date);

    this.commonservice.getAllData(this.commonservice.projectpath + "/getselectionData").subscribe(response => {
      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])

      }
      else {
        this.cust_data = response.data[0].customerData;
        if(this.role === 'users') {
          this.cust_data = this.cust_data.filter(item => item.first_name + " " + item.last_name === this.username);
        }
        this.cust_data = Array.from(
        new Map(
          this.cust_data.map(item => [
            `${item.customer_id}-${item.customer_name}`,
            {
              customer_id: item.customer_id,
              customer_name: item.customer_name
            }
          ])
        ).values()
      );
        console.log(this.cust_data);
        this.contact_data = response.data[1].contactData;
        console.log(" this.contact_data ", this.contact_data);
        this.stage_data = response.data[2].stageData;
        this.personDetails = response.data[3].personData;
        this.funcDetails = response.data[4].funcDetails;

      }
    });

    this.commonservice.getAllData(this.commonservice.projectpath + "/getlastestdvr?role=" + this.role + "&login_id=" + this.login_id).subscribe(response => {
      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])

      } else {

        if (response.data[0].getdvrDataStatus == '1') {
          //data not found
          console.log("in dataa not found");
          this.checkdataflag = true
        } else {
          console.log("in data");
          //  this.checkdataflag=false;
          console.log("response.data[0].dvrData;", response.data[0].getdvrDataStatus);
          // if(response.data[0].getdvrDataStatus == '1'){
          //   console.log("in if condition");
          // }else{
          //   console.log("in else condition");
          this.currentDateData = response.data[0].dvrData;

          // }


        }
        this.dtTrigger.next(this.dtOptions)


      }
      console.log("response-------->", response);
    });


    setTimeout(() => {
      $('#datatableexample').DataTable({
        pagingType: 'full_numbers',
        pageLength: 5,
        processing: true,
        lengthMenu: [5, 10, 25]
      });
    }, 1);


    if (localStorage.getItem("contactlastinsert")) {
      console.log("data is prsent for contact insert");
      this.contact_name = localStorage.getItem("contactlastinsert");
      this.contactEntryForm = new FormGroup({
        date: new FormControl(this.autofillData["date"], Validators.required),
        message: new FormControl(this.autofillData["message"], Validators.required),
        contactName: new FormControl(this.contact_name, Validators.required),
        custName: new FormControl(this.customer_name, Validators.required),
        stageName: new FormControl(this.stage_des, Validators.required),
        nextstep: new FormControl(this.autofillData["nextstep"], Validators.required),
        secondContact: new FormControl(this.second_contact, Validators.required),
        estDate: new FormControl(this.autofillData["estDate"], Validators.required),
        objective: new FormControl(this.autofillData["objective"], Validators.required),
        deal: new FormControl(this.autofillData["deal"], Validators.required),
        postion: new FormControl(this.postion, Validators.required),
        personData: new FormControl(this.person, Validators.required),

      });
    }


    if (localStorage.getItem("autofilldata")) {
      console.log("data is autofilldata");

      console.log("local storage item", localStorage.getItem("autofilldata"));
      console.log("local storage item---->", localStorage.getItem("contactlastinsert"));

      this.autofillData.push(JSON.parse(localStorage.getItem("autofilldata")));
      console.log("this.autofillData", this.autofillData[0]);
      this.autofillData = this.autofillData[0][0];

      console.log("date", this.autofillData["custName"].customer_name);
      this.customer_name = this.autofillData["custName"].customer_name;

      if (localStorage.getItem("contactlastinsert")) {
        this.contact_name = localStorage.getItem("contactlastinsert")
      }
      this.cust_id = this.autofillData["custName"].customer_id;
      if (this.autofillData["stageName"] == null) {
        //stage name null
      } else {
        this.stage_id = this.autofillData["stageName"].stage_id;
        this.stage_des = this.autofillData["stageName"].stage_desc;
      }

      // this.stage_des=
      this.contactEntryForm = new FormGroup({
        date: new FormControl(this.autofillData["date"], Validators.required),
        message: new FormControl(this.autofillData["message"], Validators.required),
        contactName: new FormControl(this.contact_name, Validators.required),
        custName: new FormControl(this.customer_name, Validators.required),
        stageName: new FormControl(this.stage_des, Validators.required),
        ph_meet: new FormControl(this.autofillData["ph_meet"], Validators.required),
        nextstep: new FormControl(this.autofillData["nextstep"], Validators.required),
        secondContact: new FormControl(this.second_contact, Validators.required),
        estDate: new FormControl(this.autofillData["estDate"], Validators.required),
        objective: new FormControl(this.autofillData["objective"], Validators.required),
        deal: new FormControl(this.autofillData["deal"], Validators.required),
        postion: new FormControl(this.autofillData["postion"], Validators.required),
        personData: new FormControl(this.person, Validators.required),

      });
    }




  }
  ngOnDestroy(): void {
    this.dtTrigger.unsubscribe();
  }

  ngOnchanges() {
    console.log("form.value.message", this.contactEntryForm);
    this.secondContactDetails(this.contactEntryForm)
  }

  ngDoCheck() {
    console.log("form.value.message", this.contactEntryForm);
    this.secondContactDetails(this.contactEntryForm)
  }

  openPopup() {
    this.displayStyle = "block";
  }
  closePopup() {
    this.displayStyle = "none";

    if (this.checkoperationflag == true) {
      this.router.navigate(['/home'])

    } else {
      if (this.entry_successflag == true) {
        window.location.reload();
      }
    }
  }


  dvrEntry(form: FormGroup) {


    console.log("this.login_id", this.login_id)


    if (this.checkoperationflag == true) {
      //in updation

      console.log("form.value.custName", form.value.custName.length);
      if (form.value.custName.length == undefined) {
        console.log("change custname");
        this.customer_name = form.value.custName.customer_name;
        //((form.value.custName ? form.value.custName.customer_name : '') ? '' : this.customer_name )
      } if (form.value.contactName.length == undefined) {
        console.log("change contactname", form.value.contactName);
        this.contact_name = form.value.contactName.first_name + '  ' + form.value.contactName.last_name;
        console.log("contact name", this.contact_name);
      } if (form.value.stageName.length == undefined) {
        console.log("change stage id");
        this.stage_id = form.value.stageName.stage_id;
      } if (form.value.secondContact.length == undefined) {
        console.log("change contactname", form.value.secondContact);
        this.second_contact = form.value.secondContact.first_name + '  ' + form.value.secondContact.last_name;
        console.log("contact name", this.second_contact);
      }

      const createdvr = {
        dvr_id: this.dvr_id,
        visit_date: form.value.date,
        customer_name: this.customer_name,
        contact_name: this.contact_name,
        message: form.value.message,
        physical_metting: form.value.ph_meet,
        stage_id: this.stage_id,
        updated_by: this.login_id,
        nextstep: form.value.nextstep,
        second_contact: this.second_contact != null ? this.second_contact : '',
        estDate: form.value.estDate,
        objective: form.value.objective,
        deal: form.value.deal,
        postion: form.value.postion,
        person: form.value.personData,

      }

      console.log("createdvr111", createdvr);

      this.commonservice.updateData(this.commonservice.projectpath + "/updateDvrEntry", createdvr).subscribe(response => {
        this.status_msg = "";
        this.error_msg = "";
        if (response.status == 'tokenfalse') {
          this.router.navigate(['/login'])
        } else {
          console.log("response.error", response.error);
          console.log("response.data", response.data[0]);

          if (response.data.length == 0) {
            //warning 
            this.openPopup();
            this.status_msg = "Warning";
            this.error_msg = response.error;
          } else if (response.data.length > 0) {
            console.log("inside if(response.message== '') ")
            this.openPopup();
            localStorage.removeItem("autofilldata")
            this.status_msg = "Success";
            this.error_msg = response.data[0].message;
            // console.log("response.data.message", response.data[0].exception.errorid);
            // if (response.data[0].exception.errorid != '') {
            //   this.openPopup();
            //   this.status_msg = "Warning";
            //   this.error_msg = response.error;
            // }
          }
          else {
            this.status_msg = "";
            this.error_msg = "";
          }
        }


        console.log("response-------->", response);
      });

    } else {
      //in insert
      var createdvr;
      console.log("this.stage_id", this.stage_id);
      console.log("this.second_contact", this.second_contact, form.value.secondContact);

      if (this.stage_id == undefined) {

        createdvr = {
          visit_date: form.value.date,
          customer_name: (this.customer_name == undefined ? form.value.custName?.customer_name : this.customer_name),
          contact_name: (this.contact_name == undefined ? form.value.contactName?.first_name + ' ' + form.value.contactName?.last_name : this.contact_name),
          message: form.value.message,
          physical_metting: form.value.ph_meet,
          sale_person: this.username,
          stage_id: (form.value.stageName ? form.value.stageName.stage_id : ''),
          created_by: this.login_id,
          nextstep: form.value.nextstep,
          second_contact: (form.value.secondContact == null ? null : form.value.secondContact.first_name + form.value.secondContact.last_name),
          estDate: form.value.estDate,
          objective: form.value.objective,
          deal: form.value.deal,
          func: form.value.postion ? form.value.postion.func_name : null,
          person: form.value.personData ? form.value.personData.person_name : null,

        }
      } else {

        createdvr = {
          visit_date: form.value.date,
          customer_name: (this.customer_name == undefined ? form.value.custName.customer_name : this.customer_name),
          contact_name: (this.contact_name == undefined ? form.value.contactName.first_name + form.value.contactName.last_name : this.contact_name),
          message: form.value.message,
          physical_metting: form.value.ph_meet,
          sale_person: this.username,
          stage_id: this.stage_id,
          created_by: this.login_id,
          nextstep: form.value.nextstep,
          second_contact: (form.value.secondContact == null ? null : form.value.secondContact.first_name + form.value.secondContact.last_name),
          estDate: form.value.estDate,
          objective: form.value.objective,
          deal: form.value.deal,
          func: form.value.postion ? form.value.postion.func_name : null,
          person: form.value.personData ? form.value.personData.person_name : null,

        }
      }


      console.log("createdvr in insert", createdvr);
      console.log("estDate", form.value.estDate);
      console.log("yyyyyyyy", this.customer_name, form.value.custName, this.stage_id, form.value.stageName, this.username);
      this.commonservice.getData(this.commonservice.projectpath + "/createDvrEntry", createdvr).subscribe(response => {
        this.status_msg = "";
        this.error_msg = "";

        if (response.status == 'tokenfalse') {
          this.router.navigate(['/login'])
        } else {
          console.log("response.error", response.error);
          console.log("response.data", response.data.length);

          if (response.data.length == 0) {
            //warning 
            this.openPopup();
            this.status_msg = "Warning";
            this.error_msg = response.error;
          } else if (response.data.length > 0) {
            console.log("inside if(response.message== '') ");
            localStorage.removeItem("contactlastinsert")

            this.openPopup();
            this.status_msg = "Success";
            this.error_msg = response.data[0].message;
            this.entry_successflag = true;
            this.customer_name = "";
            this.contact_name = "";
            this.stage_id = "";
            this.stage_des = "";
            this.postion = "";
            this.person = "";
            this.second_contact = "";
            localStorage.removeItem("autofilldata")
            this.contactEntryForm = new FormGroup({
              date: new FormControl(null, Validators.required),
              message: new FormControl(null, Validators.required),
              contactName: new FormControl(null, Validators.required),
              custName: new FormControl(null, Validators.required),
              stageName: new FormControl(null, Validators.required),
              ph_meet: new FormControl('yes', Validators.required),
              nextstep: new FormControl(null, Validators.required),
              secondContact: new FormControl(null, Validators.required),
              estDate: new FormControl(null, Validators.required),
              objective: new FormControl(null, Validators.required),
              deal: new FormControl(null, Validators.required),
              postion: new FormControl(null, Validators.required),
              personData: new FormControl(null, Validators.required),




            });
            // console.log("response.data.message", response.data[0].exception.errorid);
            if (response.data[0].exception.errorid != '') {
              this.openPopup();
              this.status_msg = "Warning";
              this.error_msg = response.error;
            }
          }
          else {
            this.status_msg = "";
            this.error_msg = "";
          }
        }


        console.log("response-------->", response);
      });

    }






    console.log(" this.logindata=========>", this.login_id, this.role);

    this.commonservice.getAllData(this.commonservice.projectpath + "/getlastestdvr?role=" + this.role + "&login_id=" + this.login_id).subscribe(response => {

      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])
      } else {
        // console.log("response-------->", response);

        this.currentDateData = response.data[0].dvrData;

      }
    });

  }

  onReset() {
    this.contactEntryForm.reset();
  }


  addUser() {
    console.log("addUser button click");

    this.customer_name = "";
    this.contact_name = "";
    this.stage_id = "";
    this.stage_des = "";
    this.second_contact = "";
    this.postion = "";
    this.person = "";
    this.contactEntryForm = new FormGroup({
      date: new FormControl(null, Validators.required),
      message: new FormControl(null, Validators.required),
      contactName: new FormControl(null, Validators.required),
      custName: new FormControl(null, Validators.required),
      stageName: new FormControl(null, Validators.required),
      ph_meet: new FormControl('yes', Validators.required),
      nextstep: new FormControl(null, Validators.required),
      secondContact: new FormControl(null, Validators.required),
      estDate: new FormControl(null, Validators.required),
      objective: new FormControl(null, Validators.required),
      deal: new FormControl(null, Validators.required),
      postion: new FormControl(null, Validators.required),
      personData: new FormControl(null, Validators.required),




    });
  }

  contactDetails(form: FormGroup) {


    console.log("form value", form.value);

    if (form.value.contactName == "Add New Contact") {

      if (form.value.custName == null) {
        console.log("value not entered");
        //user not entered customer details
        this.router.navigate(['/contactDetails'])
        localStorage.removeItem('autofilldata');

      } else if (this.customer_name != null) {
        this.router.navigate(["/contactDetails/contact:" + this.customer_name + "/id:" + this.cust_id]);
      }
      else {
        console.log("value entered");
        this.cust_name = form.value.custName.customer_name;
        this.cust_id = form.value.custName.customer_id
        this.saveautoData.push(form.value);
        console.log("this.saveautoData", this.saveautoData)
        localStorage.setItem('autofilldata', JSON.stringify(this.saveautoData));
        //user entered customer details
        this.router.navigate(["/contactDetails/contact:" + this.cust_name + "/id:" + this.cust_id]);
      }
    } else {
      console.log('other options selected');

    }

    if (form.value.secondContact == "Add New Contact") {

      if (form.value.custName == null) {
        console.log("value not entered");
        //user not entered customer details
        this.router.navigate(['/contactDetails'])
        localStorage.removeItem('autofilldata');

      } else if (this.customer_name != null) {
        this.router.navigate(["/contactDetails/contact:" + this.customer_name + "/id:" + this.cust_id]);
      }
      else {
        console.log("value entered");
        this.cust_name = form.value.custName.customer_name;
        this.cust_id = form.value.custName.customer_id
        this.saveautoData.push(form.value);
        console.log("this.saveautoData", this.saveautoData)
        localStorage.setItem('autofilldata', JSON.stringify(this.saveautoData));
        //user entered customer details
        this.router.navigate(["/contactDetails/contact:" + this.cust_name + "/id:" + this.cust_id]);
      }
    } else {
      console.log('other options selected');

    }


  }

  customerDetails(form: FormGroup) {
    console.log("form value", form.value.custName.customer_name);
    if (form.value.custName) {
      this.commonservice.getAllData(this.commonservice.projectpath + "/getcustcontactdetails?customer_id=" + form.value.custName.customer_name).subscribe(response => {
        if (response.status == 'tokenfalse') {
          this.router.navigate(['/login'])
        } else {
          this.contact_data = response.data[0].conrtactData;
          console.log("aaaaaaaaaaa------------>", this.contact_data);
          // this.dtTrigger.next(this.dtOptions)

        }
      });

    } else {
      console.log("customer not selected yet");
    }

  }

  get dateValidationCheck() {
    return this.formControlName.get('date');
  }

  isFieldValid(field: string) {
    // console.log("in field", field)
    return !this.contactEntryForm.get(field).valid && this.contactEntryForm.get(field).touched;
  }
  displayFieldCss(field: string) {
    return {
      'has-error': this.isFieldValid(field),
      'has-feedback': this.isFieldValid(field)
    };
  }


  formatDate(date) {
    var d = new Date(date),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear();

    if (month.length < 2)
      month = '0' + month;
    if (day.length < 2)
      day = '0' + day;

    return [year, month, day].join('-');
  }

  currformatDate() {
    var d = new Date(),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear();

    if (month.length < 2)
      month = '0' + month;
    if (day.length < 2)
      day = '0' + day;

    return [year, month, day].join('-');
  }



  deleteEntry() {
    console.log("delete entry");


    const dvrEntryData = {
      dvr_id: this.dvr_id,
      created_by: this.login_id
    }

    console.log("dvrEntryData ", dvrEntryData);

    this.commonservice.getData(this.commonservice.projectpath + "/deletedvrEntry", dvrEntryData).subscribe(response => {

      console.log("response", response);

      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])
      } else {
        console.log("response", response);

        if (response.data.length < 1) {
          //warning 
          console.log("in warning")
          this.openPopup();
          this.status_msg = "Warning";
          this.error_msg = response.error;
        } else if (response.data.length > 0) {
          console.log("inside if(response.message== '') ");
          console.log("message", response.data[0].message);
          this.openPopup();
          this.status_msg = "Success";
          this.error_msg = response.data[0].message;
          console.log("this.error_msg", this.error_msg);
          this.entry_successflag = true;
          this.customer_name = "";
          this.contact_name = "";
          this.stage_id = "";
          this.stage_des = "";
          this.postion = "";
          this.person = "";
          localStorage.removeItem("contactlastinsert")
          localStorage.removeItem("autofilldata")
          this.contactEntryForm = new FormGroup({
            date: new FormControl(null, Validators.required),
            message: new FormControl(null, Validators.required),
            contactName: new FormControl(null, Validators.required),
            custName: new FormControl(null, Validators.required),
            stageName: new FormControl(null, Validators.required),
            ph_meet: new FormControl('yes', Validators.required),
            nextstep: new FormControl(null, Validators.required),
            secondContact: new FormControl(null, Validators.required),
            estDate: new FormControl(null, Validators.required),
            objective: new FormControl(null, Validators.required),
            deal: new FormControl(null, Validators.required),
            postion: new FormControl(null, Validators.required),
            personData: new FormControl(null, Validators.required),




          });
          //this.router.navigate(['/home'])
          // console.log("response.data.message", response.data[0].exception.errorid);

        }
        else {
          this.status_msg = "";
          this.error_msg = "";
        }

      }
    });

  }

  secondContactDetails(form: FormGroup) {
    // console.log("form value", form.value);
    if (form.value.contactName != null) {
      console.log("first contact is present")
      console.log("email", form.value.contactName.email_id)
      if (form.value.contactName.email_id != null) {
        this.secondContact_Details = this.contact_data.filter((item: { email_id: any; }) => item.email_id != form.value.contactName.email_id)
        console.log("contact dataqqqqqqqqqqqqqqqqqqq", this.contact_data)
        this.currentSecondContact = true;

      } else {
        this.currentSecondContact = false;
      }

    } else {
      console.log("first contact is not present")
    }


  }

  funcPersonDetails(form: FormGroup) {
    console.log("form value", form.value);
    if (form.value.postion != null) {
      console.log("postion", form.value.postion)
      this.commonservice.getAllData(this.commonservice.projectpath + "/mappingFuncIDToPersonNames?func_id=" + form.value.postion.func_id).subscribe(response => {
        if (response.status == 'tokenfalse') {
          this.router.navigate(['/login'])
        } else {
          console.log("response:::::::::::::::::::::::::::::::::::::::::::::::::", response.data)
          this.personDetails = response.data;
          console.log("personDetails------------>", this.personDetails);
        }
      });

    } else {
      console.log(" func_id is not present")
    }


  }

}
