import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
 
import { LocalDataSource } from 'ng2-smart-table';
import { SmartTableData } from '../../@core/data/smart-table';
import { PageapiService } from '../pageapi.service';
import { NbToastrService, NbWindowControlButtonsConfig, NbWindowRef, NbWindowService } from '@nebular/theme';
 


import {
  NbComponentStatus,
  NbGlobalLogicalPosition,
  NbGlobalPhysicalPosition,
  NbGlobalPosition,
 
  NbToastrConfig,
} from '@nebular/theme';
import { Router } from '@angular/router';
import { CancelFormComponent } from './cancel-form/cancel-form.component';
import { AssignFormComponent } from './assign-form/assign-form.component';
import { FormControl, FormGroup, Validators } from '@angular/forms';
 
@Component({
  selector: 'ngx-order',
  templateUrl: './order.component.html',
  styleUrls: ['./order.component.scss']
})
export class OrderComponent  {

  settings:any =[];
  source: LocalDataSource = new LocalDataSource();
  minimize = false;
  maximize = false;
  fullScreen = true;
  close = true;
  formData:any=[]
  index = 1;
  destroyByClick = true;
  duration = 2000;
  selectedRows:any=[];
  hasIcon = true;
  position: NbGlobalPosition = NbGlobalPhysicalPosition.TOP_RIGHT;
  preventDuplicates = false;
  drivers:any=[];
  status: NbComponentStatus = 'primary';
  driverForm:any =[];
  constructor(private domSanitizer: DomSanitizer, private router:Router,private toastrService: NbToastrService,private service: SmartTableData,public _api:PageapiService,private windowService: NbWindowService) {
    const data = this.service.getData();

    this.settings = {
      selectMode: 'multi',
       
     actions: {
       
       position: 'right', // left|right
     },
     mode: 'external',
     userRowSelect: (selectedRows: any[]) => {
       this.handleRowSelection(selectedRows);
     },
     add: {
       addButtonContent: '<i class="nb-plus"></i>',
       createButtonContent: '<i class="nb-checkmark"></i>',
       cancelButtonContent: '<i class="nb-close"></i>',
     },
     edit: {
       editButtonContent: '<i class="nb-edit"></i>',
       saveButtonContent: '<i class="nb-checkmark"></i>',
       cancelButtonContent: '<i class="nb-close"></i>',
     },
     delete: {
       deleteButtonContent: '<i class="nb-trash"></i>',
       confirmDelete: true,
     },
     columns: {
       
       index: {
         title: 'ID',
         type: 'number',
               width:"10px"
       },
       orderId: {
         title: 'Order ID',
         type: 'string',
        
       },
       'OrderDetails.CusDetails.cusName': {
         title: 'Customer Name',
         type: 'string',
         width:"40px"
       },
       'ProductDetails.productName': {
         title: 'Product',
         type: 'string',
       
       },
       qty: {
         title: 'Qty',
         type: 'string',
         width:"10px",
         rowClass: (row) => {
          // Function to determine the row class based on the value of a specific column
          const columnName = 'qty'; // Specify the name of the desired column
          const desiredValue = 'qty'; // Specify the desired value for the row color

          if (row[columnName] === desiredValue) {
            return 'desired-value-row'; // CSS class for rows with the desired value
          } else {
            return ''; // CSS class for other rows
          }
        }
       },
       status: {
         title: 'Status',
         type: 'string',
         valuePrepareFunction: (cell, row) => {
          // Add a string value to the column

          if(cell == "Out For Delivery"){
            return  cell + " ("+ row["UserDetails.userName"]+")"; 
           
          }else{

          }
          return cell  ; // Modify this as per your requirement
        }
 
       },  
       reason: {
         title: 'Cancel Reason',
         type: 'string',
         width:"25px"
       },
      
     },
   };
 
  
    this.getorderlistApi()

    this. getDriverlistApi()

    this.driverForm = new FormGroup({
      
 
      driver: new FormControl('', [ Validators.required])
    
    });

    
  }

  onDeleteConfirm(event): void {
    console.log(event)
    let passData = event.data

    const buttonsConfig: NbWindowControlButtonsConfig = {
      minimize: this.minimize,
      maximize: this.maximize,
      fullScreen: this.fullScreen,
      close: this.close,
    };
    const windowRef: NbWindowRef =  this.windowService.open(CancelFormComponent, { title: `Cancel Product`, context: event.data
    , 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 Changed Successfully', 'Order Cancel Completed..!');
         this.getorderlistApi();
           console.log('Window closed 123');
        }else if(data == 0){
          this.showToast('warning', 'Somthing is Wrong...!', 'Order Cancel Failed..!');
        }
       
      
      });
    
  }

  getFuelColor(w){
    console.log(w)
  }
  onCreateConfirm(event) {
    console.log("Create Event In Console")
    console.log(event);
    const buttonsConfig: NbWindowControlButtonsConfig = {
      minimize: this.minimize,
      maximize: this.maximize,
      fullScreen: this.fullScreen,
      close: this.close,
    };
    let config= {
      hasBackdrop: true,
      width: '500px',
      height: '300px',
    }
    this.addOrder()
  }

  onSaveConfirm(event) {
    console.log("Edit Event In Console")
    console.log(event);

    const buttonsConfig: NbWindowControlButtonsConfig = {
      minimize: this.minimize,
      maximize: this.maximize,
      fullScreen: this.fullScreen,
      close: this.close,
    };
    console.log("add")
    this._api.orderDetails.next(event)

  
  
    this.router.navigate(['/pages/order/add']) 
  }


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

       let passData =  res.data
       passData.sort((a: any, b: any) => {
        return b.id - a.id;
      });
       passData.forEach((element:any, index) => {
        element.index = index       +1  
        
      });
      //  console.log(data)
        this.source.load(passData);
      }
    })
  }


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

  addOrder(){
    console.log("add")
    this._api.orderDetails.next(null)
    this.router.navigate(['/pages/order/add']) 
  }

  handleRowSelection(selectedRows: any[]) {
    // Get the selected row data
    const selectedData = selectedRows.map(row => row.data);
    console.log(selectedData);
  }
  onUserRowSelect(event) {
    console.log(event)
    this.selectedRows = event.selected;
}

Assign(){
  console.log(1)
  if(this.selectedRows.length>0){

 
  const buttonsConfig: NbWindowControlButtonsConfig = {
    minimize: this.minimize,
    maximize: this.maximize,
    fullScreen: this.fullScreen,
    close: this.close,
  };
  const windowRef: NbWindowRef =  this.windowService.open(AssignFormComponent, { title: `Assign Driver`, context: this.selectedRows
 
  , 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 Changed Successfully', 'Driver Assign Completed..!');
       this.getorderlistApi();
         console.log('Window closed 123');
      }else if(data == 0){
        this.showToast('warning', 'Somthing is Wrong...!', 'Driver Assign Failed..!');
      }
     
    
    });
  }else{
    this.showToast('warning', 'Somthing is Wrong...!', 'Please Select Orders..!');
  }

}


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
    //  console.log(data)
    
    }
  })
}

onSubmit(){
  if(this.selectedRows.length>0){

 
  console.log( this.selectedRows , this.driverForm.value)
  let tmp=[];
  this.selectedRows.forEach(element => {
    tmp.push({id:element.id ,driverId: this.driverForm.value.driver ,  status:'Out For Delivery' })
    
  });

 let  param ={driver:tmp}
  
   
    
   
  
 
     
     this._api.CreateOrder (param).subscribe(res => {
       if (res.status == 200) {
 console.log(res)
 this.showToast('success', 'Data Changed Successfully', 'Orders Assign Completed..!');
 this.getorderlistApi();
       }else{
        this.showToast('warning', 'Somthing is Wrong...!', 'Orders Assign Failed..!');
       }
     })
 }else{
    this.showToast('warning', 'Somthing is Wrong...!', 'Please Select Orders..!');
  }
}

}
