import { Component, OnInit } from '@angular/core';
import { PageapiService } from '../../pageapi.service';
import { NbComponentStatus, 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';

@Component({
  selector: 'ngx-order-form',
  templateUrl: './order-form.component.html',
  styleUrls: ['./order-form.component.scss']
})
export class OrderFormComponent implements OnInit {
  customer:any =[];
  product:any =[];
  mixedGas: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=[]
  index = 1;
  destroyByClick = true;
  duration = 2000;
  hasIcon = true;
  setData:any =[];
  position: NbGlobalPosition = NbGlobalPhysicalPosition.TOP_RIGHT;
  preventDuplicates = false;
  status: NbComponentStatus = 'primary';
  selectCustomerData :any =[];
  constructor(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. setData =   res.data


      }
  
    })

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

   
    if(  Object.keys(this.setData).length != 0){
      this.fieldTitle = 'Edit Order'
    }
  }
    this.getuserlistApi()
   
  }


  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'}) 
       customer.forEach((element:any, index) => {
        element.index = index     +1    
        
      });
      console.log(customer)
      this.customer  = customer
      if(  Object.keys(this.setData).length != 0){
      this.selectCustomer =     this.setData['OrderDetails.CusDetails.cusName']
      this.setData['OrderDetails.CusDetails.cusType']
      this.getProductlistApi(  this.setData['OrderDetails.CusDetails.cusType'])
      //  console.log(data)
      }
      }
    })
  }

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

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

      this.product = product
      if(this.setData != undefined){
      if(  Object.keys(this.setData).length != 0){

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

  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 product= this.product.filter(arr=>{return arr.qty != 0}) 
   
    console.log( product)
    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...!', '');
    }
  }
  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 });
  }
}
