import {ChangeDetectorRef, Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {MatDialog, MatInput, MatTableDataSource} from '@angular/material';
import { ApiService } from '../../../../../core/api/api.service';
import { ModalEncuestaComponent } from '../modal-encuesta/modal-encuesta.component';
import { ModalSetLitrajeComponent } from '../modal-set-litraje/modal-set-litraje.component';
import { SolicitudesServicio } from '../solicitudes-servicio.model';
import moment from "moment";
import {ActivatedRoute, Router} from "@angular/router";
import {environment} from '../../../../../../environments/environment';
import {FiltrosServiciosResponseModel} from '../../models/filtros-servicios-response.model';

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

	@ViewChild('inputElement', {static: false, read: MatInput}) inputElement: MatInput;
	//Search
	lastLength = 0;
	typingTimer;
	typingInterval = 1500;
	serviciosForm: FormGroup;

	displayedColumns: string[] = ['solicitud_servicio_id', 'estatus_servicio_nombre', 'fecha_agenda', 'fecha_solicitud', 'tiempo_atencion', 'denominacion', 'clientes_colonia', 'forma_pago_nombre', 'servicio_nombre', 'tipo_servicio_nombre', 'facturado', 'vehiculo_num_economico', 'operador_apellido_paterno', 'actions'];
	dataSource: MatTableDataSource<SolicitudesServicio>;
	estatusServicios = null;
	estatusSelected = null;

	//Loadings
	isLoading = true;
	showMessageWait = true;

	//Paginator, Searcher
	searchText: string;
	sortBy = 'servicios_det.fecha_solicitud';
	order = 'asc';
	page = '1';
	perPage = 10;
	total = 0;
	pages = [10, 25, 50, 100];
	titulo = 'Solicitudes de Servicios';

	constructor(private api: ApiService,
				private ref: ChangeDetectorRef,
				private router: Router,
				private activatedRoute: ActivatedRoute,
				private dialog: MatDialog,
				private fb: FormBuilder) {
		this.dataSource = new MatTableDataSource<SolicitudesServicio>();
	}

	ngOnInit() {
		this.crearFormulario();
		this.getFiltros();
	}

	getData(fecha){

		if(fecha) this.inputElement.value = '';
		this.isLoading = true;
		this.ref.detectChanges();

		this.api.solicitudesServicioService.index2(this.page, this.searchText, this.sortBy, this.order, this.perPage + "", null, null, !fecha ? this.formatDate(this.serviciosForm.controls['date'].value) : null, (this.estatusSelected) ? this.estatusSelected : null).subscribe(res =>{
			this.isLoading = false;
			this.showMessageWait = false;
			this.dataSource.data = res.data;
			this.total = res.total;
			this.ref.detectChanges();
		}, ()=>{
			this.isLoading = false;
			this.showMessageWait = false;
		})
	}

	getFiltros(){
		this.api.solicitudesServicioService.filtrosServicios('filtros_servicios').subscribe((res: FiltrosServiciosResponseModel) => {
			this.estatusServicios = res.estatus_servicios;
		})
	};

	getInfoByEstatus(id){
		this.estatusSelected = id;
		this.getData(false);
	}

	formatDate(fecha){
		return moment(fecha).format('YYYY-MM-DD');
	}

	crearFormulario() {
		this.serviciosForm = this.fb.group({
			date: [new Date(), [Validators.required]]
		});
	}

	ngAfterViewInit(): void {
		this.getData(false);
	}

	editLitraje(servicio){

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

		dialogRef.afterClosed().subscribe(result => {
			if(result){
				this.dataSource.data = [];
				this.isLoading = true;
				this.ref.detectChanges();
				this.getData(false);
			}
		});
	}

	openQuiz(id) {
		const dialogRef = this.dialog.open(ModalEncuestaComponent, {
			data: id,
			disableClose: true,
			maxHeight: '100vh'
		});

		dialogRef.afterClosed().subscribe(result => {
			if(result){
			}
		});
	}

	openPDF(servicioEncId, servicioDetId) {
		window.open(environment.API + `atencionclientes/solicitud_servicios/solicitud/${servicioEncId}/servicio/${servicioDetId}?token=`+this.api.getAccessToken(), '_blank')
	}

	editSurvey(id) {
		this.router.navigate(['../solicitudes-servicio/edit/', id], {relativeTo: this.activatedRoute})
	}

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

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

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

		this.lastLength = filterValue.length;
	}

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

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