import { Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
import { MatPaginator, MatPaginatorIntl } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { GradoEducativo } from '../../interfaces/GradoEducativo.interface';
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 { GradosEducativosService } from '../../services/grados-educativos.service';
import Swal from 'sweetalert2';
import { MatDialog } from '@angular/material/dialog';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { NivelEducativoService } from '../../services/nivel-educativo.service';




@Component({
  selector: 'app-grados-educativos',
  templateUrl: './grados-educativos.component.html',
  styleUrl: './grados-educativos.component.css'
})
export class GradosEducativosComponent {
  public color: string = '';
  public textColor: string = '';
  public columnas: string[] = ['claveGrado', 'nombreGrado', 'nivelRelacionado', 'estado', 'acciones'];
  public datos: GradoEducativo[] = [];
  // public dataSource: any;

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



  constructor(private _MatIconRegister: MatIconRegistry,
    private _DomSanitizer: DomSanitizer,
    private paginatorIntl: MatPaginatorIntl,
    private _enviarInfo: EnviarInfoService,
    private gradoEducativoService: GradosEducativosService,
    public dialog: MatDialog
  ) {
    this._MatIconRegister.addSvgIcon('excel', this._DomSanitizer.bypassSecurityTrustResourceUrl('assets/icons/excel.svg'));
    //paginador de la tabla angular material 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;
    });
    this._enviarInfo.tabla$.subscribe(() => {
      this.getGrados();
    });

    this.getGrados();
  }



  deleteGrado(id: string) {

    Swal.fire({
      icon: 'question',
      title: '¿Desea cambiar el estado del grado?',
      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.gradoEducativoService.eliminarGrado(id).subscribe((response: any) => {
          console.log(response);
          Swal.fire({
            icon: 'success',
            title: 'Grado educativo 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();
      }
    });

  }

  enableGrado(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.gradoEducativoService.habilitarGrado(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.mensaje}`,
          })
        }
        )
      } else if (result.dismiss == 'cancel') {
        this.ngOnInit();
      }
    });
  }

  //filtro de busqueda
  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
  public allInfo: any;
  public isLoading: boolean = true;
  public dataSource: any;

  getGrados() {
    this.gradoEducativoService.getAll().subscribe((response: any) => {
      this.isLoading = false;
      this.allInfo = response;
      this.dataSource = new MatTableDataSource<GradoEducativo>(this.allInfo.filter((filtro:any) => filtro.estado === 'Activo'));
      this.dataSource.paginator = this.paginator;
    });
  }

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

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

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


  //exportar búsqueda a excel
  exportAsExcel() {
    const ws: XLSX.WorkSheet = XLSX.utils.table_to_sheet(this.table.nativeElement);
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'COLEGIOABC-ConsultaGrados');
    XLSX.writeFile(wb, 'Grados.xlsx');

  }

  // exportar toda la data
  exportAll() {
    const dataSource = this.dataSource.data;
    const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(dataSource);
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'COLEGIOABC-ConsultaGrados');
    XLSX.writeFile(wb, 'Grados.xlsx');
  }

  openDialog(id: string) {
    const dialogRef = this.dialog.open(ModalGradoeducativoEdit, {
      autoFocus: false
    });

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

    dialogRef.componentInstance.setData(id);
  }

}


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

})

export class ModalGradoeducativoEdit implements OnInit {
  public isLoading: boolean = true;
  public data: any;
  public dataNiveles: any;

  public widowWidth!: number;
  //esto es para actualizar la tabla
  @Output() gradoActualizado = new EventEmitter<void>();
  constructor(public dialog: MatDialog,
    private gradoEducativoService: GradosEducativosService,
    private nivelEducativoService: NivelEducativoService) {
  }

  ngOnInit(): void {
    this.getNiveles()
  }

  public form = new FormGroup({
    idGrado: new FormControl<string>({ value: '', disabled: true }),
    nombreGrado: new FormControl<string>('', Validators.required),
    idNivel: new FormControl<string>('', Validators.required),
  })
  setData(id: any) {
    this.gradoEducativoService.getOne(id).subscribe((response: any) => {

      this.isLoading = false;
      this.data = response;

      // mostrar data en el formulario
      this.form.controls['idGrado'].setValue(this.data.idGrado);
      this.form.controls['nombreGrado'].setValue(this.data.nombreGrado);
      this.form.controls['idNivel'].setValue(this.data.idNivel);
    })
  }
  getNiveles() {
    return this.nivelEducativoService.getHabilitados().subscribe((response) => {
      this.dataNiveles = response;
      ;
    })
  }
  editarGradoEducativo() {

    let info = {
      id: this.data.nombreGrado,
      idGrado: this.data.idGrado,
      nombreGrado: this.form.value.nombreGrado,
      idNivel: this.form.value.idNivel,
    }

    this.gradoEducativoService.actualizarGrado(info).subscribe((response: any) => {

      Swal.fire({
        icon: 'success',
        title: `${response.mensaje}`
      })
      this.dialog.closeAll();
      this.gradoActualizado.emit();
    }, (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;
    }
  }
}