import {AfterViewInit, 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 {Clientes} from '../clientes.model';

@Component({
  selector: 'kt-clientes-list',
  templateUrl: './clientes-list.component.html',
  styleUrls: ['./clientes-list.component.scss']
})
export class ClientesListComponent implements OnInit {

  //Search
  lastLength = 0;
  typingTimer;
  typingInterval = 700;
  deleted_at = '0';

  displayedColumns: string[] = ['denominacion', 'email', 'sucursal', 'asesor', 'created_at', 'actions'];
  dataSourceClientes: MatTableDataSource<Clientes>;

  //Loadings
  isLoading = true;
  showMessageWait = true;

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

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

  ngOnInit() {
  }

toggle(event){
	this.deleted_at = event.checked == false ? '0' : '1';
	this.getClientes();
}

  getClientes(){
    this.isLoading = true;
    this.api.clientes.index(this.page, this.searchText, this.sortBy, this.order, this.perPage, null, this.deleted_at).subscribe(res =>{
      this.isLoading = false;
      this.showMessageWait = false;
      this.dataSourceClientes.data = res.data;
      this.total = res.total;
      this.ref.detectChanges();
    }, ()=>{
      this.isLoading = false;
      this.showMessageWait = false;
    })
  }

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

    this.lastLength = filterValue.length;
  }

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

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

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

  editCliente(id) {
    this.router.navigate(['../clientes/edit/', id], {relativeTo: this.activatedRoute})
  }

  deleteCliente(cliente) {
    let title = (cliente.deleted_at == null) ? 'Eliminar cliente' : 'Activar cliente';
    let name = (cliente.denominacion) ? cliente.denominacion : '';
    let description = (cliente.deleted_at == null) ? '¿Está seguro de eliminar el cliente ' + name + '?' : '¿Está seguro de activar el cliente ' + name + '?';
    let waitDesciption = (cliente.deleted_at == null) ? 'Eliminando cliente...' : 'Activando cliente...';
    let deleteMessage = (cliente.deleted_at == null) ? `El cliente ha sido eliminado con éxito` : `El cliente ha sido activado con éxito`;
    let errorMessage = (cliente.deleted_at == null) ? `El cliente no se ha podido eliminar` : `El cliente no se ha podido activar` ;
  	let btnText = (!cliente.deleted_at) ? 'Eliminar' : 'Activar';

    let dialogRef = this.layoutUtilsService.deleteElement(title, description, waitDesciption, btnText);
    dialogRef.afterClosed().subscribe(res => {
      if (!res) {
        return;
      }
	  let reactivate = (cliente.deleted_at != null)

      this.api.clientes.delete(cliente.id, reactivate).subscribe(() => {
        this.getClientes();
        this.layoutUtilsService.showActionNotification(deleteMessage, MessageType.Delete);
      }, () => {
        this.layoutUtilsService.showActionNotification(errorMessage, MessageType.Delete);
      });
    });

  }

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

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

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

}
