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

sta_select : [null],

stat_mulsel : [null],

dyan_sel : [null],

dyna_mul : [null],

autoc : [null],

auto_mul : [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 === "Adv2s_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.getalldyan_sel();



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


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

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

this.getallautoc();

this.getallauto_mul();




  }
 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.nodeEditPropertiesstat_mulsel.editselectedAttributesstat_mulsel = JSON.parse(this.rowSelected.stat_mulsel );



this.nodeEditPropertiesdyna_mul.editselectedAttributesdyna_mul = JSON.parse(this.rowSelected.dyna_mul );



this.nodeEditPropertiesauto_mul.editselectedAttributesauto_mul = JSON.parse(this.rowSelected.auto_mul );




    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.stat_mulsel  = JSON.stringify(this.nodeEditPropertiesstat_mulsel.editselectedAttributesstat_mulsel  );



this.rowSelected.dyna_mul  = JSON.stringify(this.nodeEditPropertiesdyna_mul.editselectedAttributesdyna_mul  );



this.rowSelected.auto_mul  = JSON.stringify(this.nodeEditPropertiesauto_mul.editselectedAttributesauto_mul  );



    //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.stat_mulsel  = JSON.stringify(this.nodeEditPropertiesstat_mulsel.addselectedAttributesstat_mulsel );



this.entryForm.value.dyna_mul  = JSON.stringify(this.nodeEditPropertiesdyna_mul.addselectedAttributesdyna_mul );



this.entryForm.value.auto_mul  = JSON.stringify(this.nodeEditPropertiesauto_mul.addselectedAttributesauto_mul );



  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.nodeEditPropertiesdyna_mul.addselectedAttributesdyna_mul = ""



this.nodeEditPropertiesauto_mul.addselectedAttributesauto_mul = ""




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

} 




nodeEditPropertiesstat_mulsel  = {   addselectedAttributesstat_mulsel :"",   editselectedAttributesstat_mulsel :"" }
							 selectstat_mulsel =[
								
 
								'x',
								 

 
								'y',
								 

 
								'z',
								 

							];

dyan_seldefault=false
selectdyan_sel ;     
getalldyan_sel() {
 this.mainService.getAlldyan_sel().subscribe(data=>{
this.selectdyan_sel = data;       
console.log(data);
},(error) => {       console.log(error);     });   }		



  // ================== ORDER SUMMARY LOGIC START ==================
  /**
   * Order Summary Array and Methods for Add to Order functionality
   */
  dyan_selSummary: any[] = [];
  dyan_seltotal;
isdyan_selorder =false;
  /**
   * Add selected product to order summary
   */
  adddyan_selOrder() {
    const formValue = this.entryForm.value;
    if (!formValue.dyan_sel ) {
      this.toastr.error('Please select dyan sel');
      return;
    }
    // Get description from master (selectdyan_sel)


   

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

 
      const found = this.selectdyan_sel.find(p => p.name === formValue.dyan_sel);
 

    

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

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

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

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

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

  /**
   * Calculate grand total (subtotal + GST)
   */
  getdyan_selGrandTotal(): number {
    return this.getdyan_selSubtotal() + this.getdyan_selGST();

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


selectdyna_mul;    
 getalldyna_mul () {
		this.mainService.getAlldyna_mul().subscribe(data=>{
							      this.selectdyna_mul = data;     
  console.log(data);
 },(error) => {       console.log(error);     });   } 
 nodeEditPropertiesdyna_mul  = {     addselectedAttributesdyna_mul:"",  editselectedAttributesdyna_mul :""   }

selectautoc ;    
 getallautoc () {
							    this.mainService.getAllautoc().subscribe(data=>{
							      this.selectautoc = data;       console.log(data);
							    },(error) => {       console.log(error);     });   }

selectauto_mul;    
 getallauto_mul () {
		this.mainService.getAllauto_mul().subscribe(data=>{
							      this.selectauto_mul = data;     
  console.log(data);
 },(error) => {       console.log(error);     });   } 
 nodeEditPropertiesauto_mul  = {     addselectedAttributesauto_mul:"",  editselectedAttributesauto_mul :""   }



// updateaction
}















