import { AfterViewInit, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { MatDialog, MatTableDataSource } from '@angular/material';
import { ApiService } from '../../../../../app/core/api/api.service';
import { ModalFiltrosServiciosComponent } from './modal-filtros-servicios/modal-filtros-servicios.component';
import { ServiciosModel } from './servicios.model';

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

	titulo = 'Reporte de servicios';

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

	//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;

	totalServicios = 0;
	totalCosto = 0.00;

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

	ngOnInit() {}

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

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

			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/' + res.nombre_archivo;
					}
				}else{
					this.totalServicios = 0;
					this.totalCosto = 0.00;
					this.dataSource.data = [];

					this.dataSource.data = res.data;
					this.total = res.total;
					this.totalServicios = res.total_servicios;
					this.totalCosto = res.total_costo;
				}

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

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

		dialogRef.afterClosed().subscribe(data => {
			if(data){
				this.showMessageSetFilters = false;
				this.data = data;
				this.dataSource.data = [];
				this.getInformation();
			}
		});
	}

	ngAfterViewInit() {
		this.filters();
	}

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