import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AlertService } from 'src/app/services/alert.service';
import { Formbservice} from './Formb.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 { Formbcardvariable } from './Formb_cardvariable';
import { UserInfoService } from 'src/app/services/user-info.service';
declare var JsBarcode: any; 
@Component({
  selector: 'app-Formb',
  templateUrl: './Formb.component.html',
  styleUrls: ['./Formb.component.scss']
})
export class FormbComponent implements OnInit {
  cardButton = Formbcardvariable.cardButton;
  cardmodeldata = Formbcardvariable.cardmodeldata;
  public dashboardArray: DashboardContentModel2[];
  isCardview = Formbcardvariable.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 = 'Formb_formCode'
tableName = 'Formb';  checkFormCode; selected: any[] = []; constructor(
    private extensionService: ExtensionService,
private userInfoService:UserInfoService,
    private mainService:Formbservice,
    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({
name : [null],

surveyff : [null],

 
 
aa:[null],
 

 
bb:[null],
 


child: this._fb.array([this.initLinesForm()]),



qrcode : [null],

barcode : [null],

 

texts : [null],





approved_field_status : [null],


 























  }); // 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 === "Formb_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 

























  }






// one to many start
 initLinesForm() {    return this._fb.group({ 


 	
 active: [null],
 

 	
 description: [null],
 

 	
 name: [null],
 


});  }  
get controls() {return (this.entryForm.get("child") as FormArray).controls;  }
onAddLines() {
(<FormArray>this.entryForm.get("child")).push(this.initLinesForm());  }
onRemoveLines(index: number) {
(<FormArray>this.entryForm.get("child")).removeAt(index);  }
 oneditLines() {    this.components.push({ 

 
active: "",
 

 
description: "",
 

 
name: "",
 


	  });  }  
 deleteRow(index) {
 this.components.splice(index, 1); 
 }  
		 components;
 // one to many end 















approved_field_tablename = 'Formb' 

 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.components = row.child;





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





//calculated field start
	
 
	   this.concatinationname= row.name;
	  

 
	   this.concatinationtexts= row.texts;
	  

//calculated field end



  this.serverData = [];


    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.name= this.concatinationname;
	 

 
this.rowSelected.texts= this.concatinationtexts;
	 

this.onInputChangeconcatination ();
 //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);
























      }, (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.name  = this.concatinationname ;
	  

 
this.entryForm.value.texts  = this.concatinationtexts ;
	  

//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);





















// approve code
        this.serverData = this.serverData.map((item) => {
          item.tablename = this.approved_field_tablename;          
         return item;
        });         this.serverData = this.serverData.map((item) => {
          item.service_order_id = data.id;          
          return item;         });
        console.log(this.serverData);      
  this.serverData.forEach((item) => {
           this.mainService.create_approved(item).subscribe(
            (data) => {               console.log(data);             })
          })          // approved code end 


      }, (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.getdatagggsData();



  //calculated field start

  
 
  this.concatinationname  = '';
 

 
  this.concatinationtexts  = '';
 



  this.concatinationtotal = '';

  //calculated field end






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

} 








//Value List field start    
valuelistMode;
searchcusttextvalue_list_field :any;    
 valueListModalvalue_list_field :boolean=false;
    openvalueListvalue_list_field(mode){
 this.valueListModalvalue_list_field=!this.valueListModalvalue_list_field ; 
      this.valuelistMode = mode;     }
     customerdatavalue_list_field ;     
cutomererror;
   clickedID:number;

getcustvalue_list_fieldID(id:number){    
 this.clickedID=id;
						    console.log("clicked by id"+ id);
						    this.mainService.getById(id).subscribe((data) => {       console.log(data);
						         if(this.valuelistMode == "ADD"){ 

							
 
							this.entryForm.get('name').setValue(data.name);
							 


						}else if(this.valuelistMode == "EDIT"){

							
 
							this.rowSelected.name= data. name
							 


						}       });       this.valueListModalvalue_list_field =false;
						    }    //value List field end 



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

//datagrid datagggs  filed start    
productdatagggs;     
 rowsdatagggs :any[];
         getHeadersdatagggs () {          
			 this.rowsdatagggs = this.productdatagggs;         
  let headers: string[] = [];
          if(this.rowsdatagggs ) {             
this.rowsdatagggs.forEach((value) => {         
      Object.keys(value).forEach((key) => {
                if(!headers.find((header) => header == key)){
                  headers.push(key)             
    }         
              })                 
     })         
}
         
 return headers;      
   } 
 //datagrid datagggs filed end 
					    
getdatagggsData() {
    this.mainService.getdatagggsAll().subscribe((data) => {
      console.log(data);      this.productdatagggs  = data; 
    });
}



 // calculated field code start 

 
 concatinationname; 
  

 
 concatinationtexts; 
  

  concatinationtotal ; 
 concatinationcalculateOperators = "Forma_ListFilter1/Forma_ListFilter1"
onInputChangeconcatination() {
const lastObj = 0
const lastObjstring = ''
	
 

    const name= this.concatinationname|| '';

	const nameValue = parseFloat(this.concatinationname) || 0;

	  

 

    const texts= this.concatinationtexts|| '';

	const textsValue = parseFloat(this.concatinationtexts) || 0;

	  

if (this.concatinationcalculateOperators =="Addition") {
 this.concatinationtotal = (   
	
 
		 nameValue +
	 

 
		 textsValue +
	 
 lastObj).toString();
}
if (this.concatinationcalculateOperators == "Subtraction") {
	 this.concatinationtotal = (   

 
 nameValue   -
	 

 
 textsValue   -
	 

	lastObj).toString();
}
if (this.concatinationcalculateOperators =="Multiplication") {
  this.concatinationtotal = (

	
 
	nameValue *
		 

 
	textsValue *
		 

lastObj).toString();
}
if (this.concatinationcalculateOperators =="Division") {
 
	this.concatinationtotal = ( 

 
nameValue   /
	 

 
textsValue   /
	 

lastObj).toString();

}
if (this.concatinationcalculateOperators =="Concatination") {
 this.concatinationtotal =  

 
name+ ' '+
	 

 
texts+ ' '+
	 
 lastObjstring 
}
}

// payment code start
  checkoutModal = false;
  checkout(){     this.checkoutModal = true;   } 
paytmPay(){
    this.checkoutModal = false;     console.log('Paytm Payment started');
    this.mainService.paytmPay(this.entryForm.value).subscribe(data=>{
      console.log(data);    this.onSubmit();     },(error)=>{
      console.log(error);     });   }      orderData = {
    amount: '',    };     
 razorPay(){
    this.checkoutModal = false;
    this.orderData.amount = this.entryForm.value.amount;
    console.log('Razorpay Payment started');
    this.mainService.razorPay(this.orderData).subscribe(data=>{
      console.log(data);       this.onSubmit();     },(error)=>{
      console.log(error);     });   }  // payment code end 

 // approval code 
   serverData:any = [];    
  onAddLines() {
     this.serverData.push({   formCode:"",      
  documentSeq:"",
 approver:"",      
  actionType:"",        
actionTaken:"",
   comments:"",       
 actionedAt:"",     
   tablename:"",
       service_order_id:"",        });      }
      onRemoveLines(index: number){      
  this.serverData.splice(index, 1);
      }   
    oneditAddLines() {    
   this.serverData.push({
     formCode:"",          documentSeq:"",          approver:"",
          actionType:"",          actionTaken:"",          comments:"",
          actionedAt:"",          tablename:"",
          service_order_id:"",          });        }
        oneditRemoveLines(index: number){          this.serverData.splice(index, 1);
        }   // approval code end 

// updateaction
}























