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({
 

 



country : [null],

state : [null],

stmlit : [null],

stmmlt2 : [null],

dy2 : [null],

dy1 : [null],

dymlti1 : [null],

dymlt2 : [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 














this.getalldy2();



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


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

        const found = this.selectdy2.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.getalldy1();



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


 
    this.entryForm.get('dy1')?.valueChanges.subscribe(description => {
      if (description && this.selectdy1) {

        const found = this.selectdy1.find(p => p.description === description);
 


        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.getalldymlti1();

this.getalldymlt2();


  }
 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.nodeEditPropertiesstmlit.editselectedAttributesstmlit = JSON.parse(this.rowSelected.stmlit );

this.nodeEditPropertiesstmmlt2.editselectedAttributesstmmlt2 = JSON.parse(this.rowSelected.stmmlt2 );





this.nodeEditPropertiesdymlti1.editselectedAttributesdymlti1 = JSON.parse(this.rowSelected.dymlti1 );

this.nodeEditPropertiesdymlt2.editselectedAttributesdymlt2 = JSON.parse(this.rowSelected.dymlt2 );


    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.stmlit  = JSON.stringify(this.nodeEditPropertiesstmlit.editselectedAttributesstmlit  );

this.rowSelected.stmmlt2  = JSON.stringify(this.nodeEditPropertiesstmmlt2.editselectedAttributesstmmlt2  );





this.rowSelected.dymlti1  = JSON.stringify(this.nodeEditPropertiesdymlti1.editselectedAttributesdymlti1  );

this.rowSelected.dymlt2  = JSON.stringify(this.nodeEditPropertiesdymlt2.editselectedAttributesdymlt2  );

    //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.stmlit  = JSON.stringify(this.nodeEditPropertiesstmlit.addselectedAttributesstmlit );

this.entryForm.value.stmmlt2  = JSON.stringify(this.nodeEditPropertiesstmmlt2.addselectedAttributesstmmlt2 );





this.entryForm.value.dymlti1  = JSON.stringify(this.nodeEditPropertiesdymlti1.addselectedAttributesdymlti1 );

this.entryForm.value.dymlt2  = JSON.stringify(this.nodeEditPropertiesdymlt2.addselectedAttributesdymlt2 );

  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.getdatagrid_fieldData();

 this.getdatagrid_field2Data();















this.nodeEditPropertiesdymlti1.addselectedAttributesdymlti1 = ""

this.nodeEditPropertiesdymlt2.addselectedAttributesdymlt2 = ""


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

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

//datagrid datagrid_field2  filed start    
productdatagrid_field2;     
 rowsdatagrid_field2 :any[];
         getHeadersdatagrid_field2 () {          
			 this.rowsdatagrid_field2 = this.productdatagrid_field2;         
  let headers: string[] = [];
          if(this.rowsdatagrid_field2 ) {             
this.rowsdatagrid_field2.forEach((value) => {         
      Object.keys(value).forEach((key) => {
                if(!headers.find((header) => header == key)){
                  headers.push(key)             
    }         
              })                 
     })         
}
         
 return headers;      
   } 
 //datagrid datagrid_field2 filed end 
					    
getdatagrid_field2Data() {
    this.mainService.getdatagrid_field2All().subscribe((data) => {
      console.log(data);      this.productdatagrid_field2  = data; 
    });
}







nodeEditPropertiesstmlit  = {   addselectedAttributesstmlit :"",   editselectedAttributesstmlit :"" }
							 selectstmlit =[
								
 
								'bihar',
								 

 
								'sikkim',
								 

							];

nodeEditPropertiesstmmlt2  = {   addselectedAttributesstmmlt2 :"",   editselectedAttributesstmmlt2 :"" }
							 selectstmmlt2 =[
								
 
								'p2',
								 

 
								'p3',
								 

 
								'ap',
								 

							];

dy2default=false
selectdy2 ;     
getalldy2() {
 this.mainService.getAlldy2().subscribe(data=>{
this.selectdy2 = data;       
console.log(data);
},(error) => {       console.log(error);     });   }		



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


   

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

 
      const found = this.selectdy2.find(p => p.name === formValue.dy2);
 

    

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

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

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

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

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

  /**
   * Calculate grand total (subtotal + GST)
   */
  getdy2GrandTotal(): number {
    return this.getdy2Subtotal() + this.getdy2GST();

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


dy1default=false
selectdy1 ;     
getalldy1() {
 this.mainService.getAlldy1().subscribe(data=>{
this.selectdy1 = data;       
console.log(data);
},(error) => {       console.log(error);     });   }		



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


   

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

 
      const found = this.selectdy1.find(p => p.description === formValue.dy1);
 

    

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

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

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

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

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

  /**
   * Calculate grand total (subtotal + GST)
   */
  getdy1GrandTotal(): number {
    return this.getdy1Subtotal() + this.getdy1GST();

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


selectdymlti1;    
 getalldymlti1 () {
		this.mainService.getAlldymlti1().subscribe(data=>{
							      this.selectdymlti1 = data;     
  console.log(data);
 },(error) => {       console.log(error);     });   } 
 nodeEditPropertiesdymlti1  = {     addselectedAttributesdymlti1:"",  editselectedAttributesdymlti1 :""   }

selectdymlt2;    
 getalldymlt2 () {
		this.mainService.getAlldymlt2().subscribe(data=>{
							      this.selectdymlt2 = data;     
  console.log(data);
 },(error) => {       console.log(error);     });   } 
 nodeEditPropertiesdymlt2  = {     addselectedAttributesdymlt2:"",  editselectedAttributesdymlt2 :""   }

// updateaction
}





















