import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AlertService } from 'src/app/services/alert.service';
import { Emp_detailsservice} from './Emp_details.service';
import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators, ValidationErrors } from '@angular/forms';
import { ExtensionService } from 'src/app/services/fnd/extension.service';
import { DashboardContentModel2 } from 'src/app/models/builder/dashboard'; 
import { Emp_detailscardvariable } from './Emp_details_cardvariable';
import { UserInfoService } from 'src/app/services/user-info.service';
declare var JsBarcode: any; 
@Component({
  selector: 'app-Emp_details',
  templateUrl: './Emp_details.component.html',
  styleUrls: ['./Emp_details.component.scss']
})
export class Emp_detailsComponent implements OnInit {
  cardButton = Emp_detailscardvariable.cardButton;
  cardmodeldata = Emp_detailscardvariable.cardmodeldata;
  public dashboardArray: DashboardContentModel2[];
  isCardview = Emp_detailscardvariable.cardButton;
  cardmodal;  changeView(){
  this.isCardview = !this.isCardview;
  }
    beforeText(fieldtext: string): string { // Extract the text before the first '<'
    const index = fieldtext.indexOf('<');
    return index !== -1 ? fieldtext.substring(0, index) : fieldtext;
  }
  afterText(fieldtext: string): string { // Extract the text after the last '>'
    const index = fieldtext.lastIndexOf('>');
    return index !== -1 ? fieldtext.substring(index + 1) : '';
  }
  transform(fieldtext: string): string {
    const match = fieldtext.match(/<([^>]*)>/);
    return match ? match[1] : ''; // Extract the text between '<' and '>'
  }
 userrole;
  rowSelected :any= {};
  modaldelete=false;
  modalEdit=false;
  modalAdd= false;
  public entryForm: FormGroup;
  loading = false;
  product;
  modalOpenedforNewLine = false;
  newLine:any;
 additionalFieldsFromBackend: any[] = [];
  formcode = 'Emp_details_formCode'
tableName = 'Emp_details';  checkFormCode; selected: any[] = []; constructor(
    private extensionService: ExtensionService,
private userInfoService:UserInfoService,
    private mainService:Emp_detailsservice,
    private alertService: AlertService,
    private toastr: ToastrService,
    private _fb: FormBuilder,
  ) { }
// component button 
  ngOnInit(): void {
    if(this.cardmodeldata !== ''){
     this.cardmodal = JSON.parse(this.cardmodeldata);
    this.dashboardArray = this.cardmodal.dashboard.slice();
    console.log(this.dashboardArray)
    }
    this.userrole=this.userInfoService.getRoles();
    this.getData();
    this.entryForm = this._fb.group({
first_name : [null],

numbera : [null,[Validators.required]],

phone_number: ['+91'],

paragraph_field : [null],

password_field : [null],
confirmpassword_field : [null],

textarea_field : [null],

date_field : [null],

datetime_field : [null],

email_field : [null],

toggle_switch : [false],

url_field : [null],

decimal_field : [null,[Validators.required]],

percentage_field : [null,[Validators.required]],

recaptcha : ['', [Validators.required,this.checkrecaptcha.bind(this)]],

documentsequence : [null],

selectsta : [null],

radios : [null],

  
 
q:[false],
   

 
b:[false],
   










survey_form : [null],

currency : [null, { updateOn: 'blur' }],

qrcode_field : [null],

barcode_field : [null],

numberb : [null,[Validators.required]],




 







    }, {
        validator: Confirmedpassword_fieldValidator('password_field', 'confirmpassword_field')















































  }); // component_button200
 // form code start
    this.extensionService.getJsonObjectsByFormCodeList(this.formcode).subscribe(data => {
      console.log(data);
      const jsonArray = data.map((str) => JSON.parse(str));
      this.additionalFieldsFromBackend = jsonArray;
      this.checkFormCode = this.additionalFieldsFromBackend.some(field => field.formCode === "Emp_details_formCode");
      console.log(this.checkFormCode);
      console.log(this.additionalFieldsFromBackend);
      if (this.additionalFieldsFromBackend && this.additionalFieldsFromBackend.length > 0) {
        this.additionalFieldsFromBackend.forEach(field => {
          if (field.formCode === this.formcode) {
            if (!this.entryForm.contains(field.extValue)) {
              // Add the control only if it doesn't exist in the form
              this.entryForm.addControl(field.extValue, this._fb.control(field.fieldValue));
            }
          }
        });
      }
    });
    console.log(this.entryForm.value);
    // form code end 


























this.generaterecaptcha()






























  }






































FileDataImageupload_field: any[];
  selectedImageupload_field: any[];

FileDataAudio_field: any[];
  selectedAudio_field: any[];

FileDataVideo_field: any[];
  selectedVideo_field: any[];














 error; 
  getData() {
    this.mainService.getAll().subscribe((data) => {
      console.log(data);
      this.product = data;
 if(this.product.length==0){
        this.error="No Data Available"
     }   
    },(error) => {
      console.log(error);
      if(error){
       this.error="Server Error";
     }
    });
  }
  onEdit(row) {
    this.rowSelected = row;




































    this.selectedfileupload_field = [];
    this.mainService.uploadfilegetByIdfileupload_field(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDatafileupload_field = uploaddata;
    
    })

    this.selectedimageupload_field = [];
    this.mainService.uploadImageupload_fieldgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataimageupload_field = uploaddata;
    
    })

    this.selectedaudio_field = [];
    this.mainService.uploadAudio_fieldgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataaudio_field = uploaddata;
    
    })

    this.selectedvideo_field = [];
    this.mainService.uploadVideo_fieldgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDatavideo_field = uploaddata;
    
    })







  //    bar code field start 
   setTimeout(function(){ 
		JsBarcode("#barcodebarcode_field", row?.barcode_field);
	     }, 500);
	   //    bar code field start



//calculated field start
	
 
	   this.calculatedaddnumbera= row.numbera;
	  

 
	   this.calculatedaddnumberb= row.numberb;
	  

//calculated field end


    this.modalEdit = true;
  }
   onDelete(row) {
    this.rowSelected = row;
     this.modaldelete=true;
  }
  delete(id)
  {
    this.modaldelete = false;
    console.log("in delete  "+id);
    this.mainService.delete(id).subscribe(
      (data) => {
        console.log(data);
        this.ngOnInit();
  if (data) {				      this.toastr.success('Deleted successfully');      }
    });
  }
    onUpdate(id) {
    this.modalEdit = false;






















































//calculated field start
	
 
this.rowSelected.numbera= this.calculatedaddnumbera;
	 

 
this.rowSelected.numberb= this.calculatedaddnumberb;
	 

this.onInputChangecalculatedadd ();
 //calculated field end

    //console.log("in update");
    console.log("id  " + id);
    console.log(this.rowSelected);
    //console.log("out update");
    this.mainService.update(id, this.rowSelected).subscribe(
      (data) => {
        console.log(data);
        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Update Successfully");
        }
setTimeout(() => {
      this.ngOnInit();
    }, 500);




































for (let i = 0; i < this.selectedfileupload_field.length; i++){

  this.mainService.uploadfilefileupload_field(data.id,this.tableName,this.selectedfileupload_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}

for (let i = 0; i < this.selectedimageupload_field.length; i++){

  this.mainService.uploadImageupload_field(data.id,this.tableName,this.selectedimageupload_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}

for (let i = 0; i < this.selectedaudio_field.length; i++){

  this.mainService.uploadAudio_field(data.id,this.tableName,this.selectedaudio_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}

for (let i = 0; i < this.selectedvideo_field.length; i++){

  this.mainService.uploadVideo_field(data.id,this.tableName,this.selectedvideo_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}













      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("update Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Updated");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Updated");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  } 
onCreate() {
     this.modalAdd=false;






















































//calculated field start
	
 
this.entryForm.value.numbera  = this.calculatedaddnumbera ;
	  

 
this.entryForm.value.numberb  = this.calculatedaddnumberb ;
	  

//calculated field end

  this.mainService.create(this.entryForm.value).subscribe(
    (data) => {
      console.log(data);
  if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Added Successfully");
        }
setTimeout(() => {
      this.ngOnInit();
    }, 500);



































for (let i = 0; i < this.selectedfileupload_field.length; i++){

  this.mainService.uploadfilefileupload_field(data.id,this.tableName,this.selectedfileupload_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}

for (let i = 0; i < this.selectedimageupload_field.length; i++){

  this.mainService.uploadImageupload_field(data.id,this.tableName,this.selectedimageupload_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}

for (let i = 0; i < this.selectedaudio_field.length; i++){

  this.mainService.uploadAudio_field(data.id,this.tableName,this.selectedaudio_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}

for (let i = 0; i < this.selectedvideo_field.length; i++){

  this.mainService.uploadVideo_field(data.id,this.tableName,this.selectedvideo_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}














      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("Added Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Added");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Added");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }
  goToAdd(row) {
this.modalAdd = true; this.submitted = false;



































this.FileDatafileupload_field = [];
this.selectedfileupload_field =[];

this.FileDataImageupload_field = [];
this.selectedImageupload_field =[];

this.FileDataAudio_field = [];
this.selectedAudio_field =[];

this.FileDataVideo_field = [];
this.selectedVideo_field =[];











  //calculated field start

  
 
  this.calculatedaddnumbera  = '';
 

 
  this.calculatedaddnumberb  = '';
 



  this.calculatedaddtotal = '';

  //calculated field end


  }
 submitted = false;
onSubmit() {
  console.log(this.entryForm.value);
 this.submitted = true;
  if (this.entryForm.invalid) {
    return;
  }this.onCreate();

} 




isValidPhone_number(phone: string): boolean {
  const phonePattern = /^(\+[1-9][0-9]{0,2})?[1-9][0-9]{9}$/;
  return phonePattern.test(phone);
}

rsModalparagraph_field = false;  
 goToReplaceStringparagraph_field (row){
						    this.rowSelected = row;     this.rsModalparagraph_field  =true;   }

newpHidepassword_field: boolean = true;
 newIconpassword_field: string = "eye"; 
newShapeChangerpassword_field() {
this.newpHidepassword_field = !this.newpHidepassword_field;  
 if(this.newpHidepassword_field){
this.newIconpassword_field = 'eye'   } else {     this.newIconpassword_field = 'eye-hide'   }
} 

 newaddpHidepassword_field: boolean = true;
 newaddIconpassword_field: string = "eye";
newaddChangerpassword_field() {   this.newaddpHidepassword_field = !this.newaddpHidepassword_field;
 if(this.newaddpHidepassword_field){     this.newaddIconpassword_field = 'eye'   } else {
  this.newaddIconpassword_field = 'eye-hide'   } }

rsModaltextarea_field = false;   
goToReplaceStringtextarea_field(row){
this.rowSelected = row;     this.rsModaltextarea_field  =true;   }





isValidemail_field(email: string): boolean {
						 const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
						    return emailPattern.test(email);   }



isValidurl_field(url: string): boolean {
						    return  /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/.test(url);   } 
						goTourl_fieldUrl(val){     window.open(val)   }





recaptchaCode = '';  
generaterecaptcha (): void {
  const possibleCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const codeLength = 6; // Change to desired length

  let recaptcha= '';
  for (let i = 0; i < codeLength; i++) {
    const randomIndex = Math.floor(Math.random() * possibleCharacters.length);
    recaptcha += possibleCharacters.charAt(randomIndex);
  }
  this.recaptchaCode = recaptcha;
}

checkrecaptcha(control: AbstractControl): ValidationErrors | null {
  if (control.value !== this.recaptchaCode) {
    return { recaptchaMismatch: true };
  }
  return null;
}  

recaptchaMismatch = false;  

checkrecaptchaEdit(): void {
	  if (this.rowSelected.recaptcha  !== this. recaptchaCode) {
	  this. recaptchaMismatch = true;    } else {      this.recaptchaMismatch = false;    }  } 





updateradios (radios : string): void {    
 this.entryForm.get('radios').setValue(radios);   }

updateradiosEdit(radios : string): void {    this.rowSelected.radios  =  radios }
						 ;



filePreviewfileupload_field: string | ArrayBuffer | null = null;
FileDatafileupload_field: {uploadedfile_name?:any, filePreview: string | ArrayBuffer | null }[] = []; // Initialize the array
selectedfileupload_field: File[]=[]; 
public onFileChangedfileupload_field(event, index) {
  const files = event.target.files;
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    this.FileDatafileupload_field[index].uploadedfile_name = files[i].name;
    this.selectedfileupload_field.push(files[i]);
    if (file.type.startsWith('file/')) {
      const reader = new FileReader();
      reader.onload = (e) => {
        // Set the file preview source
        const filePreview = e.target?.result as string;
        this.FileDatafileupload_field[index] = {
          ...this.FileDatafileupload_field[index], // Preserve existing properties
          filePreview: filePreview // Update only the filePreview property
        };
      };
      reader.readAsDataURL(file);
    }
  }
}
    onAddLinesfileupload_field(){
      this.FileDatafileupload_field.push({
        uploadedfile_name: "",
        filePreview: "",
        // f3: "",
      });
    }
    deleteRowfileupload_field(index,id) {
      this.FileDatafileupload_field.splice(index, 1);

      if(id){
      this.mainService.uploadfiledeletefileupload_field(id).subscribe(data =>{
        console.log(data);
      })
      }
    }

filePreviewimageupload_field: string | ArrayBuffer | null = null;
FileDataimageupload_field: {uploadedfile_name?:any, filePreview: string | ArrayBuffer | null }[] = []; // Initialize the array
selectedimageupload_field: File[]=[]; 
public onFileChangedimageupload_field(event, index) {
  const files = event.target.files;
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    this.FileDataimageupload_field[index].uploadedfile_name = files[i].name;
    this.selectedimageupload_field.push(files[i]);
    if (file.type.startsWith('image/')) {
      const reader = new FileReader();
      reader.onload = (e) => {
        // Set the file preview source
        const filePreview = e.target?.result as string;
        this.FileDataimageupload_field[index] = {
          ...this.FileDataimageupload_field[index], // Preserve existing properties
          filePreview: filePreview // Update only the filePreview property
        };
      };
      reader.readAsDataURL(file);
    }
  }
}
    onAddLinesimageupload_field(){
      this.FileDataimageupload_field.push({
        uploadedfile_name: "",
        filePreview: "",
        // f3: "",
      });
    }
    deleteRowimageupload_field(index,id) {
      this.FileDataimageupload_field.splice(index, 1);

      if(id){
      this.mainService.uploadImageupload_fielddelete(id).subscribe(data =>{
        console.log(data);
      })
      }
    }

filePreviewaudio_field: string | ArrayBuffer | null = null;
FileDataaudio_field: {uploadedfile_name?:any, filePreview: string | ArrayBuffer | null }[] = []; // Initialize the array
selectedaudio_field: File[]=[]; 
public onFileChangedaudio_field(event, index) {
  const files = event.target.files;
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    this.FileDataaudio_field[index].uploadedfile_name = files[i].name;
    this.selectedaudio_field.push(files[i]);
    if (file.type.startsWith('audio/')) {
      const reader = new FileReader();
      reader.onload = (e) => {
        // Set the file preview source
        const filePreview = e.target?.result as string;
        this.FileDataaudio_field[index] = {
          ...this.FileDataaudio_field[index], // Preserve existing properties
          filePreview: filePreview // Update only the filePreview property
        };
      };
      reader.readAsDataURL(file);
    }
  }
}
    onAddLinesaudio_field(){
      this.FileDataaudio_field.push({
        uploadedfile_name: "",
        filePreview: "",
        // f3: "",
      });
    }
    deleteRowaudio_field(index,id) {
      this.FileDataaudio_field.splice(index, 1);

      if(id){
      this.mainService.uploadAudio_fielddelete(id).subscribe(data =>{
        console.log(data);
      })
      }
    }

filePreviewvideo_field: string | ArrayBuffer | null = null;
FileDatavideo_field: {uploadedfile_name?:any, filePreview: string | ArrayBuffer | null }[] = []; // Initialize the array
selectedvideo_field: File[]=[]; 
public onFileChangedvideo_field(event, index) {
  const files = event.target.files;
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    this.FileDatavideo_field[index].uploadedfile_name = files[i].name;
    this.selectedvideo_field.push(files[i]);
    if (file.type.startsWith('video/')) {
      const reader = new FileReader();
      reader.onload = (e) => {
        // Set the file preview source
        const filePreview = e.target?.result as string;
        this.FileDatavideo_field[index] = {
          ...this.FileDatavideo_field[index], // Preserve existing properties
          filePreview: filePreview // Update only the filePreview property
        };
      };
      reader.readAsDataURL(file);
    }
  }
}
    onAddLinesvideo_field(){
      this.FileDatavideo_field.push({
        uploadedfile_name: "",
        filePreview: "",
        // f3: "",
      });
    }
    deleteRowvideo_field(index,id) {
      this.FileDatavideo_field.splice(index, 1);

      if(id){
      this.mainService.uploadVideo_fielddelete(id).subscribe(data =>{
        console.log(data);
      })
      }
    }



//currency  field start
   formatCurrencycurrency () {
    // Format the currency with two decimal places    
	this.rowSelected.currency = Number(this.rowSelected.currency ).toFixed(2);
    // Remove commas from the formatted currency   
	 this.rowSelected.currency = this.rowSelected.currency?.replace(/,/g, '');  }
  //currency  field end



//bar code field start 
     generateBarcodebarcode_field(value) {
      const barcodeValue = value;
      const barcodeElement = document.getElementById("barcodebarcode_field"); 
      if (barcodeElement) {         if (barcodeValue) {
          JsBarcode(barcodeElement, barcodeValue, {             format: "CODE128"
          });         } else {
          // Clear the barcode if the input is empty
          barcodeElement.innerHTML = '';         }       }     }
         //    bar code field end 



 // calculated field code start 

 
 calculatedaddnumbera; 
  

 
 calculatedaddnumberb; 
  

  calculatedaddtotal ; 
 calculatedaddcalculateOperators = "aa"
onInputChangecalculatedadd() {
const lastObj = 0
const lastObjstring = ''
	
 

    const numbera= this.calculatedaddnumbera|| '';

	const numberaValue = parseFloat(this.calculatedaddnumbera) || 0;

	  

 

    const numberb= this.calculatedaddnumberb|| '';

	const numberbValue = parseFloat(this.calculatedaddnumberb) || 0;

	  

if (this.calculatedaddcalculateOperators =="Addition") {
 this.calculatedaddtotal = (   
	
 
		 numberaValue +
	 

 
		 numberbValue +
	 
 lastObj).toString();
}
if (this.calculatedaddcalculateOperators == "Subtraction") {
	 this.calculatedaddtotal = (   

 
 numberaValue   -
	 

 
 numberbValue   -
	 

	lastObj).toString();
}
if (this.calculatedaddcalculateOperators =="Multiplication") {
  this.calculatedaddtotal = (

	
 
	numberaValue *
		 

 
	numberbValue *
		 

lastObj).toString();
}
if (this.calculatedaddcalculateOperators =="Division") {
 
	this.calculatedaddtotal = ( 

 
numberaValue   /
	 

 
numberbValue   /
	 

lastObj).toString();

}
if (this.calculatedaddcalculateOperators =="Concatination") {
 this.calculatedaddtotal =  

 
numbera+ ' '+
	 

 
numberb+ ' '+
	 
 lastObjstring 
}
}

// updateaction
}







export function Confirmedpassword_fieldValidator(controlName: string, matchingControlName: string){
  return (formGroup: FormGroup) => {
      const control = formGroup.controls[controlName];
      const matchingControl = formGroup.controls[matchingControlName];
      if (matchingControl.errors && !matchingControl.errors.confirmedpassword_fieldValidator) {
          return;
      }
      if (control.value !== matchingControl.value) {
          matchingControl.setErrors({ confirmedpassword_fieldValidator: true });
      } else {
          matchingControl.setErrors(null);
      }
  }
}
















































