import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AlertService } from 'src/app/services/alert.service';
import { Testbservice} from './Testb.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 { Testbcardvariable } from './Testb_cardvariable';
import { UserInfoService } from 'src/app/services/user-info.service';
declare var JsBarcode: any; 
@Component({
  selector: 'app-Testb',
  templateUrl: './Testb.component.html',
  styleUrls: ['./Testb.component.scss']
})
export class TestbComponent implements OnInit {
  cardButton = Testbcardvariable.cardButton;
  cardmodeldata = Testbcardvariable.cardmodeldata;
  public dashboardArray: DashboardContentModel2[];
  isCardview = Testbcardvariable.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 = 'Testb_formCode'
tableName = 'Testb';  checkFormCode; selected: any[] = []; constructor(
    private extensionService: ExtensionService,
private userInfoService:UserInfoService,
    private mainService:Testbservice,
    private alertService: AlertService,
    private toastr: ToastrService,
    private _fb: FormBuilder,
  ) { }
  private editInterval: any;
// 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({
snames : [null],

select_sta : [null],

select_statmul : [null],

selectdya : [null],

select_dynmul : [null],

select_auto : [null],

select_automul : [null],

radio : [null],

  
 
f:[false],
   

 
g:[false],
   

 
h:[false],
   




 

qrcode_field : [null],

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

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



child : [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 === "Testb_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.getallselectdya();



    if (this.selectdyadefault) {
    // Listen for product changes to auto-fill description


 
    this.entryForm.get('selectdya')?.valueChanges.subscribe(name => {
      if (name && this.selectselectdya) {

        const found = this.selectselectdya.find(p => p.name === name);
 


        console.log('found is ', found);

        // Auto-fill price when product is selected
        if (found && found.default_field) {
          this.entryForm.patchValue({ default_field: found.default_field_link });
        } else {
          this.entryForm.patchValue({ default_field: null });
        }

      }
    });
}

this.getallselect_dynmul();

this.getallselect_auto();

this.getallselect_automul();















  // Subscribe to value changes for auto calculation
    this.entryForm.valueChanges.subscribe(() => {
      this.onInputChangecalculated_field('add');
    });

// Start polling for edit changes
    this.editInterval = setInterval(() => {
      if (this.modalEdit) {
        this.onInputChangecalculated_field('edit');
      }
    }, 200);




  }
 ngOnDestroy(): void {
    if (this.editInterval) {
      clearInterval(this.editInterval);
    }
  }































 error; 
  getData() {
    this.mainService.getAll().subscribe((data) => {
      console.log(data);
      this.product = data;
this.product = [...this.product].reverse(); 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.nodeEditPropertiesselect_statmul.editselectedAttributesselect_statmul = JSON.parse(this.rowSelected.select_statmul );



this.nodeEditPropertiesselect_dynmul.editselectedAttributesselect_dynmul = JSON.parse(this.rowSelected.select_dynmul );



this.nodeEditPropertiesselect_automul.editselectedAttributesselect_automul = JSON.parse(this.rowSelected.select_automul );




















    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;




this.rowSelected.select_statmul  = JSON.stringify(this.nodeEditPropertiesselect_statmul.editselectedAttributesselect_statmul  );



this.rowSelected.select_dynmul  = JSON.stringify(this.nodeEditPropertiesselect_dynmul.editselectedAttributesselect_dynmul  );



this.rowSelected.select_automul  = JSON.stringify(this.nodeEditPropertiesselect_automul.editselectedAttributesselect_automul  );















//calculated field start
	
this.onInputChangecalculated_field ('edit');
 //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;




this.entryForm.value.select_statmul  = JSON.stringify(this.nodeEditPropertiesselect_statmul.addselectedAttributesselect_statmul );



this.entryForm.value.select_dynmul  = JSON.stringify(this.nodeEditPropertiesselect_dynmul.addselectedAttributesselect_dynmul );



this.entryForm.value.select_automul  = JSON.stringify(this.nodeEditPropertiesselect_automul.addselectedAttributesselect_automul );



















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
































      }, (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.nodeEditPropertiesselect_dynmul.addselectedAttributesselect_dynmul = ""



this.nodeEditPropertiesselect_automul.addselectedAttributesselect_automul = ""







 this.getdatagrid_fieldData();












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

} 




nodeEditPropertiesselect_statmul  = {   addselectedAttributesselect_statmul :"",   editselectedAttributesselect_statmul :"" }
							 selectselect_statmul =[
								
 
								'ac',
								 

 
								'cn',
								 

 
								'cb',
								 

							];

selectdyadefault=false
selectselectdya ;     
getallselectdya() {
 this.mainService.getAllselectdya().subscribe(data=>{
this.selectselectdya = data;       
console.log(data);
},(error) => {       console.log(error);     });   }		



  // ================== ORDER SUMMARY LOGIC START ==================
  /**
   * Order Summary Array and Methods for Add to Order functionality
   */
  selectdyaSummary: any[] = [];
  selectdyatotal;
isselectdyaorder =false;
  /**
   * Add selected product to order summary
   */
  addselectdyaOrder() {
    const formValue = this.entryForm.value;
    if (!formValue.selectdya ) {
      this.toastr.error('Please select selectdya');
      return;
    }
    // Get description from master (selectselectdya)


   

    if (this.selectselectdya && Array.isArray(this.selectselectdya)) {

 
      const found = this.selectselectdya.find(p => p.name === formValue.selectdya);
 

    

    }
    const line = this.selectdyaSummary.length + 1;
    const orderItem = {
      line: line,

      // unitPrice: Number(formValue.price),
      // quantity: Number(formValue.quantity),
      // total: Number(formValue.price) * Number(formValue.quantity)
    };
    this.selectdyaSummary.push(orderItem);
    
    this.selectdyatotal = '';
  }

  /**
   * Remove item from order summary by index
   */
  removeselectdyaOrder(index: number) {
    this.selectdyaSummary.splice(index, 1);
    // Recalculate line numbers
    this.selectdyaSummary.forEach((item, i) => {
      item.line = i + 1;
    });
  }

  /**
   * Calculate subtotal of all order items
   */
  getselectdyaSubtotal(): number {
    return this.selectdyaSummary.reduce((sum, item) => sum + item.total, 0);
  }

  /**
   * Calculate GST (18%)
   */
  getselectdyaGST(): number {
    return this.getselectdyaSubtotal() * 0.18;
  }

  /**
   * Calculate grand total (subtotal + GST)
   */
  getselectdyaGrandTotal(): number {
    return this.getselectdyaSubtotal() + this.getselectdyaGST();

  }
  // ================== ORDER SUMMARY LOGIC END ==================


selectselect_dynmul;    
 getallselect_dynmul () {
		this.mainService.getAllselect_dynmul().subscribe(data=>{
							      this.selectselect_dynmul = data;     
  console.log(data);
 },(error) => {       console.log(error);     });   } 
 nodeEditPropertiesselect_dynmul  = {     addselectedAttributesselect_dynmul:"",  editselectedAttributesselect_dynmul :""   }

selectselect_auto ;    
 getallselect_auto () {
							    this.mainService.getAllselect_auto().subscribe(data=>{
							      this.selectselect_auto = data;       console.log(data);
							    },(error) => {       console.log(error);     });   }

selectselect_automul;    
 getallselect_automul () {
		this.mainService.getAllselect_automul().subscribe(data=>{
							      this.selectselect_automul = data;     
  console.log(data);
 },(error) => {       console.log(error);     });   } 
 nodeEditPropertiesselect_automul  = {     addselectedAttributesselect_automul:"",  editselectedAttributesselect_automul :""   }

updateradio (radio : string): void {    
 this.entryForm.get('radio').setValue(radio);   }

updateradioEdit(radio : string): void {    this.rowSelected.radio  =  radio }
						 ;



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

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

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


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

							
 
							this.rowSelected.snames= data. snames
							 


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

//datagrid datagrid_field  filed start    
productdatagrid_field;     
 rowsdatagrid_field :any[];
         getHeadersdatagrid_field () {          
			 this.rowsdatagrid_field = this.productdatagrid_field;         
  let headers: string[] = [];
          if(this.rowsdatagrid_field ) {             
this.rowsdatagrid_field.forEach((value) => {         
      Object.keys(value).forEach((key) => {
                if(!headers.find((header) => header == key)){
                  headers.push(key)             
    }         
              })                 
     })         
}
         
 return headers;      
   } 
 //datagrid datagrid_field filed end 
					    
getdatagrid_fieldData() {
    this.mainService.getdatagrid_fieldAll().subscribe((data) => {
      console.log(data);      this.productdatagrid_field  = data; 
    });
}








  // calculated field code start 


 
 calculated_fieldnumber_fieldssss; 
  

 
 calculated_fieldnumber_field; 
  


  calculated_fieldtotal;
  calculated_fieldcalculateOperators: 'Addition' | 'Subtraction' | 'Multiplication' | 'Division' | 'Concatination' = "Lista_ListFilter1/Lista_ListFilter1"
  onInputChangecalculated_field(mode: 'add' | 'edit') {

  
    const lastObj = 0
    const lastObjstring = ''
    if (mode === 'add') {
      
 
      this.calculated_fieldnumber_fieldssss = this.entryForm.value.number_fieldssss || '';
       

 
      this.calculated_fieldnumber_field = this.entryForm.value.number_field || '';
       


    } else {

 
      this.calculated_fieldnumber_fieldssss = this.rowSelected.number_fieldssss;
 

 
      this.calculated_fieldnumber_field = this.rowSelected.number_field;
 

    }
    
 
    const number_fieldssssValue = parseFloat(this.calculated_fieldnumber_fieldssss) || 0;
     

 
    const number_fieldValue = parseFloat(this.calculated_fieldnumber_field) || 0;
     

    switch (this.calculated_fieldcalculateOperators) {
      case 'Addition':
        this.calculated_fieldtotal = (
          
 
          number_fieldssssValue +
           

 
          number_fieldValue +
           

          lastObj).toString();
        break;
      case 'Subtraction':
        this.calculated_fieldtotal = (
          
 
          number_fieldssssValue -
           

 
          number_fieldValue -
           

          lastObj).toString();
        break;
      case 'Multiplication':
        this.calculated_fieldtotal = (
          
 
          number_fieldssssValue *
           

 
          number_fieldValue *
           

         1).toString();

        break;
      case 'Division':

        this.calculated_fieldtotal = (
          
 
          number_fieldssssValue /
           

 
          number_fieldValue /
           

          1).toString();

        break;
      case 'Concatination':
        this.calculated_fieldtotal = `
          
 
          ${this.calculated_fieldnumber_fieldssss || ''}
           

 
          ${this.calculated_fieldnumber_field || ''}
           

          ${lastObjstring || ''}`;

        break;
      default:
        this.calculated_fieldtotal = '';
    }
  }




// updateaction
}































