import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { MatDialog, MatTableDataSource } from '@angular/material';
import { ApiService } from '../../../../core/api/api.service';
import { ModalFiltrosServiciosClienteComponent } from './modal-filtros-servicios-cliente/modal-filtros-servicios-cliente.component';
import { ServiciosClienteModel } from './servicios-cliente.model';

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

	titulo = 'Reporte de servicios por cliente';

	displayedColumns: string[] = ['numero_solicitud', 'fecha_servicio', 'hora_servicio', 'servicio', 'costo', 'tipo_servicio', 'estatus_servicio', 'colonia_cliente', 'nombre_asesor', 'nombre_auxiliar', 'vehiculo', 'duracion_servicio', 'litraje'];
	dataSource: MatTableDataSource<ServiciosClienteModel>;

	//Loadings
	isLoading = false;
	showMessageWait = false;
	showMessageSetFilters = true;

	//Paginator, Searcher
	page = '1';
	perPage = '10';
	total = 0;
	sortBy = 'denominacion';
	order = 'asc';
	pages = [10, 25, 50, 100];
	deleted = '0';

	data = null;

	constructor(private api: ApiService, private ref: ChangeDetectorRef, private dialog: MatDialog) {
		this.dataSource = new MatTableDataSource<ServiciosClienteModel>();
	}

	ngOnInit() {
	}

	getInformation(excel = false){
		if(this.data){
			this.isLoading = true;
			this.showMessageWait = true;

			let url = excel? 'servicios/clientes/excel' : 'servicios/clientes';

			this.api.reportesService.getInformation(url, this.data, this.page, this.perPage, this.deleted).subscribe(res => {

				this.isLoading = false;
				this.showMessageWait = false;

				if(excel){
					if (res.nombre_archivo) {
						document.location.href = this.api.reportesService.baseUrlStorage + 'servicios_clientes/' + res.nombre_archivo;
					}
				}else{
					this.dataSource.data = [];

					this.dataSource.data = res.data;
					this.total = res.total;
				}

				this.ref.detectChanges();
			}, () => {
				this.isLoading = false;
				this.showMessageWait = false;
			});
		}
	}

	filters(){
		const dialogRef = this.dialog.open(ModalFiltrosServiciosClienteComponent, {
			data: this.data,
			disableClose: true
		});

		dialogRef.afterClosed().subscribe(data => {
			if(data){
				this.showMessageSetFilters = false;
				this.data = data;
				this.dataSource.data = [];
				this.titulo = 'Reporte de servicios por cliente (' + data.user + ')';
				this.getInformation();
			}
		});
	}

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

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

	ngAfterViewInit() {
		this.filters();
	}
}
