import { Component, ElementRef, EventEmitter, Inject, OnInit, Output, ViewChild } from '@angular/core';
import { Grupo } from '../../interfaces/Grupo.interface';
import { MatPaginator, MatPaginatorIntl } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import * as XLSX from 'xlsx';
import { EnviarInfoService } from '../../services/enviar-info.service';
import { GruposService } from '../../services/grupos.service';
import { MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import Swal from 'sweetalert2';
import { HttpClient } from '@angular/common/http';
import { ExportExcellService } from '../../services/export-excell.service';

@Component({
  selector: 'app-grupos',
  templateUrl: './grupos.component.html',
  styleUrl: './grupos.component.css'
})
export class GruposComponent {
  public columnas: string[] = ['claveGrupo', 'nombreGrupo', 'estado', 'acciones'];
  public datos: Grupo[] = [];
  public dataSource: any;
  public color: string = '';
  public textColor: string = '';

  @ViewChild('TABLE') table!: ElementRef;
  @ViewChild(MatPaginator, { static: true }) paginator!: MatPaginator;


  constructor(private _MatIconRegister: MatIconRegistry,
    private _DomSanitizer: DomSanitizer,
    private paginatorIntl: MatPaginatorIntl,
    private _enviarInfo: EnviarInfoService,
    private gruposService: GruposService,
    public dialog: MatDialog,
    public http:HttpClient,
    private exportExcell : ExportExcellService,

  ) {
    this._MatIconRegister.addSvgIcon('excel', this._DomSanitizer.bypassSecurityTrustResourceUrl('assets/icons/excel.svg'));

    //paginador de tabla a español
    const spanishRangeLabel = (page: number, pageSize: number, length: number): string => {
      if (length === 0 || pageSize === 0) {
        return `0 de ${length}`;
      }
      length = Math.max(length, 0);
      const startIndex = page * pageSize;
      const endIndex = startIndex < length ?
        Math.min(startIndex + pageSize, length) :
        startIndex + pageSize;
      return `${startIndex + 1} - ${endIndex} de ${length}`;
    };
    this.paginatorIntl.nextPageLabel = "Siguiente";
    this.paginatorIntl.previousPageLabel = "Anterior";
    this.paginatorIntl.firstPageLabel = "Ir a la primer página";
    this.paginatorIntl.lastPageLabel = "Ir a la última página";
    this.paginatorIntl.itemsPerPageLabel = "Registros por página";
    this.paginatorIntl.getRangeLabel = spanishRangeLabel;
  }

  ngOnInit(): void {
    this._enviarInfo.currentTextColor.subscribe(textColor => {
      this.textColor = textColor;
    });
    this._enviarInfo.currentColor.subscribe(color => {
      this.color = color;
    });

    //suscribirse al subject que manda al servicio
    this._enviarInfo.tabla$.subscribe(() => {
      this.getGrupos();
    });

    this.getGrupos();
  }

  //filtro de búsqueda
  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

  public isLoading: boolean = true;


  exportarTodo() {
    this.exportExcell.exportAll('grupos');
  }


  public allInfo: any;

  //Traer la información y mostrarla en la tabla
  getGrupos() {
    return this.gruposService.getAllGrupos().subscribe((response: any) => {
      this.isLoading = false;
      this.allInfo = response
      this.dataSource = new MatTableDataSource<Grupo>(this.allInfo.filter((filtro: any) => filtro.estado === 'Activo'));
      this.dataSource.paginator = this.paginator;
      console.log(response);
      return response;
    })
  }

  option(event: string) {
    this.isLoading = true;
    let filteredData: any;

    if (event === 'Activos') {
      filteredData = this.allInfo.filter((filtro: any) => filtro.estado === 'Activo');
    } else if (event === 'Eliminados') {
      filteredData = this.allInfo.filter((filtro: any) => filtro.estado === 'Eliminado');
    }

    this.dataSource = new MatTableDataSource<Grupo>(filteredData);
    this.dataSource.paginator = this.paginator;
    this.isLoading = false;
  }

  deleteGrupo(id: string) {

    Swal.fire({
      icon: 'question',
      title: '¿Desea cambiar el estado del grupo?',
      showCancelButton: true,
      allowEscapeKey: false,
      allowOutsideClick: false,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: "Eliminar",
    }).then((result: any) => {
      /* Read more about isConfirmed, isDenied below */
      if (result.isConfirmed) {
        this.gruposService.eliminarGrupo(id).subscribe((response: any) => {
          console.log(response);
          Swal.fire({
            icon: 'success',
            title: 'Grupo deshabilitado',
            confirmButtonColor: 'rgb(237,46,56)',
            confirmButtonText: 'Ok',
          }).then((result: any) => {

            if (result.isConfirmed) {
              this.ngOnInit();
              Swal.close();
            }
          })
        }, (err) => {
          console.log(err);
          Swal.fire({
            icon: 'error',
            title: 'Error al eliminar',
            text: `${err.error.mensaje}`,
          })
          this.ngOnInit();
        }
        )
      } else if (result.dismiss == 'cancel') {
        this.ngOnInit();
      }
    });

  }

  enableGrupo(id: string) {
    Swal.fire({
      icon: 'question',
      title: '¿Desea habilitar el grado?',
      showCancelButton: true,
      allowEscapeKey: false,
      allowOutsideClick: false,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: "Habilitar",
    }).then((result: any) => {

      if (result.value) {
        this.gruposService.habilitarGrupo(id).subscribe((response: any) => {
          Swal.fire({
            icon: 'success',
            title: 'Grado educativo habilitado',
            confirmButtonColor: 'rgb(237,46,56)',
            confirmButtonText: 'Ok',
          }).then((result: any) => {
            if (result.isConfirmed) {
              Swal.close();
              this.ngOnInit();
            }
          })
        }, (err) => {
          console.log(err);
          Swal.fire({
            icon: 'error',
            title: 'Error al habilitar',
            text: `${err.error.message}`,
          })
        }
        )
      } else if (result.dismiss == 'cancel') {
        this.ngOnInit();
      }
    });
  }

  openDialog(grupo: any) {
    const dialogRef = this.dialog.open(ModalGrupoEdit, {
      autoFocus: false,
      data: grupo
    });

    //esto es para actualizar la tabla una vez actualizada la info
    dialogRef.componentInstance.nivelActualizado.subscribe(() => {
      this.getGrupos();
    });

  }

}





@Component({
  selector: 'dialog-content-example-dialog',
  templateUrl: 'editar.component.html',
  styleUrl: './grupos.component.css'

})

export class ModalGrupoEdit implements OnInit {

  public dataNiveles: any;

  public widowWidth!: number;
  //esto es para actualizar la tabla
  @Output() nivelActualizado = new EventEmitter<void>();
  constructor(
    public dialog: MatDialog,
    private gruposService: GruposService,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.setData();
  }

  ngOnInit(): void {

  }

  public form = new FormGroup({
    idGrupo: new FormControl<string>({ value: '', disabled: true }),
    nombreGrupo: new FormControl<string>('', Validators.required),

  })
  setData() {

    console.log(this.data);
    // mostrar data en el formulario
    this.form.controls['idGrupo'].setValue(this.data.idGrupo);
    this.form.controls['nombreGrupo'].setValue(this.data.nombreGrupo);

  }

  editarGrupo() {

    let info = {
      id: this.data.idGrupo,
      idGrupo: this.data.idGrupo,
      nombreGrupo: this.form.value.nombreGrupo,
    }

    this.gruposService.actualizarGrupo(info).subscribe((response: any) => {
      console.log(response);
      Swal.fire({
        icon: 'success',
        title: `${response.mensaje}`
      })
      this.dialog.closeAll();
      this.nivelActualizado.emit();
    }, (err) => {
      console.log(err);
      Swal.fire({
        icon: 'error',
        title: `${err.message}`
      })
    })
  }

  close() {
    this.dialog.closeAll()
  }

  limpiar() {
    this.form.reset();
  }

  campoNoValido(campo: string): boolean {
    if (this.form.get(campo)?.invalid && this.form.get(campo)?.touched) {
      return true;
    } else {
      return false;
    }
  }

  campoVacio(campo: string): boolean {
    if ((this.form.get(campo)?.value === '') && this.form.get(campo)?.touched) {
      return true;
    } else {
      return false;
    }
  }
}
