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

contact_person : [null],

manufacturer : [null],

type : [null],


product : [null],


email_address : [null],

customer_address : [null],

deployment_type : [null],

  
 
dg_monitoring___with_fule:[false],
   

 
active_energy:[false],
   

 
dg_monitoring___without_fule:[false],
   

 
ups_monitoring:[false],
   

 
apfc_panel_monitoring:[false],
   

 
busbar_monitoring:[false],
   

 
lt_panel_monitoring:[false],
   

 
ht_panel_monitoring:[false],
   

 
compressed_air__gag_monitoring:[false],
   

 
water_management_stp_etp:[false],
   

 
compressed_air___lpg_n2_o2_co2:[false],
   

 
water_management_water_monitoring:[false],
   


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

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



description : [null],



phone_number: ['+91'],


 





























  }); // 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 === "Customer_information_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();



    if (this.manufacturerdefault) {
    // Listen for product changes to auto-fill description
    this.entryForm.get('manufacturer')?.valueChanges.subscribe(name => {
      if (name && this.selectmanufacturer) {

        const found = this.selectmanufacturer.find(p => p.default_field_link === 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('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
      }
    });






this.getalldeployment_type();



    if (this.deployment_typedefault) {
    // Listen for product changes to auto-fill description
    this.entryForm.get('deployment_type')?.valueChanges.subscribe(name => {
      if (name && this.selectdeployment_type) {

        const found = this.selectdeployment_type.find(p => p.default_field_link === 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 });
        }

      }
    });
}







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

// Start polling for edit changes
    this.editInterval = setInterval(() => {
      if (this.modalEdit) {
        this.onInputChangetotal('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;






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

//  Dependemt Dropdown field start
this.dependet2product(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.onInputChangetotal ('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();

} 


rsModalcontact_person = false;   
goToReplaceStringcontact_person(row){
this.rowSelected = row;     this.rsModalcontact_person  =true;   }

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



  // ================== ORDER SUMMARY LOGIC START ==================
  /**
   * Order Summary Array and Methods for Add to Order functionality
   */
  manufacturerSummary: any[] = [];
  manufacturertotal;
ismanufacturerorder =false;
  /**
   * Add selected product to order summary
   */
  addmanufacturerOrder() {
    const formValue = this.entryForm.value;
    if (!formValue.manufacturer ) {
      this.toastr.error('Please select Manufacturer');
      return;
    }
    // Get description from master (selectmanufacturer)


   

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

 
      const found = this.selectmanufacturer.find(p => p.manufacturer_name === formValue.manufacturer);
 

    

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

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

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

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

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

  /**
   * Calculate grand total (subtotal + GST)
   */
  getmanufacturerGrandTotal(): number {
    return this.getmanufacturerSubtotal() + this.getmanufacturerGST();

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


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

isValidemail_address(email: string): boolean {
						 const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
						    return emailPattern.test(email);   }

rsModalcustomer_address = false;  
 goToReplaceStringcustomer_address (row){
						    this.rowSelected = row;     this.rsModalcustomer_address  =true;   }

deployment_typedefault=false
selectdeployment_type ;     
getalldeployment_type() {
 this.mainService.getAlldeployment_type().subscribe(data=>{
this.selectdeployment_type = data;       
console.log(data);
},(error) => {       console.log(error);     });   }		



  // ================== ORDER SUMMARY LOGIC START ==================
  /**
   * Order Summary Array and Methods for Add to Order functionality
   */
  deployment_typeSummary: any[] = [];
  deployment_typetotal;
isdeployment_typeorder =false;
  /**
   * Add selected product to order summary
   */
  adddeployment_typeOrder() {
    const formValue = this.entryForm.value;
    if (!formValue.deployment_type ) {
      this.toastr.error('Please select Deployment Type');
      return;
    }
    // Get description from master (selectdeployment_type)


   

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

 
      const found = this.selectdeployment_type.find(p => p.deployment_type === formValue.deployment_type);
 

    

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

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

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

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

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

  /**
   * Calculate grand total (subtotal + GST)
   */
  getdeployment_typeGrandTotal(): number {
    return this.getdeployment_typeSubtotal() + this.getdeployment_typeGST();

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









  // calculated field code start 


 
 totalquantity; 
  

 
 totalprice; 
  


  totaltotal;
  totalcalculateOperators: 'Addition' | 'Subtraction' | 'Multiplication' | 'Division' | 'Concatination' = "Multiplication"
  onInputChangetotal(mode: 'add' | 'edit') {

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

 
      this.totalprice = this.entryForm.value.price || '';
       


    } else {

 
      this.totalquantity = this.rowSelected.quantity;
 

 
      this.totalprice = this.rowSelected.price;
 

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

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

    switch (this.totalcalculateOperators) {
      case 'Addition':
        this.totaltotal = (
          
 
          quantityValue +
           

 
          priceValue +
           

          lastObj).toString();
        break;
      case 'Subtraction':
        this.totaltotal = (
          
 
          quantityValue -
           

 
          priceValue -
           

          lastObj).toString();
        break;
      case 'Multiplication':
        this.totaltotal = (
          
 
          quantityValue *
           

 
          priceValue *
           

         1).toString();

        break;
      case 'Division':

        this.totaltotal = (
          
 
          quantityValue /
           

 
          priceValue /
           

          1).toString();

        break;
      case 'Concatination':
        this.totaltotal = `
          
 
          ${this.totalquantity || ''}
           

 
          ${this.totalprice || ''}
           

          ${lastObjstring || ''}`;

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


rsModaldescription = false;  
 goToReplaceStringdescription (row){
						    this.rowSelected = row;     this.rsModaldescription  =true;   }

//Value List field start    
order_summaryMode;
searchcusttextorder_summary :any;    
 valueListModalorder_summary :boolean=false;
    openvalueListorder_summary(mode){
 this.valueListModalorder_summary=!this.valueListModalorder_summary ; 
      this.order_summaryMode = mode;     }
     customerdataorder_summary ;     
order_summaryerror;
clickedorder_summaryID:number;

getcustorder_summaryID(id:number){    
 this.clickedorder_summaryID=id;
						    console.log("clicked by id"+ id);
						    this.mainService.getById(id).subscribe((data) => {       console.log(data);
						         if(this.order_summaryMode == "ADD"){ 

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

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

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

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

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


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

							
 
							this.rowSelected.product= data. product
							 

 
							this.rowSelected.description= data. description
							 

 
							this.rowSelected.price= data. price
							 

 
							this.rowSelected.quantity= data. quantity
							 

 
							this.rowSelected.total= data. total
							 


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

isValidPhone_number(phone: string): boolean {
  const phonePattern = /^(\+[1-9][0-9]{0,2})?[1-9][0-9]{9}$/;
  return phonePattern.test(phone);
}

// updateaction
}





























