import { Component, OnInit } from '@angular/core';
import { PageapiService } from '../../pageapi.service';
import { NbComponentStatus, NbDialogService, NbGlobalPhysicalPosition, NbGlobalPosition, NbToastrService, NbWindowControlButtonsConfig, NbWindowRef, NbWindowService } from '@nebular/theme';
import { SmartTableData } from '../../../@core/data/smart-table';
import { OrderSummaryFormComponent } from '../order-summary-form/order-summary-form.component';
import { ActivatedRoute, Router } from '@angular/router';
 
import pdfMake from "pdfmake/build/pdfmake";
import pdfFonts from "pdfmake/build/vfs_fonts";
import { log } from 'console';
import { AddOrderComponent } from '../add-order/add-order.component';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
class Product{
  name: string;
  price: string;
  qty: number;
}
class Invoice{
  customerName: string;
  address: string;
  contactNo: number;
  email: string;
  
  products: Product[] = [];
  additionalDetails: string;
}
@Component({
  selector: 'ngx-order-form',
  templateUrl: './order-form.component.html',
  styleUrls: ['./order-form.component.scss']
})
export class OrderFormComponent implements OnInit {
  customer:any =[];
  // Filtered customer list for display
  filteredCustomers: any[] = []; // Search query
  searchQuery: string = '';
    product:any =[];
    ResultDisplay:any =[];
  // Selected customer
  selectCustomer: string | null = null;
  mixedGas:any =[];productfull:any=[];
  // selectCustomer:any ="";
  items = [
    { label: 'Item 1', quantity: 0 },
    { label: 'Item 2', quantity: 0 },
    { label: 'Item 3', quantity: 0 }
  ];
fieldTitle:any ='New Order'
  minimize = false;
  maximize = false;
  fullScreen = true;
  close = true;
  formData:any=[];productlistReturn:any =[];
  index = 1;
  destroyByClick = true;
  duration = 2000;
  hasIcon = true;
  setData:any =[];
  position: NbGlobalPosition = NbGlobalPhysicalPosition.TOP_RIGHT;
  preventDuplicates = false;
  status: NbComponentStatus = 'primary'; 
  inputFieldGroups:any = [{id:'', qty: '1', productSpec: '' , productName : '' }]; 
  selectCustomerData :any =[];selectStatus:any =[];CancelReason:any =[];selectDriver:any =[];
  drivers:any =[];
  filteredDrivers: any[] = []; // Search query
  searchDriverQuery: string = '';
  invoice = new Invoice(); 
  hiddenBtn= false;
  dropdown_data: any = null;
  delArr:any=[]
  selectedProductId: number | undefined = null;
  addFormBtn: any;
  selectedProductName: any;
  filteredProducts: any[] = [];
  searchProductQuery: string = '';
   constructor(private dialogService: NbDialogService,private route :ActivatedRoute,private router: Router,public _api:PageapiService,private toastrService: NbToastrService,private service: SmartTableData ,private windowService: NbWindowService) {

    this._api.orderDetails_observable$.subscribe((res) => {
      console.log('booked', res);
      

      if(res){
        this.addFormBtn = 1
        this.setData = res
        this.dropdown_data = this.setData['status'];
        // alert(this.setData['status'])
        console.log(this.setData)
       this.selectStatus = res.status
       console.log(this.selectStatus)
//  res.name = res.productName
//  res.qty = parseInt(res.qty)
//  res.price = this.setData['OrderDetails.CusDetails.cusType']
//  this.invoice.additionalDetails = 'https://vnms.in/services/'
//   this.invoice.products.push(res)
        setTimeout(() => {
          localStorage.setItem('graud','1')
        }, 1300);
       
      }else{
        console.log('else')
        this.addFormBtn = 0
        localStorage.setItem('graud','0')
      }
  
    })

   }    
   receivedMessageHandler(res){
    console.log(res, this.productfull)
   let tmp =[];
    this.productfull.forEach(element => {
      if(element.productName ==  "Mixed Gas"){
        
        tmp.push(element)
      }
    
    });
    console.log(tmp)
    let tmp2 = [];
    res.forEach(element => {
   //   if(element.id !=null ){
        tmp2.push({"productName": tmp[0].productName , productId:tmp[0].id, id:element.id ,qty:element.qty, productSpec:element.productSpec})
     // }
    
    });
    this.mixedGas = tmp2
    console.log(tmp2)
 
   }
   receiveAutoMsgHandler(p) {
    console.log(p)
  }
  ngOnInit() {


    this.getDriverlistApi()
    console.log(this.setData)
    // this.dropdown_data = this.setData['OrderDetails.status'];
    if(this.setData != undefined){

   
    if(  Object.keys(this.setData).length != 0){
      let result = localStorage.getItem('viewOrder')
      if(result == '1'){
        this.fieldTitle = 'View Order'
      }else{
        this.fieldTitle = 'Edit Order'
      }

    }
  }
    this.getuserlistApi()



 
   
  }

   // Filter customers based on search input
   filterCustomers() {
    if (this.searchQuery.trim() === '') {
      this.filteredCustomers = [...this.customer];
    } else {
      this.filteredCustomers = this.customer.filter(user =>
        user['CusDetails.cusName']
          ?.toLowerCase()
          .includes(this.searchQuery.toLowerCase())
      );
    }
  }

 
  getuserlistApi(){
    let param={}
    this._api.getusers(param).subscribe(res => {
   
      if(res.status == 200){

       let passData =  res.data

       let customer = passData.filter(arr=>{return arr.role == 'CUSTOMER' && arr.isActive == 1}) 
       customer.forEach((element:any, index) => {
        element.index = index     +1    
        
      });
      console.log(customer)
      this.customer  = customer
      this.filteredCustomers = [...this.customer];
      if(  Object.keys(this.setData).length != 0){
      localStorage.setItem('cusId', this.setData['OrderDetails.CusDetails.id'])
      localStorage.setItem('driverId',this.setData.driverId)
      this.selectCustomer =     this.setData['OrderDetails.CusDetails.cusName']
      this.invoice.customerName =  this.selectCustomer
       this.invoice.address  = ""+this.setData['OrderDetails.CusDetails.address_1']+","+this.setData['OrderDetails.CusDetails.city']+"-"+this.setData['OrderDetails.CusDetails.pincode']+""
    this.invoice.email = this.setData['OrderDetails.CusDetails.email']
      this.invoice.contactNo =  this.setData['OrderDetails.CusDetails.phoneNo']

      this.setData['OrderDetails.CusDetails.cusType']

      this.selectCustomerData['CusDetails.address_1'] =  this.setData['OrderDetails.CusDetails.address_1']
      this.selectCustomerData['CusDetails.city'] =  this.setData['OrderDetails.CusDetails.city']
      this.selectCustomerData['CusDetails.phoneNo'] =  this.setData['OrderDetails.CusDetails.phoneNo']
      this.getProductlistApi(  this.setData['OrderDetails.CusDetails.cusType'])
      this.getProductlistApi2(  this.setData['OrderDetails.CusDetails.cusType'])
      console.log( this.setData['OrderDetails.CusDetails.cusType'])

      localStorage.setItem('orderId',this.setData.orderId)

      this._api.getReturnProductListSummary({orderId:this.setData.orderId}).subscribe(res => {
        console.log(res)
        if(res.status == 200){
  
          this.productlistReturn = res.data
     
      
  
        }
      })
      }
      }
    })
  }

  getProductlistApi(param){
    console.log(this.fieldTitle, param)
    let data
    if(this.fieldTitle != 'New Order'){
       data ={} 
    }else {
       data ={type : param} 
    }
    console.log(data)
    this.getProductlistApi2(param)
    this._api.getProducts(data).subscribe(res => {
      console.log(res)
      if(res.status == 200){

        let passData =  res.data
        let product
        if(this.fieldTitle != 'New Order'){  
             
          let UniqueProducts = this.getUniqueProducts(passData, 'productName');
          let filteredProducts = UniqueProducts.filter(product => product.productCategory === param);
          product = filteredProducts 
      
        } else{
          product = passData 
        }

      
       console.log(product)
       product.forEach((element:any, index) => {
        element.index = index  +1       
        element.qty = 0;
        element.pId = element.id
        
      });

      this.product = product

      this.filteredProducts = [...this.product];

      console.log(this.product)
     // this.productfull = product
      if(this.setData != undefined){
      if(  Object.keys(this.setData).length != 0){

        this.getAnswerProduct(this.setData.orderId)
      // this.product.forEach(element => {
      //   if(element.productName ==  this.setData['ProductDetails.productName'] ){
      //     element.qty =  this.setData.qty
      //   }
      // });
    }
    }
      //  console.log(data)
       
      }else{
        this.product = [];
      }
    })
  }



  getUniqueProducts(products: any[], propertyName: string): any[] {
    const uniqueProducts = [];
    const seen = new Set();

    for (const product of products) {
      const value = product[propertyName];
      if (!seen.has(value)) {
        seen.add(value);
        uniqueProducts.push(product);
      }
    }

    return uniqueProducts;
  }

  getProductlistApi2(param){
    let data ={type : param} 
    this._api.getProducts(data).subscribe(res => {
      console.log(res)
      if(res.status == 200){

       let passData =  res.data
       let product = passData 
 
      this.productfull = product


      
      //  console.log(data)
       
      }else{
 
      }
    })
  }
  checkType(data){
    console.log(data)
   this.selectCustomerData = data
     let productType = data['CusDetails.cusType']
     console.log(productType)
     this.  getProductlistApi(productType)

  }
  cancel(){

  }

  save(){

    console.log(this.selectCustomer)
 let mixProd= this.product.filter(arr=>{return arr.qty != 0}) 
   let product = mixProd.filter(arr=>{return arr.productName !=  "Mixed Gas"}) 
   
    console.log( product,this.mixedGas)


    if(this.setData != undefined){

   
      if(  Object.keys(this.setData).length != 0){
    product.forEach(element => {
      element.productSpec =  this. setData.productSpec
     
    });
  }
}
  

    const buttonsConfig: NbWindowControlButtonsConfig = {
      minimize: this.minimize,
      maximize: this.maximize,
      fullScreen: this.fullScreen,
      close: this.close,
    };
    let config= {
      hasBackdrop: true,
      width: '500px',
      height: '300px',
    }
  

    let results = [ ...this.mixedGas, ...product];

    if(results.length>0){

    

    let passData = {name:this.selectCustomer,product:results,customerData:this.selectCustomerData}

    const windowRef: NbWindowRef =  this.windowService.open(OrderSummaryFormComponent, { title: ` Order Summary (`+this.selectCustomer+`)`,  context:passData,buttons: buttonsConfig , });
   


      // Subscribe to the afterClosed event
      windowRef.onClose.subscribe((data) => {
        // Handle the window closure
        console.log(data);
        if(data == 1){
          this.showToast('success', 'Data Saved Successfully', 'New Order Placed..!');
         // this.getuserlistApi();
         setTimeout(() => {
          this.router.navigate(['../'], { relativeTo: this.route });
         }, 500);
           console.log('Window closed 123');
        }else if(data == 0){
       this.showToast('warning', 'Somthing is Wrong...!', 'Order Placed Failed..!');
        }
      });
    }else{
      this.showToast('warning', 'Please Fill Request Fields...!', '');
    }
  }

  // onProductSelect(event: any,prod:any) {
  //   if(prod != 'Mixed Gas')
  //   {
  //   // this.selectedProductId = event;
  //   this.product = this.product.filter((item) => item.id !== event);
  //   }
  // }


  onProductSelect(selectedProductId: number) {
    // Find the selected product index
    const selectedIndex = this.product.findIndex(product => product.id === selectedProductId);

    if (selectedIndex !== -1) {
      // Remove the selected product from the array
      this.product.splice(selectedIndex, 1);
    }
  }

  saveNew(){
    let data = { 'id' : this.delArr}
    this._api.delOrder(data).subscribe(res => { console.log( "success");
    })

    console.log(this.selectCustomer,this.inputFieldGroups, this.product)

    this.inputFieldGroups.forEach((element:any) => {
      
      // delete element.isNew;
    this.product.forEach(e => {
      
  
if(e.id === element.id){
  element.name = e.productName


}
});

});
console.log( this.inputFieldGroups )
this.invoice.products =[];
// this.inputFieldGroups.forEach((res:any) => {
      
  
//   res.name = res.name
// res.qty = res.qty
// res.price = this.setData['OrderDetails.CusDetails.cusType']
// this.invoice.additionalDetails = 'https://vnms.in/services/'

//  this.invoice.products.push(res)




// })
 
 let mixProd= this.inputFieldGroups.filter((arr:any)=>{return arr.qty != 0}) 
 

//     if(this.setData != undefined){

   
//       if(  Object.keys(this.setData).length != 0){
//     product.forEach(element => {
//       element.productSpec =  this. setData.productSpec
     
//     });
//   }
// }
// let mixedProductGas = this.inputFieldGroups.filter((arr:any)=>{return arr.name == 'Mixed Gas'}) 
// console.log(mixedProductGas)

const filteredItems = this.inputFieldGroups.filter(item => item.name === 'Mixed Gas' && item.productSpec === '');
console.log(filteredItems)
  if (filteredItems.length > 0) {
    this.showToast('warning', 'Please Fill Mixed Gas Fields...!', '');
    return;
  } else{

    const buttonsConfig: NbWindowControlButtonsConfig = {
      minimize: this.minimize,
      maximize: this.maximize,
      fullScreen: this.fullScreen,
      close: this.close,
    };
    let config= {
      hasBackdrop: true,
      width: '500px',
      height: '300px',
    }
  

    let results = [ ...this.mixedGas, ...mixProd];
    console.log(results)

    const filteredItems = results.filter(item => !item.hasOwnProperty('name'));

    console.log(filteredItems)
     

    if(results.length>0 && filteredItems.length == 0){

    

    let passData = {name:this.selectCustomer,product:results,customerData:this.selectCustomerData}

    const windowRef: NbWindowRef =  this.windowService.open(OrderSummaryFormComponent, { title: ` Order Summary (`+this.selectCustomer+`)`,  context:passData,buttons: buttonsConfig , });
   


      // Subscribe to the afterClosed event
      windowRef.onClose.subscribe((data) => {
        // Handle the window closure
        console.log(data);
        if(data == 1){
          this.showToast('success', 'Data Saved Successfully', 'New Order Placed..!');
         // this.getuserlistApi();
         setTimeout(() => {
          this.router.navigate(['../'], { relativeTo: this.route });
         }, 500);
           console.log('Window closed 123');
        }else if(data == 0){
       this.showToast('warning', 'Somthing is Wrong...!', 'Order Placed Failed..!');
        }
      });
    }else{
      this.showToast('warning', 'Please Fill Request Fields...!', '');
    }

  }

    
  }
  private showToast(type: NbComponentStatus, title: string, body: string) {
    const config = {
      status: type,
      destroyByClick: this.destroyByClick,
      duration: this.duration,
      hasIcon: this.hasIcon,
      position: this.position,
      preventDuplicates: this.preventDuplicates,
    };
    const titleContent = title ? ` ${title}` : '';

    this.index += 1;
    this.toastrService.show(
      body,
      `${titleContent}`,
      config);
  }

  back(){
    this.router.navigate(['../'], { relativeTo: this.route });
  }


  generatePDF(action = 'open') {
    console.log(this.setData)
    this.inputFieldGroups.forEach((element:any) => {      
      this.productfull.forEach(e => {
      if(e.id === element.id){
         element.name = e.productName +"-("+e.skuId+")"
      }
      });
    });
    console.log( this.inputFieldGroups )
    this.invoice.products =[];
    this.inputFieldGroups.forEach((res:any) => {
      res.name = res.name
      res.qty = parseInt(res.qty)
      res.price = this.setData['OrderDetails.CusDetails.cusType']
      this.invoice.additionalDetails = 'https://vnms.in/services/'
      this.invoice.products.push(res) 
    })
    this.invoice.products = this.invoice.products.filter(arr=>{return arr.qty != 0}) 
    let docDefinition = {
      content: [
        {
          image: 'data:image/png;base64,[encoded data, 84716 characters]', // Path to your logo image
          width: 100,
          alignment: 'center',
          margin: [0, 10] // Adjust the margins as needed
        },
        // {
        //   text: 'VNMS',
        //   fontSize: 16,
        //   alignment: 'center',
        //   color: '#047886'
        // },
        // {
        //   text: 'INVOICE',
        //   fontSize: 20,
        //   bold: true,
        //   alignment: 'center',
        //   decoration: 'underline',
        //   color: 'skyblue'
        // },
        {
          text: 'Customer Details',
          style: 'sectionHeader'
        },
        {
          columns: [
            [
              {
                text: this.invoice.customerName,
                bold:true
              },
              { text: this.invoice.address },
              { text: this.invoice.email },
              { text: this.invoice.contactNo }
            ],
            [
              { 
                text: `SALES ORDER`,
                alignment: 'right'
              },
              {
                text: `Date: ${new Date(this.setData.createdAt).toLocaleDateString('en-GB')}, ${new Date(this.setData.createdAt).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true })}`,
                alignment: 'right'
              },
              { 
                text: `ORDER ID : ${this.setData.orderId}`,
                alignment: 'right'
              }
            ]
          ]
        },
        {
          text: 'Order Details',
          style: 'sectionHeader'
        },
        {
          table: {
            headerRows: 1,
            widths: ['*', 'auto',  'auto'],
            body: [
              [
                { text: 'Product', color: 'white', fillColor: 'black' },
                { text: 'Type', color: 'white', fillColor: 'black' },
                { text: 'Quantity', color: 'white', fillColor: 'black' }
              ],
              ...this.invoice.products.map((p) => [
                p.name,
                p.price,
                
                (  p.qty) ,
              ]),
              [{text: 'Total Qty', colSpan: 2}, {},    this.invoice.products .reduce((sum, p) => sum + p.qty, 0)]
             
            ]
          }
        },
        // {
        //   text: 'Additional Details',
        //   style: 'sectionHeader'
        // },
        {
            text: '',
            margin: [0, 0 ,0, 15]          
        },
        {
          columns: [
            // [{ qr: `${this.invoice.customerName}`, fit: '50' }],
            // [{ text: 'Signature', alignment: 'right', italics: true}],
          ]
        },
        {
          text: 'Terms and Conditions',
          style: 'sectionHeader'
        },
        {
            ul: [
              'Order once placed cannot be changed . Please contact VNMS for any queries.',
              'Delivery of the product will be subject to the manufacturer terms and conditions.',
              'This is a system generated sales order.',
            ],
        }
      ],
      styles: {
        sectionHeader: {
          bold: true,
          decoration: 'underline',
          fontSize: 14,
          margin: [0, 15,0, 15]          
        }
      }
    };

    if(action==='download'){
      console.log(this.selectCustomer , this.setData.orderId)
      let name= this.selectCustomer+"-"+this.setData.orderId
      pdfMake.createPdf(docDefinition).download(name);
      
    }else if(action === 'print'){
      pdfMake.createPdf(docDefinition).print();      
    }else{
      pdfMake.createPdf(docDefinition).open();      
    }

  }

  getAnswerProduct(orderId){

            console.log(orderId)

            

      let param={orderId:orderId}
      this._api.getProductList(param).subscribe(res => {
          
      if(res.status == 200){

        let result = res.data

        this.ResultDisplay = result
        console.log(result)
          this.inputFieldGroups =[];

        // setTimeout(() => {
          console.log('gwm');
          console.log(result);

        result.forEach(element => { 

          this.inputFieldGroups.push({id:parseInt(element.productId ) , qty: element.qty, productSpec: element.productSpec , primaryId:element.id ,
                                    productName :element.productName });
          

        })
        // }, 1000);
        console.log(  this.inputFieldGroups);

        result.forEach(element => {
          console.log(element)
          if(element.ProductDetails.length>0){

          
          // if(element.ProductDetails[0].productName  =="Mixed Gas"){
          //   console.log("hiiii")
          //   element.name = element.ProductDetails[0].productName 
          //   element.qty = parseInt(element.qty)
          //   element.price = this.setData['OrderDetails.CusDetails.cusType']
          //   this.invoice.products.push(element)
          // }
}
  
    
});
// this.product.forEach(element => {

//   delete element.id

// })

this.product.forEach(element => {
  result.forEach(e => {
    console.log(e,element)
    if( e.ProductDetails.length>0){
      if(element.productName ==  e.ProductDetails[0].productName ){
        //id: 110
        element.productId=  element.id
       // element.id =  e.id
        element.qty =  parseInt(e.qty)
      } 
    }

});

});
console.log(this.product)
      }
      const uniqueArray = this.invoice.products.filter((obj:any, index, self) =>
  index === self.findIndex((o:any) => o.id === obj.id)
);
//this.invoice.products = uniqueArray
      console.log(this.product,this.invoice.products)
    })

    this.product.forEach(res => {
      
  
      res.name = res.productName
 res.qty = res.qty
 res.price = this.setData['OrderDetails.CusDetails.cusType']
 this.invoice.additionalDetails = 'https://vnms.in/services/'
 
 // this.invoice.products.push(res)
 

 
 
})
console.log(this.product,this.invoice.products)
  }


edit(){

  localStorage.setItem('viewOrder','0')
  let result = localStorage.getItem('viewOrder')
  if(result == '1'){
    this.fieldTitle = 'View Order'
  }else{
    this.fieldTitle = 'Edit Order'
    this._api.orderDetails.next(    this.setData)
    
  }
  console.log(this.fieldTitle)
}

cancelData(){
  this.router.navigate(['../'], { relativeTo: this.route });
  // localStorage.setItem('viewOrder','1')
  // let result = localStorage.getItem('viewOrder')
  // if(result == '1'){
  //   this.fieldTitle = 'View Order'
  //   this._api.orderDetails.next(    this.setData)
  // }else{
  //   this.fieldTitle = 'Edit Order'
  // }
  // console.log(this.fieldTitle)
}

getDriverlistApi(){
  let param ={}
  this._api.getusers(param).subscribe(res => {
    console.log(res)
    if(res.status == 200){

     let passData =  res.data
     let driver = passData.filter(arr=>{return arr.role == 'DRIVER'}) 
     driver.sort((a: any, b: any) => {
      return b.id - a.id;
    });
     driver.forEach((element:any, index) => {
      element.index = index       +1  
      
    });



    this.drivers = driver
    this.filteredDrivers = [...this.drivers];
    if(this.setData != undefined){
      if(  Object.keys(this.setData).length != 0){
    this.selectDriver = parseInt(this.setData.driverId)
    console.log(  this.drivers)
      }}
    }
  })
}

     // Filter customers based on search input
     filterDrivers() {
      if (this.searchDriverQuery.trim() === '') {
        this.filteredDrivers = [...this.drivers];
      } else {
        this.filteredDrivers = this.drivers.filter(user =>
          user.userName?.toLowerCase().includes(this.searchDriverQuery.toLowerCase())
        );
      }
    }


onSelectChange(newValue: string) {
  // Handle the selected value change here
  this.selectDriver = []
  console.log(newValue);
  this.dropdown_data = newValue;
  if(newValue == 'Out For Delivery'){
  this.hiddenBtn = true;
  }
  else{
    this.hiddenBtn = false;
  }
}

onSelectChange1(newValue: string) {
  // Handle the selected value change here
  console.log(newValue);
  if(!newValue){
  this.hiddenBtn = true;
  }
  else{
    this.hiddenBtn = false;
  }
}



notify(id,ordId,cusName){
  let obj = { "id" : id , "ordId" : ordId , 'cusName' : cusName }
  this._api.Notification(obj).subscribe(res => { console.log( "success");
  })
  }

onSubmit2(){
 

 
  console.log(  this.selectDriver,this.selectStatus)
  let tmp=[];
 

    
    if(this.selectStatus == "Out For Delivery"){
      tmp.push({orderId:this.setData.orderId  , driverId:this.selectDriver, status:this.selectStatus })
    }else if(this.selectStatus == "Cancelled"){
      tmp.push({orderId:this.setData.orderId  , reason:this.CancelReason, status:this.selectStatus })
    }else{
      tmp.push({orderId:this.setData.orderId  ,  status:this.selectStatus })
    }

    if(this.selectStatus == "Delivered"){

     this.onCreateConfirm()

    }else{

      let  param ={driver:tmp,orderId:this.setData.orderId}
  
   
    
   
  
 
     
     this._api.CreateOrder (param).subscribe(res => {
      
       if (res.status == 200) {
        console.log(res)
        this.showToast('success', 'Updated Successfully', '');
        
        
        if(this.selectStatus == "Out For Delivery"){
           this.notify(this.selectDriver , this.setData.orderId , this.selectCustomer );
        }
        this.selectStatus =[];
       }else{
        this.showToast('warning', 'Somthing is Wrong...!', '');
       }
     })

    }
  
    
 

//       let  param ={driver:tmp,orderId:this.setData.orderId}
  
   
    
   
  
 
     
//      this._api.CreateOrder (param).subscribe(res => {
//        if (res.status == 200) {
//  console.log(res)
//  this.showToast('success', 'Data Changed Successfully', '');
 
//  this.selectStatus =[];
//        }else{
//         this.showToast('warning', 'Somthing is Wrong...!', '');
//        }
//      })
  
}


onDropdownChange(event: any) {
  // Find the selected product in the array and get its name
  const selectedProduct = this.checkProductArray().find(product => product.id === event);
  if (selectedProduct) {
    this.selectedProductName = selectedProduct.productName;
  } else {
    this.selectedProductName = ''; // If no product found, clear the selected product name
  }
  console.log(this.selectedProductName);
 
  this.inputFieldGroups.forEach(element => {
    if(element.id == event){
        element.productName = this.selectedProductName;
    }
  });

}
// checkProductArray() {
//   // console.log(this.inputFieldGroups)
//     const hasNullId = this.inputFieldGroups.some((group) => group.id === null);
//   // console.log(hasNullId)
//   if (!hasNullId) {
//     // There's an object with id = null in the inputFieldGroups array
//     // console.log('There is an object with id = null');
//     return this.product;
//   } else {
//     // There is no object with id = null in the inputFieldGroups array
//     // Filter products based on the condition (productName !== 'Mixed Gas' in inputFieldGroups)
//     const filteredProducts = this.product.filter((product) => {
//       const isSelected = this.inputFieldGroups.some((group) => group.id === product.id );
//       return product.productName === 'Mixed Gas' || !isSelected;
//     });

//     return filteredProducts;
//   }
 

// }

checkProductArray() {
  const hasNullId = this.inputFieldGroups.some((group) => group.id === null);
  
  let filteredProducts;
  if (!hasNullId) {
    filteredProducts = [...this.product]; 
  } else {
    filteredProducts = this.product.filter((product) => {
      const isSelected = this.inputFieldGroups.some((group) => group.id === product.id);
      return product.productName === 'Mixed Gas' || !isSelected;
    });
  }

  // Apply search filtering
  if (this.searchProductQuery.trim() !== '') {
    return filteredProducts.filter(product =>
      product.productName?.toLowerCase().includes(this.searchProductQuery.toLowerCase()) ||
      product.skuId?.toString().toLowerCase().includes(this.searchProductQuery.toLowerCase())
    );
  }

  return filteredProducts;
}

filterProduct() {
  if (this.searchProductQuery.trim() === '') {
    this.filteredProducts = this.checkProductArray();
  } else {
    this.filteredProducts = this.checkProductArray().filter(product =>
      product.productName?.toLowerCase().includes(this.searchProductQuery.toLowerCase()) ||
      product.skuId?.toString().toLowerCase().includes(this.searchProductQuery.toLowerCase())
    );
  }
}


addInputFieldGroup() {
  if(this.fieldTitle != 'New Order'){    
    console.log(this.product)
    let activeProductList = this.product.filter(item => item.isActive == '1')
    console.log(activeProductList)
    this.product = activeProductList
  }
  this.searchProductQuery = ''
  this.filteredProducts = this.product
  // this.inputFieldGroups.push({id:null, qty: '1', productSpec: '' });
   // Add a new input field group to the array
  const newGroup = { id: null, qty: 1, productSpec: '', isNew: true , productName : '' };
  this.inputFieldGroups.push(newGroup);
  console.log(this.inputFieldGroups)
  //this.childButtonEvent.emit( this.inputFieldGroups);
}

isReadOnly(param,index: number) {
  console.log(this.inputFieldGroups)
  console.log(param,index)
  // You can add your condition here to determine if the option should be readonly.
  // For example, if you want to make options at index 2 and 3 readonly:
  // return index === 2 || index === 3;
}

removeInputFieldGroup(index: number) {
  console.log(  this.inputFieldGroups[index].primaryId)
  this.delArr.push(this.inputFieldGroups[index].primaryId)
  this.inputFieldGroups.splice(index, 1); // Remove the input field group at the specified index
  //this.childButtonEvent.emit( this.inputFieldGroups);
}


onCreateConfirm() {   
  let data:any = {details:this.setData['OrderDetails.CusDetails.cusType'],action:'Add',title:'Add Return'}
  const dialogRef = this.dialogService.open(AddOrderComponent, {
    hasBackdrop: true,
    dialogClass: 'custom-dialog-class', // Add your custom CSS class here
    context: data
  });

  dialogRef.onClose.subscribe((result) => {
   // Execute custom logic when the dialog is closed
   console.log(result);       
   if(result == 1){
    console.log(  this.selectDriver,this.selectStatus)
    let tmp=[];
   
  
      
      if(this.selectStatus == "Out For Delivery"){
        tmp.push({orderId:this.setData.orderId  , driverId:this.selectDriver, status:this.selectStatus })
      }else if(this.selectStatus == "Cancelled"){
        tmp.push({orderId:this.setData.orderId  , reason:this.CancelReason, status:this.selectStatus })
      }else{
        tmp.push({orderId:this.setData.orderId  ,  status:this.selectStatus })
      }

      let  param ={driver:tmp,orderId:this.setData.orderId}
  
   
    
   
  
 
     
      this._api.CreateOrder (param).subscribe(res => {
        if (res.status == 200) {
  console.log(res)
  this.showToast('success', 'Updated Successfully', '');
  
  this.selectStatus =[];
        }else{
         this.showToast('warning', 'Somthing is Wrong...!', '');
        }
      })
   // this.showToast('success', 'Data Saved Successfully', '');
   //  this.toastrService.success('Entity Added Successfully','Entity');
      console.log('Window closed 123');
   }else if(result == 0){

    this.showToast('warning', 'Somthing is Wrong...!', '');
    // this.toastrService.success('Somthing is Wrong...!', 'Add Entity Failed..!');
   }
  });
   
}

// getProduct(param){
//   console.log(param)
//   if(param == 'Others'){
//    this.mixedBTN = true
//   }else{
//     this.mixedBTN = false
//   }
// }

// isProductSpecValid(): boolean {
//   console.log(this.inputFieldGroups )
//   return !!this.inputFieldGroups.find((fieldGroup) => fieldGroup.productSpec);
// }


}
