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

child: this.childinitLinesForm(),

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

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









contry : [null],

state : [null],


distric : [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 === "Adv3_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 








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

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

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

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

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

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

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

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

this.getallcontry();



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


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

        const found = this.selectcontry.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 });
        }

      }
    });
}


    // Listen for country changes

 
    this.entryForm.get('contry')?.valueChanges.subscribe((item) => {
 

      if (item) {
        this.dependet2state(item);
      } else {
        this.statedependentData = [];
        this.entryForm.get('state')?.setValue(null); // clear state
      }
    });



    // Listen for country changes

 
    this.entryForm.get('state')?.valueChanges.subscribe((item) => {
 

      if (item) {
        this.dependet2distric(item);
      } else {
        this.districdependentData = [];
        this.entryForm.get('distric')?.setValue(null); // clear state
      }
    });



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


childinitLinesForm() {   return this._fb.group({

 
  active: [null],
 

 
  description: [null],
 

 
  name: [null],
 
		

});   } 
		



















 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;


















//  Dependemt Dropdown field start
this.dependet2state(row.dependentDD);
  //  Dependemt Dropdown field end

//  Dependemt Dropdown field start
this.dependet2distric(row.dependentDD);
  //  Dependemt Dropdown 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.onInputChangecalculated_add ('edit');
 //calculated field end

//calculated field start
	
this.onInputChangecalculated_sub ('edit');
 //calculated field end

//calculated field start
	
this.onInputChangecalculated_mul ('edit');
 //calculated field end

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






















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

} 









  // calculated field code start 


 
 calculated_addage_1; 
  

 
 calculated_addage2; 
  


  calculated_addtotal;
  calculated_addcalculateOperators: 'Addition' | 'Subtraction' | 'Multiplication' | 'Division' | 'Concatination' = "Addition"
  onInputChangecalculated_add(mode: 'add' | 'edit') {

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

 
      this.calculated_addage2 = this.entryForm.value.age2 || '';
       


    } else {

 
      this.calculated_addage_1 = this.rowSelected.age_1;
 

 
      this.calculated_addage2 = this.rowSelected.age2;
 

    }
    
 
    const age_1Value = parseFloat(this.calculated_addage_1) || 0;
     

 
    const age2Value = parseFloat(this.calculated_addage2) || 0;
     

    switch (this.calculated_addcalculateOperators) {
      case 'Addition':
        this.calculated_addtotal = (
          
 
          age_1Value +
           

 
          age2Value +
           

          lastObj).toString();
        break;
      case 'Subtraction':
        this.calculated_addtotal = (
          
 
          age_1Value -
           

 
          age2Value -
           

          lastObj).toString();
        break;
      case 'Multiplication':
        this.calculated_addtotal = (
          
 
          age_1Value *
           

 
          age2Value *
           

         1).toString();

        break;
      case 'Division':

        this.calculated_addtotal = (
          
 
          age_1Value /
           

 
          age2Value /
           

          1).toString();

        break;
      case 'Concatination':
        this.calculated_addtotal = `
          
 
          ${this.calculated_addage_1 || ''}
           

 
          ${this.calculated_addage2 || ''}
           

          ${lastObjstring || ''}`;

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



  // calculated field code start 


 
 calculated_subage_1; 
  

 
 calculated_subage2; 
  


  calculated_subtotal;
  calculated_subcalculateOperators: 'Addition' | 'Subtraction' | 'Multiplication' | 'Division' | 'Concatination' = "Subtraction"
  onInputChangecalculated_sub(mode: 'add' | 'edit') {

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

 
      this.calculated_subage2 = this.entryForm.value.age2 || '';
       


    } else {

 
      this.calculated_subage_1 = this.rowSelected.age_1;
 

 
      this.calculated_subage2 = this.rowSelected.age2;
 

    }
    
 
    const age_1Value = parseFloat(this.calculated_subage_1) || 0;
     

 
    const age2Value = parseFloat(this.calculated_subage2) || 0;
     

    switch (this.calculated_subcalculateOperators) {
      case 'Addition':
        this.calculated_subtotal = (
          
 
          age_1Value +
           

 
          age2Value +
           

          lastObj).toString();
        break;
      case 'Subtraction':
        this.calculated_subtotal = (
          
 
          age_1Value -
           

 
          age2Value -
           

          lastObj).toString();
        break;
      case 'Multiplication':
        this.calculated_subtotal = (
          
 
          age_1Value *
           

 
          age2Value *
           

         1).toString();

        break;
      case 'Division':

        this.calculated_subtotal = (
          
 
          age_1Value /
           

 
          age2Value /
           

          1).toString();

        break;
      case 'Concatination':
        this.calculated_subtotal = `
          
 
          ${this.calculated_subage_1 || ''}
           

 
          ${this.calculated_subage2 || ''}
           

          ${lastObjstring || ''}`;

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



  // calculated field code start 


 
 calculated_mulage_1; 
  

 
 calculated_mulage2; 
  


  calculated_multotal;
  calculated_mulcalculateOperators: 'Addition' | 'Subtraction' | 'Multiplication' | 'Division' | 'Concatination' = "Multiplication"
  onInputChangecalculated_mul(mode: 'add' | 'edit') {

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

 
      this.calculated_mulage2 = this.entryForm.value.age2 || '';
       


    } else {

 
      this.calculated_mulage_1 = this.rowSelected.age_1;
 

 
      this.calculated_mulage2 = this.rowSelected.age2;
 

    }
    
 
    const age_1Value = parseFloat(this.calculated_mulage_1) || 0;
     

 
    const age2Value = parseFloat(this.calculated_mulage2) || 0;
     

    switch (this.calculated_mulcalculateOperators) {
      case 'Addition':
        this.calculated_multotal = (
          
 
          age_1Value +
           

 
          age2Value +
           

          lastObj).toString();
        break;
      case 'Subtraction':
        this.calculated_multotal = (
          
 
          age_1Value -
           

 
          age2Value -
           

          lastObj).toString();
        break;
      case 'Multiplication':
        this.calculated_multotal = (
          
 
          age_1Value *
           

 
          age2Value *
           

         1).toString();

        break;
      case 'Division':

        this.calculated_multotal = (
          
 
          age_1Value /
           

 
          age2Value /
           

          1).toString();

        break;
      case 'Concatination':
        this.calculated_multotal = `
          
 
          ${this.calculated_mulage_1 || ''}
           

 
          ${this.calculated_mulage2 || ''}
           

          ${lastObjstring || ''}`;

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



  // calculated field code start 


 
 calculated_divage2; 
  

 
 calculated_divage_1; 
  


  calculated_divtotal;
  calculated_divcalculateOperators: 'Addition' | 'Subtraction' | 'Multiplication' | 'Division' | 'Concatination' = "Division"
  onInputChangecalculated_div(mode: 'add' | 'edit') {

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

 
      this.calculated_divage_1 = this.entryForm.value.age_1 || '';
       


    } else {

 
      this.calculated_divage2 = this.rowSelected.age2;
 

 
      this.calculated_divage_1 = this.rowSelected.age_1;
 

    }
    
 
    const age2Value = parseFloat(this.calculated_divage2) || 0;
     

 
    const age_1Value = parseFloat(this.calculated_divage_1) || 0;
     

    switch (this.calculated_divcalculateOperators) {
      case 'Addition':
        this.calculated_divtotal = (
          
 
          age2Value +
           

 
          age_1Value +
           

          lastObj).toString();
        break;
      case 'Subtraction':
        this.calculated_divtotal = (
          
 
          age2Value -
           

 
          age_1Value -
           

          lastObj).toString();
        break;
      case 'Multiplication':
        this.calculated_divtotal = (
          
 
          age2Value *
           

 
          age_1Value *
           

         1).toString();

        break;
      case 'Division':

        this.calculated_divtotal = (
          
 
          age2Value /
           

 
          age_1Value /
           

          1).toString();

        break;
      case 'Concatination':
        this.calculated_divtotal = `
          
 
          ${this.calculated_divage2 || ''}
           

 
          ${this.calculated_divage_1 || ''}
           

          ${lastObjstring || ''}`;

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


contrydefault=false
selectcontry ;     
getallcontry() {
 this.mainService.getAllcontry().subscribe(data=>{
this.selectcontry = data;       
console.log(data);
},(error) => {       console.log(error);     });   }		



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


   

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

 
      const found = this.selectcontry.find(p => p.name === formValue.contry);
 

    

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

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

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

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

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

  /**
   * Calculate grand total (subtotal + GST)
   */
  getcontryGrandTotal(): number {
    return this.getcontrySubtotal() + this.getcontryGST();

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


//  Dependemt Dropdown field start   

 
  statedependentData: any;    
dependet2state (item){
    this.mainService.getstateDependent(item).subscribe( (data) => {
        console.log(data);     
    this.statedependentData = data;
  },(error) => {     console.log(error);   });
 }


   //  DependemtDropdown field end

//  Dependemt Dropdown field start   

 
  districdependentData: any;    
dependet2distric (item){
    this.mainService.getdistricDependent(item).subscribe( (data) => {
        console.log(data);     
    this.districdependentData = data;
  },(error) => {     console.log(error);   });
 }


   //  DependemtDropdown field end

// updateaction
}





















