import {ChangeDetectorRef, Component, OnInit} from '@angular/core';
import {MatTableDataSource} from '@angular/material';
import {ApiService} from '../../../../../core/api/api.service';
import {ActivatedRoute, Router} from '@angular/router';
import {LayoutUtilsService, MessageType} from '../../../../../core/_base/crud';
import {ClientesDomicilios} from '../clientes-domicilios.model';
import {Subscription} from 'rxjs';

@Component({
  selector: 'kt-clientes-domicilios-list',
  templateUrl: './clientes-domicilios-list.component.html',
  styleUrls: ['./clientes-domicilios-list.component.scss']
})
export class ClientesDomiciliosListComponent implements OnInit {
//Search
lastLength = 0;
typingTimer;
typingInterval = 700;

displayedColumns: string[] = ['nombre_sucursal', 'domicilio', 'nombre_responsable_sucursal', 'telefono', 'email', 'created_at', 'croquis', 'actions'];
dataSourceClientesDomicilios: MatTableDataSource<ClientesDomicilios>;

//Loadings
isLoading = true;
showMessageWait = true;
subscriptions: Subscription[] = [];
clienteDomicilioID = 0;

//Paginator, Searcher
searchText: string;
sortBy = 'nombre_sucursal';
order = 'asc';
page = '1';
perPage = '10';
total = 0;
pages = [10, 25, 50, 100];
titulo = 'Domicilios de Cliente:';

clienteDomiciliosID = 0;
clienteID = '';

constructor(private api: ApiService,
      private router: Router,
      private layoutUtilsService: LayoutUtilsService,
      private activatedRoute: ActivatedRoute,
      private ref: ChangeDetectorRef) {
      this.dataSourceClientesDomicilios = new MatTableDataSource<ClientesDomicilios>();
}

ngOnInit() {
  this.clienteID = this.activatedRoute.snapshot.paramMap.get('id');
}

getClientesDomicilios(){
  let routeSubscription = this.activatedRoute.params.subscribe(params => {
      this.isLoading = true;
      this.clienteDomicilioID = params.id;
      this.api.clientesDomicilios.index('/domicilios', this.page, this.searchText, this.sortBy, this.order, this.perPage, this.clienteDomicilioID).subscribe(res =>{
      this.titulo = this.titulo + ' ' + res.cliente_denominacion;
      this.isLoading = false;
      this.showMessageWait = false;
      this.dataSourceClientesDomicilios.data = res.data;
      this.total = res.total;
      this.ref.detectChanges();
    }, ()=>{
      this.isLoading = false;
      this.showMessageWait = false;
    })
  });
  this.subscriptions.push(routeSubscription);
}

//Search
filtrarBusqueda(filterValue: string) {
  if (filterValue.length != 0) {
    this.searchText = filterValue.trim().toLowerCase();
    this.getClientesDomicilios();
  } else if (this.lastLength != 0) {
    this.searchText = '';
    this.getClientesDomicilios();
  }

  this.lastLength = filterValue.length;
}

onKeyUp(ev) {
  clearTimeout(this.typingTimer);
  this.typingTimer = setTimeout(() => {
    this.filtrarBusqueda(ev.target.value)
  }, this.typingInterval);
}

onKeyDown() {
  this.showMessageWait = true;
  this.dataSourceClientesDomicilios.data = [];
  clearTimeout(this.typingTimer);
}//Fin search

editClienteDomicilio(id) {
  this.router.navigate(['../../clientes-domicilios/edit', id, this.clienteDomicilioID], {relativeTo: this.activatedRoute})
}

deleteClienteDomicilio(domicilio) {
  let title = 'Eliminar domicilio del cliente';
  let name = (domicilio.nombre_sucursal)? domicilio.nombre_sucursal : '';
  let description = '¿Está seguro de eliminar el domicilio del cliente ' + name + '?';
  let waitDesciption = 'Eliminando domicilio del cliente...';
  let deleteMessage = `El domicilio del cliente ha sido eliminado con éxito`;
  let errorMessage = `El domicilio del cliente no se ha podido eliminar`;
  let btnText = 'Eliminar';

  let dialogRef = this.layoutUtilsService.deleteElement(title, description, waitDesciption, btnText);
  dialogRef.afterClosed().subscribe(res => {
    if (!res) {
      return;
    }
    this.api.clientesDomicilios.delete('/domicilios', domicilio.id, domicilio.cliente_id).subscribe(() => {
      this.getClientesDomicilios();
      this.layoutUtilsService.showActionNotification(deleteMessage, MessageType.Delete);
    }, () => {
      this.layoutUtilsService.showActionNotification(errorMessage, MessageType.Delete);
    });
  });

}

sort(event) {
  this.order = event.direction;
  this.sortBy = event.active;
  this.getClientesDomicilios();
}

paginator(event) {
  let nextPage = event.pageIndex + 1;
  this.page = nextPage.toString();
  this.perPage = event.pageSize.toString();
  this.getClientesDomicilios();
}

ngAfterViewInit(): void {
  this.getClientesDomicilios();
}

}
