import { Component, ElementRef, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatIconRegistry } from '@angular/material/icon';
import { MatPaginator, MatPaginatorIntl } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { DomSanitizer } from '@angular/platform-browser';
import { EnviarInfoService } from '../../services/enviar-info.service';
import { MatDialog } from '@angular/material/dialog';
import { HttpClient } from '@angular/common/http';
import * as XLSX from 'xlsx';
import Swal from 'sweetalert2';
import { NivelEducativoService } from '../../services/nivel-educativo.service';
import { PeriodosService } from '../../services/periodos.service';
import { ExportExcellService } from '../../services/export-excell.service';


@Component({
  selector: 'app-periodos',
  templateUrl: './periodos.component.html',
  styleUrl: './periodos.component.css'
})
export class PeriodosComponent {
  public checked = false;
  public isLoading: boolean = true;
  public searchInput = new FormControl('');
  public color: string = '';
  public textColor: string = '';
  public columnas: string[] = ['claveNivel', 'nombreNivel', 'fechaFinalizacion', 'estado', 'acciones'];
  public dataSource = new MatTableDataSource<any>();


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


  constructor(
    private _periodoService: PeriodosService,
    private _MatIconRegister: MatIconRegistry,
    private _DomSanitizer: DomSanitizer,
    private paginatorIntl: MatPaginatorIntl,
    private _enviarInfo: EnviarInfoService,
    public dialog: MatDialog,
    private 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.getPeriodos();
    });

    this.getPeriodos()
  }
  public allInfo: any;

  //Traer la información y mostrarla en la tabla
  getPeriodos() {
    return this._periodoService.getAllPeriodos().subscribe((response: any) => {
      this.isLoading = false;
      this.allInfo = response.data
      this.dataSource = new MatTableDataSource<any>(this.allInfo.filter((filtro: any) => filtro.estatus === 'Activo' || filtro.estatus === 'Inactivo'));
      this.dataSource.paginator = this.paginator;
      console.log(response);

      return response;
    })
  }

  onToggleClick(periodo: any) {
  if (periodo.estatus === 'Inactivo') {
    this.activarPeriodo(periodo.idPeriodo);
  }
  // Si es "Eliminado" o "Activo", no hace nada (está "deshabilitado")
}


  activarPeriodo(id: string) {
    this._periodoService.activarPeriodo(id).subscribe((response: any) => {
      Swal.fire({
        icon: 'success',
        title: 'Periodo activado correctamente',
        confirmButtonColor: 'rgb(237,46,56)',
        confirmButtonText: 'Ok',
      }).then((result: any) => {
        if (result.isConfirmed) {
          this.ngOnInit();
          Swal.close();
        }
      });
    }, (err: any) => {
      console.log(err);
      Swal.fire({
        icon: 'error',
        title: 'Error al activar el periodo',
        text: `${err.error.message}`,
      });
      this.ngOnInit();
    }
    )
  }

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

    if (event === 'Todos') {
      filteredData = this.allInfo.filter((filtro: any) => filtro.estatus === 'Activo' || filtro.estatus === 'Inactivo');
    } else if (event === 'Eliminados') {
      filteredData = this.allInfo.filter((filtro: any) => filtro.estatus === 'Eliminado');
    }

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


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

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










  deletePeriodo(id: string) {

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

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

  }

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

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

  // openDialog(nivel: any) {
  //   const dialogRef = this.dialog.open(ModalNiveleducativoEdit, {
  //     autoFocus: false,
  //     data: { clave: nivel.idNivel, nombre: nivel.nombreNivel }
  //   });

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


}
