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


import {
  NbComponentStatus,
  NbGlobalLogicalPosition,
  NbGlobalPhysicalPosition,
  NbGlobalPosition,
 
  NbToastrConfig,
} from '@nebular/theme';
import { CustomerFormComponent } from './customer-form/customer-form.component';

@Component({
  selector: 'ngx-customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.scss']
})
export class CustomerComponent  {
  customer:any =[];
  settings = {
    actions: {
      
      position: 'right', // left|right
    },
    mode: 'external',
    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',
      },
      userName: {
        title: 'Name',
        type: 'string',
      },
      email: {
        title: 'E-mail',
        type: 'string',
      },
      mobileNo: {
        title: 'Mobile No',
        type: 'string',
      },
      role: {
        title: 'Role',
        type: 'string',
      },
      'CusDetails.address_1': {
        title: 'Address',
        type: 'string',
      },
 
      'CusDetails.state': {
        title: 'State',
        type: 'string',
      },
      'CusDetails.city': {
        title: 'City',
        type: 'string',
      },
    
     
     
    },
  };
  searchTerm:any=[];filteredItems:any=[];
  source: LocalDataSource = new LocalDataSource();
  minimize = false;
  maximize = false;
  fullScreen = true;
  close = true;
  formData:any=[]
  index = 1;
  destroyByClick = true;
  duration = 2000;
  hasIcon = true;
  position: NbGlobalPosition = NbGlobalPhysicalPosition.TOP_RIGHT;
  preventDuplicates = false;
  status: NbComponentStatus = 'primary';
  constructor(private dialogService: NbDialogService,private toastrService: NbToastrService,private service: SmartTableData,public _api:PageapiService,private windowService: NbWindowService) {
    const data = this.service.getData();
  
    this.getuserlistApi()

   
    
  }

  onCreateConfirm() {   
    let data:any = {details:'',action:'Add',title:'Add Customer'}
    const dialogRef = this.dialogService.open(CustomerFormComponent, {
      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){
      // this.getEntityDetails()
      this.getuserlistApi();
      this.showToast('success', 'Data Saved Successfully', 'Add Customer Data Completed..!');
     //  this.toastrService.success('Entity Added Successfully','Entity');
        console.log('Window closed 123');
     }else if(result == 0){

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

  onDeleteConfirm(event): void {
    console.log(event)
    let passData = event
   // if (window.confirm('Are you sure you want to delete?')) {
      //event.confirm.resolve();

   

      let deletedata  = {'isActive':event.isActive,'id':passData.id}
  
      this._api.addUserFormDetails (deletedata).subscribe(res => {
        if (res.status == 200) {
  console.log(res)
  this.getuserlistApi();
  if(event.isActive == 1){
    this.showToast('success', 'Active Customer Data Completed..!', '');
  }else{
    this.showToast('success', 'Inactive Customer Data Completed..!', '');
  }

  //this.showToast('success', 'Data Removed Successfully', 'Removed User Data Completed..!');
        }else{
          this.showToast('warning', 'Somthing is Wrong...!', 'Edit User Data Failed..!');
        }
      })

    // } else {
    //   event.confirm.reject();
    // }
  }
  // onCreateConfirm() {
  //   console.log("Create Event In Console")
  //  // console.log(event);
  //   const buttonsConfig: NbWindowControlButtonsConfig = {
  //     minimize: this.minimize,
  //     maximize: this.maximize,
  //     fullScreen: this.fullScreen,
  //     close: this.close,
  //   };

  //   const windowOptions = {
  //     title: 'New Customer',
  //     hasBackdrop: true,
  //     minimize: this.minimize,
  //     maximize: this.maximize,
  //     fullScreen: this.fullScreen,
  //     close: this.close,
  //     closeOnBackdropClick: false,
  //     closeOnEsc: false,
  //     buttonsConfig:buttonsConfig,
  //     dimensions: {
  //       width: '2500px',
  //       height: '300px',
  //     },
  //     /* other window options */
  //   };

  //   const windowRef: NbWindowRef =  this.windowService.open(CustomerFormComponent, { title: `Add Customer`,  
  //    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', 'Add Customer Data Completed..!');
  //         this.getuserlistApi();
  //          console.log('Window closed 123');
  //       }else if(data == 0){
  //         this.showToast('warning', 'Somthing is Wrong...!', 'Add Customer Data Failed..!');
  //       }
  //     });
  // }

  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,
    // };
    // const windowRef: NbWindowRef =  this.windowService.open(CustomerFormComponent, { title: `Edit Customer`, context: event
    // , 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', 'Edit Customer Data Completed..!');
    //       this.getuserlistApi();
    //        console.log('Window closed 123');
    //     }else if(data == 0){
    //       this.showToast('warning', 'Somthing is Wrong...!', 'Edit Customer Data Failed..!');
    //     }
       
      
    //   });

    let data:any = {details:event,action:'Edit',title:'Edit Customer'}
    const dialogRef = this.dialogService.open(CustomerFormComponent, {
      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){
      // this.getEntityDetails()  
      this.getuserlistApi();
      this.showToast('success', 'Data Changed Successfully', 'Edit Customer Data Completed..!');
     //  this.toastrService.success('Entity Added Successfully','Entity');
        console.log('Window closed 123');
     }else if(result == 0){

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


  getuserlistApi(){
    let param ={}
    this._api.getusers(param).subscribe(res => {
      console.log(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    
        element.type =element['CusDetails.cusType']

      });
      this.customer = customer
      //  console.log(data)
        //this.source.load(customer);
      }
    })
  }


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

  
filterItems() {
 console.log(  this.searchTerm)

  if(  this.searchTerm !=''){


  this.filteredItems = this.customer.filter(item =>
    Object.values(item).some(value => {
      if (typeof value === 'string') {
        return value.toLowerCase().includes(this.searchTerm.toLowerCase());
      }
      return false;
    })
  );
  this.customer = this.filteredItems
}else{
  console.log( 'fhjsgsajdhgasksjgfcckjsdfgckjsdhfk')  

  this.getuserlistApi()
}



console.log( this.filteredItems)
}

resetPassword(data){
  console.log(data)

  this.formData= new FormData();
  if(data.hasOwnProperty('id')){
    this.formData.append('id', data.id);
   
  }  
 
  this.formData.append('password', 'Test@123');


  this._api.addUserFormDetails (this.formData).subscribe(res => {
    if (res.status == 200) {
console.log(res)
this.showToast('success', 'Password Changed Successfully', '');

    }else{
      this.showToast('warning', 'Password Changed Failed', '');
    }
  })

 }
}
