import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { CommonFunctionService } from '../services/commonfunctions.service';
import { DatePipe } from '@angular/common';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { DataTableDirective } from 'angular-datatables';
import { ViewChild } from '@angular/core'


@Component({
  selector: 'dvr-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']

})
export class ContactComponent implements OnInit {

  @ViewChild(DataTableDirective, { static: false })
  dtElement: DataTableDirective;


  public contactForm !: FormGroup;
  currentDateData: any = [];

  loginData: any = [];
  login_name: any;
  last_login_date: any;
  login_id: any;
  msg: any;
  cust_data: any = [];
  currentURL: any;
  cont_name: any;
  contnav_flag: boolean = false;
  mySelect: any;
  cont_id: any;

  checkfirstnm_flag: boolean = false;
  checklastnm_flag: boolean = false;
  checkmobilleno_flag: boolean = false;
  displayStyle = "none";
  error_msg: any;
  success_msg: boolean = false;
  status_msg: any;

  disabled_flag: boolean = false;
  contactList: any = [];
  contactList1: any = [];

  dtOptions = {};
  dtTrigger: Subject<any> = new Subject();



  sucess_flag: boolean = false;
  backtodvr_flag: boolean = false;
  check_successflag: boolean = false;

  emailID_flag: boolean = true;
  role: any;


  displayMessage: { [key: string]: string } = {};
  private validationMessage: { [key: string]: { [key: string]: string } }
  rows = [];


  constructor(private commonservice: CommonFunctionService, private router: Router, private fb: FormBuilder) {

    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 15,
      processing: true,
      order: [],
      lengthMenu: [15, 25, 35],

      ordering: false,
      dom: 'Blfrtip',

      buttons: [
        {
          extend: 'print',
          title: 'Contact Details Reports'
        },
        {
          extend: 'excelHtml5',
          title: 'Contact Details Reports'
        }

      ]
    }




    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];
    if (myArray.length > 1) {
      this.disabled_flag = true;
      var myArray1 = res.split("/");
      //console.log("myArray1",myArray1[0]);
      let result = decodeURI(myArray1[0])

      // let result = myArray1[0].replace("%20", " ");

      this.cont_name = result;
      this.commonservice.getAllData(this.commonservice.projectpath + "/getcustcontactdetails?customer_id=" + this.cont_name).subscribe(response => {
        if (response.status == 'falsetoken') {
          this.router.navigate(['/login'])
        } else {
          console.log("aaaaaaaaaaa", this.contactList);

          this.contactList = response.data[0].conrtactData;
          // console.log("aaaaaaaaaaa", this.contactList);
          this.dtTrigger.next(this.dtOptions)


          // this.dtTrigger.next(this.dtOptions)

          //this.contactList = response.data[0].conrtactData;
          //console.log("check length",response.data[0]);
          if (response.data[0].getdvrDataStatus == '1') {
            //data not found
            console.log("in dataa not found");

          } else {
            console.log("in data");
            // $(document).ready(function () {
            //   $("#TABLE_ID").DataTable();
            //   $(".dataTables_empty").empty();
            //   $(".odd").empty();
            // });

          }

          // this.dtTrigger.next(this.dtOptions)
        }
      });
      //console.log("res", this.cont_name);

    }



  }

  ngOnInit() {








    this.contactList = [];


    this.loginData.push(JSON.parse(localStorage.getItem("loginData")));
    console.log("", this.loginData[0]["user_name"]);
    this.login_name = 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"];

    if (this.cont_name) {
      console.log("in if")
      this.contnav_flag = true;

    } else {
      this.contnav_flag = false;
      // this.commonservice.getAllData(this.commonservice.projectpath + "/getcontactdetails?role=" + this.role + "&login_id=" + this.login_id).subscribe(response => {
      //   if (response.status == 'falsetoken') {
      //     this.router.navigate(['/login'])
      //   } else {
      //     this.contactList = response.data[0].conrtactData;
      //     console.log("aaaaaaaaaaa------------>", this.contactList);
      //     this.dtTrigger.next(this.dtOptions)

      //   }
      // });

      this.commonservice.getAllData(this.commonservice.projectpath + "/getcustcontactdetails?customer_id=0&passid=number").subscribe(response => {
        if (response.status == 'falsetoken') {
          this.router.navigate(['/login'])
        } else {
          this.contactList = response.data[0].conrtactData;
          console.log("aaaaaaaaaaa------------>", this.contactList);
          this.dtTrigger.next(this.dtOptions)

        }
      });
    }

    this.commonservice.getAllData(this.commonservice.projectpath + "/getselectionData").subscribe(response => {
      if (response.status == 'falsetoken') {
        this.router.navigate(['/login'])
      } else {
        this.cust_data = response.data[0].customerData;
        console.log("yyyyyyyyyyyyyy");

      }
    });




    this.contactForm = new FormGroup({
      first_name: new FormControl('', Validators.required),
      last_name: new FormControl('', Validators.required),
      mobile_number: new FormControl('', [Validators.required, Validators.maxLength(10)]),
      designation: new FormControl(null, Validators.required),
      email_Id: new FormControl('', Validators.required),
      department: new FormControl('', Validators.required),
      function: new FormControl('', Validators.required),
      mob_no: new FormControl('', [Validators.required, Validators.maxLength(10)])
    })
  }

  contactData(form: FormGroup) {

    this.msg = "";

    console.log("first name", form.value.first_name);
    console.log("last name", form.value.last_name);
    console.log("email_Id", form.value.email_Id);
    var email_Id = form.value.email_Id;

    // if (form.value.first_name !=null && form.value.email_Id != null) {
    //   console.log("check email id validation");
    //   var mailformat = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$";
    //   if (email_Id.match(mailformat)) {
    //     this.emailID_flag = true;

    //   }
    //   else {
    //     this.openPopup();
    //     this.status_msg = "Warning";
    //     this.error_msg = "You have entered an invalid email address!"
    //     this.emailID_flag = false;
    //   }
    // }


    if (this.cont_name) {

      console.log("get from url")
      const contactData = {
        first_name: form.value.first_name,
        last_name: form.value.last_name,
        mobile_no: form.value.mobile_number,
        email_id: form.value.email_Id,
        designation: form.value.designation,
        department: form.value.department,
        function: form.value.function,
        contact_for: this.cont_id,
        created_by: this.login_id,
        mob_no: form.value.mob_no


      }

      if (this.emailID_flag == true) {
        this.commonservice.getData(this.commonservice.projectpath + "/createContactEntry", contactData).subscribe(response => {

          console.log("in create contact response=========>", response);

          if (response.status == 'falsetoken') {
            this.router.navigate(['/login'])
          } else {
            // console.log("response", response);
            this.msg = response["message"];
            if (response["createStatus"] == '0') {

              //reset form 

              if (response.data.length == 0) {
                //warning 
                console.log("inside if")
                this.openPopup();
                this.status_msg = "Warning";
                this.error_msg = response.errors;
              } else if (response.data.length > 0) {
                console.log("inside else condition ")


                this.openPopup();
                this.sucess_flag = true;
                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.errors;
                }
              }
              else {
                this.status_msg = "";
                this.error_msg = "";
              }
            } else {
              if (response.data.length == 0) {
                //warning 
                console.log("inside if")
                this.openPopup();
                this.status_msg = "Warning";
                this.error_msg = response.errors;
              }
              else if (response.data.length > 0) {
                console.log("inside if(response.message== '') 99999999999")
                if (response.data[0].createStatus == 1 && response.data[0].exception.errorid == 400) {
                  console.log("duplicate contact");
                   this.openPopup();
                    this.status_msg = "Warning";
                    this.error_msg = response.data[0].exception.errormessage;
                }else{
                  this.backtodvr_flag = true;
                  console.log("response.data[0].lastinsertedData", response.data[0].lastinsertedData);
                  localStorage.setItem('contactlastinsert', response.data[0].lastinsertedData);
                  this.openPopup();
                  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.errors;
                  }
                }
              } else if (response.data[0].createStatus == 1 && response.data[0].exception.errorid == 400) {
                this.openPopup();
                this.status_msg = "Warning";
                this.error_msg = response.errors;
              }
              else {
                this.status_msg = "";
                this.error_msg = "";
              }
            }
          }
        });
      }



    } else {
      console.log("getting from dropdown");

      const contactData = {
        first_name: form.value.first_name,
        last_name: form.value.last_name,
        mobile_no: form.value.mobile_number,
        email_id: form.value.email_Id,
        designation: form.value.designation,
        department: form.value.department,
        function: form.value.function,
        contact_for: (this.mySelect ? this.mySelect.customer_id : ''),
        created_by: this.login_id,
        mob_no: form.value.mob_no

      }
      console.log("contactData", contactData);
      // console.log("res", this.mySelect);


      if (this.emailID_flag == true) {
        this.commonservice.getData(this.commonservice.projectpath + "/createContactEntry", contactData).subscribe(response => {

          console.log("response", response);

          if (response.status == 'falsetoken') {
            this.router.navigate(['/login'])
          } else {
            // console.log("response", response);
            this.msg = response["message"];
            if (response["createStatus"] == '0') {

              //reset form 

              if (response.data.length == 0) {
                //warning 
                console.log("inside if")
                this.openPopup();
                this.status_msg = "Warning";
                this.error_msg = response.errors;
              } else if (response.data.length > 0) {
                console.log("inside if(response.message== '')6666666666 ")
                this.openPopup();
                this.sucess_flag = true;
                this.status_msg = "Success";
                this.error_msg = response.data[0].message;
                this.checkfirstnm_flag = true;
                this.mySelect = "";
                this.contactForm = new FormGroup({
                  first_name: new FormControl('', Validators.required),
                  last_name: new FormControl('', Validators.required),
                  mobile_number: new FormControl('', [Validators.required, Validators.maxLength(10)]),
                  designation: new FormControl(null, Validators.required),
                  email_Id: new FormControl('', Validators.required),
                  department: new FormControl('', Validators.required),
                  function: new FormControl('', Validators.required),
                  mob_no: new FormControl('', [Validators.required, Validators.maxLength(10)])
                })
                // 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.errors;
                }
              }
              else {
                this.status_msg = "";
                this.error_msg = "";
              }
            } else {
              if (response.data.length == 0) {
                //warning 
                console.log("inside if")
                this.openPopup();
                this.status_msg = "Warning";
                this.error_msg = response.errors;
              }
              else if (response.data.length > 0) {
                console.log("inside if(response.message== '')222222222222 ")
                if (response.data[0].createStatus == 1 && response.data[0].exception.errorid == 400) {
                  console.log("duplicate contact");
                   this.openPopup();
                    this.status_msg = "Warning";
                    this.error_msg = response.data[0].exception.errormessage;
                } else {
                  this.openPopup();
                  this.status_msg = "Success";
                  this.error_msg = response.data[0].message;
                  this.checkfirstnm_flag = true;
                  this.mySelect = "";
                  this.contactForm = new FormGroup({
                    first_name: new FormControl('', Validators.required),
                    last_name: new FormControl('', Validators.required),
                    mobile_number: new FormControl('', [Validators.required, Validators.maxLength(10)]),
                    designation: new FormControl(null, Validators.required),
                    email_Id: new FormControl('', Validators.required),
                    department: new FormControl('', Validators.required),
                    function: new FormControl('', Validators.required),
                    mob_no: new FormControl('', [Validators.required, Validators.maxLength(10)])
                  })
                  // 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.errors;
                  }
                }

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




    }

  }


  resetForm() {
    this.msg = "";
  }


  onBack() {
    console.log("back dvr page");
    this.router.navigate(['/dvrentry'])
  }

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

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

  closePopup() {
    this.displayStyle = "none";
    if (this.backtodvr_flag == true) {
      //  alert("in else ");
      this.router.navigate(['/dvrentry'])
    } else {
      if (this.checkfirstnm_flag == true) {
        window.location.reload();
      }

    }
  }

  ValidateEmail(mail) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail)) {
      return (true)
    }
    this.openPopup();
    this.status_msg = "Warning";
    this.error_msg = "You have entered an invalid email address!";
    // alert("You have entered an invalid email address!")
    return (false)
  }


  numberOnly(event): boolean {
    const charCode = (event.which) ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false;
    }
    return true;
  }

  modo(value: any) {
    this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
      // Destroy the table first
      dtInstance.destroy();
      // Call the dtTrigger to rerender again
    });

    console.log("data---->", value);
    console.log("customer_id", value.customer_id);

    var id;
    if (value.customer_id != undefined) {
      console.log("specific customer contact");
      id = parseInt(value.customer_id);
      console.log("parseInt", typeof (id));

    } else {
      console.log("in all customer data");
      id = value;
    }



    this.commonservice.getAllData(this.commonservice.projectpath + "/getcustcontactdetails?customer_id=" + id + "&passid=number").subscribe(response => {
      if (response.status == 'falsetoken') {
        this.router.navigate(['/login'])
      } else {

        this.dtTrigger.next(this.dtOptions)

        //console.log("check length",response.data[0]);
        if (response.data[0].getdvrDataStatus == '1') {
          //data not found
          this.contactList = [];
          console.log("in dataa not found");
          $(document).ready(function () {
            $('.odd').show();

          });


        } else {
          console.log("in data");

          this.contactList = response.data[0].conrtactData;
          //this.dtTrigger1.next(this.dtOptions1)

          // document.getElementById("myH1").style.display = "none";

          $(document).ready(function () {
            $('.odd').hide()
          });




        }

        console.log("aaaaaaaaaaa", this.contactList);
      }
    });



  }


  getContactName(first_name: any, last_name: any) {
    console.log("in contact details", first_name, last_name);
    localStorage.setItem('contactlastinsert', first_name + ' ' + last_name);
    //this.router.navigate(['/dvrentry']);
  }
}

