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

manufacturer : [null],

type : [null],


product : [null],


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

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




 













  }); // 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 === "Product_selection_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.getallmanufacturer();


    // Listen for country changes

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

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



    // Listen for country changes

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

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









  }














 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;




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

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





//calculated field start
	
 
	   this.totalprice= row.price;
	  

 
	   this.totalquantity= row.quantity;
	  

//calculated 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.rowSelected.price= this.totalprice;
	 

 
this.rowSelected.quantity= this.totalquantity;
	 

this.onInputChangetotal ();
 //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.price  = this.totalprice ;
	  

 
this.entryForm.value.quantity  = this.totalquantity ;
	  

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














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











  //calculated field start

  
 
  this.totalprice  = '';
 

 
  this.totalquantity  = '';
 



  this.totaltotal = '';

  //calculated field end


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

} 


selectmanufacturer ;     
getallmanufacturer() {
 this.mainService.getAllmanufacturer().subscribe(data=>{
this.selectmanufacturer = data;       
console.log(data);
},(error) => {       console.log(error);     });   }							   

//  Dependemt Dropdown field start   

 
  typedependentData: any;    
dependet2type (item){
    this.mainService.gettypeDependent(item).subscribe( (data) => {
        console.log(data);     
    this.typedependentData = data;
  },(error) => {     console.log(error);   });
 }


   //  DependemtDropdown field end

//  Dependemt Dropdown field start   

 
  productdependentData: any;    
dependet2product (item){
    this.mainService.getproductDependent(item).subscribe( (data) => {
        console.log(data);     
    this.productdependentData = data;
  },(error) => {     console.log(error);   });
 }


   //  DependemtDropdown field end





 // calculated field code start 

 
 totalprice; 
  

 
 totalquantity; 
  

  totaltotal ; 
 totalcalculateOperators = "Product"
onInputChangetotal() {
const lastObj = 0
const lastObjstring = ''
	
 

    const price= this.totalprice|| '';

	const priceValue = parseFloat(this.totalprice) || 0;

	  

 

    const quantity= this.totalquantity|| '';

	const quantityValue = parseFloat(this.totalquantity) || 0;

	  

if (this.totalcalculateOperators =="Addition") {
 this.totaltotal = (   
	
 
		 priceValue +
	 

 
		 quantityValue +
	 
 lastObj).toString();
}
if (this.totalcalculateOperators == "Subtraction") {
	 this.totaltotal = (   

 
 priceValue   -
	 

 
 quantityValue   -
	 

	lastObj).toString();
}
if (this.totalcalculateOperators =="Multiplication") {
  this.totaltotal = (

	
 
	priceValue *
		 

 
	quantityValue *
		 

lastObj).toString();
}
if (this.totalcalculateOperators =="Division") {
 
	this.totaltotal = ( 

 
priceValue   /
	 

 
quantityValue   /
	 

lastObj).toString();

}
if (this.totalcalculateOperators =="Concatination") {
 this.totaltotal =  

 
price+ ' '+
	 

 
quantity+ ' '+
	 
 lastObjstring 
}
}

// updateaction
}













