
import { CommonModule } from '@angular/common';
import { AfterViewInit, Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core';
import { ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatDialogTitle, MatDialogContent, MatDialogActions, MatDialogClose, MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIcon, MatIconRegistry } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatPaginator, MatPaginatorIntl } from '@angular/material/paginator';
import { MatSelect, MatSelectModule } from '@angular/material/select';
import { MatTableDataSource } from '@angular/material/table';
import { DomSanitizer } from '@angular/platform-browser';
import Swal from 'sweetalert2';
import * as XLSX from 'xlsx';
import { TipoTareasService } from '../../../services/tipo-tareas.service';
import { EnviarInfoService } from '../../../services/enviar-info.service';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatSlideToggleChange } from '@angular/material/slide-toggle';
import { NivelEducativoService } from '../../../services/nivel-educativo.service';
import { HttpClient } from '@angular/common/http';
import { ExportExcellService } from '../../../services/export-excell.service';

export interface TipoRegistroBitacora {
  clave: string;
  nombre: string;
  clasificar: string;
}
export interface TipoTareas {
  clave: string;
  nombre: string;
  envio: string;
}

export interface TipoInformacion {
  clave: string;
  nombre: string;
}

export interface PeriodoBoleta {
  clave: string;
  nombre: string;
  nivel: string;
  orden: number;
  predeterminado: boolean;
}

@Component({
  selector: 'app-tipos-tareas',
  templateUrl: './tipos-tareas.component.html',
  styleUrl: './tipos-tareas.component.css'
})
export class TiposTareasComponent implements OnInit {
  displayedColumns: string[] = [];
  dataSource = new MatTableDataSource<any>([]);
  colum: string = 'Tareas';
  color: string = '';
  textColor: string = '';
  niveles: any[] = [];
  NombreCompleto: string = '';
  filtro: string = 'Activo';
  isLoading: boolean = true;
  registros: any;

  @ViewChild('paginador1') paginator1!: MatPaginator;
  @ViewChild('paginador2') paginator2!: MatPaginator;
  @ViewChild('paginador3') paginator3!: MatPaginator;
  @ViewChild('paginador4') paginator4!: MatPaginator;
  @ViewChild('TABLE') table!: ElementRef;
  @ViewChild('filtroo') filtrooSelect!: MatSelect;

  constructor(public dialog: MatDialog, private _MatIconRegister: MatIconRegistry, private _DomSanitizer: DomSanitizer, private paginatorName: MatPaginatorIntl,
    public http: HttpClient,
        private exportExcell : ExportExcellService,

    private tipoTareasService: TipoTareasService, private _enviarInfo: EnviarInfoService) {
    this.option(this.colum);
    this._MatIconRegister.addSvgIcon('excel', this._DomSanitizer.bypassSecurityTrustResourceUrl('assets/icons/excel.svg'));
    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.paginatorName.nextPageLabel = "Siguiente";
    this.paginatorName.previousPageLabel = "Anterior";
    this.paginatorName.firstPageLabel = "Ir a la primer página";
    this.paginatorName.lastPageLabel = "Ir a la última página";
    this.paginatorName.itemsPerPageLabel = "Registros por página";
    this.paginatorName.getRangeLabel = spanishRangeLabel;
  }

  ngOnInit(): void {
    this._enviarInfo.currentTextColor.subscribe(textColor => {
      this.textColor = textColor;
    });
    this._enviarInfo.currentColor.subscribe(color => {
      this.color = color;
    });
    this.tipoTareasService.dataUpdated$.subscribe(() => {
      this.option(this.colum);
    });
  }


  option(event: any) {
    if (this.colum !== event) {
      this.filtro = 'Activo';
      if (this.filtrooSelect) {
        this.filtrooSelect.value = 'Activo';
      }
      this.colum = event;
    }
    this.isLoading = true;
    if (event === 'Tareas') {
      this.displayedColumns = ['clave', 'nombre', 'envio', 'estado', 'acciones'];
      this.tipoTareasService.getTipoTareas().subscribe(
        (data: any) => {
          this.isLoading = false;
          this.registros = data;
          this.dataSource = new MatTableDataSource(this.registros);
          this.dataSource.paginator = this.paginator1;
          this.Filtro(this.filtro);
        });
    } else if (event === 'Bitacora') {
      this.displayedColumns = ['clave', 'nombre', 'clasificar', 'estado', 'acciones'];
      this.tipoTareasService.getTipoBitacora().subscribe(
        (data: any) => {
          this.isLoading = false;
          this.registros = data;
          this.dataSource = new MatTableDataSource(this.registros);
          this.dataSource.paginator = this.paginator2;
          this.Filtro(this.filtro);
        });
    } else if (event === 'Informacion') {
      this.displayedColumns = ['clave', 'nombre', 'estado', 'acciones'];
      this.tipoTareasService.getTipoInfo().subscribe(
        (data: any) => {
          this.isLoading = false;
          this.registros = data;
          this.dataSource = new MatTableDataSource(this.registros);
          this.dataSource.paginator = this.paginator3;
          this.Filtro(this.filtro);
        });
    } else if (event === 'Boleta') {
      this.displayedColumns = ['clave1', 'nombre1', 'nivel', 'Orden', 'Predeterminado', 'estado', 'acciones'];
      this.tipoTareasService.getTipoPeriodo().subscribe(
        (data: any) => {
          this.isLoading = false;
          this.registros = data;
          this.dataSource = new MatTableDataSource(this.registros);
          this.dataSource.paginator = this.paginator4;
          this.Filtro(this.filtro);
        });
    }
  }

  Filtro(event: any) {
    this.filtro = event;
    this.dataSource.filter = this.filtro;
    if (this.colum === 'Tareas') {
      this.dataSource.paginator = this.paginator1;
    } else if (this.colum === 'Bitacora') {
      this.dataSource.paginator = this.paginator2;
    } else if (this.colum === 'Informacion') {
      this.dataSource.paginator = this.paginator3;
    } else if (this.colum === 'Boleta') {
      this.dataSource.paginator = this.paginator4;
    }
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  openDialog() {
    const dialogRef = this.dialog.open(BoletaComponent1, {
      data: { colum: this.colum }
    });
    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        if (this.colum === 'Tareas') {
          if (result.envio === true) {
            result.envio = 'Si';
          } else if (result.envio === false) {
            result.envio = 'No';
          }
          this.tipoTareasService.crearTipoTarea(result).subscribe((res: any) => {
            Swal.fire('Exito!', res.message, 'success');
          });

        } else if (this.colum === 'Bitacora') {
          if (result.clasificar === true) {
            result.clasificar = 'Si';
          } else if (result.clasificar === false) {
            result.clasificar = 'No';
          }
          this.tipoTareasService.crearTipoBitacora(result).subscribe((res: any) => {
            Swal.fire('Exito!', res.message, 'success');
          });

        } else if (this.colum === 'Informacion') {
          this.tipoTareasService.crearTipoInfo(result).subscribe((res: any) => {
            Swal.fire('Exito!', res.message, 'success');
          });

        } else if (this.colum === 'Boleta') {
          if (result.predeterminado === true) {
            result.predeterminado = 'Si';
          } else if (result.predeterminado === false) {
            result.predeterminado = 'No';
          }
          this.tipoTareasService.crearTipoPeriodo(result).subscribe((res: any) => {
            Swal.fire('Exito!', res.message, 'success');
          });
        }
      }
    });
  }
  exportarTodo() {
    this.exportExcell.exportAll('tipos_tareas');
  }

  openEditar(registro: any) {
    if (this.colum === 'Tareas') {
      const Editar = this.dialog.open(editarTarea, {
        data: { clave: registro.idTareasTipos, nombre: registro.nombreTareasTipos, envio: registro.envioPlatTareasTipos, colum: this.colum }
      });
      Editar.afterClosed().subscribe(result => {
        if (result) {
          if (result.envio === true) {
            result.envio = 'Si';
          } else if (result.envio === false) {
            result.envio = 'No';
          }
          this.tipoTareasService.actualizarTipoTarea(result).subscribe((res: any) => {
            Swal.fire('Actualizado!', res.message, 'success');
          });
        }
      });
    } else if (this.colum === 'Bitacora') {
      const Editar = this.dialog.open(editarTarea, {
        data: { clave: registro.idBitacorasTipos, nombre: registro.nombreBitacorasTipos, clasificar: registro.esReporteBitacorasTipos, colum: this.colum }
      });
      Editar.afterClosed().subscribe(result => {
        if (result) {
          if (result.clasificar === true) {
            result.clasificar = 'Si';
          } else if (result.clasificar === false) {
            result.clasificar = 'No';
          }
          this.tipoTareasService.actualizarTipoBitacora(result).subscribe((res: any) => {
            Swal.fire('Actualizado!', res.message, 'success');
          });
        }
      });
    } else if (this.colum === 'Informacion') {
      const Editar = this.dialog.open(editarTarea, {
        data: { clave: registro.idInformacionGeneralTipos, nombre: registro.nombreInformacionGeneralTipos, colum: this.colum }
      });
      Editar.afterClosed().subscribe(result => {
        if (result) {
          this.tipoTareasService.actualizarTipoInfo(result).subscribe((res: any) => {
            Swal.fire('Actualizado!', res.message, 'success');
          });
        }
      });
    } else if (this.colum === 'Boleta') {
      const Editar = this.dialog.open(editarTarea, {
        data: {
          clave: registro.idPeriodo, nombre: registro.nombrePeriodo, nivel: registro.idNivel,
          orden: registro.ordenBoleta, predeterminado: registro.predeterminado, colum: this.colum
        }
      });
      Editar.afterClosed().subscribe(result => {
        if (result) {
          if (result) {
            if (result.predeterminado === true) {
              result.predeterminado = 'Si';
            } else if (result.predeterminado === false) {
              result.predeterminado = 'No';
            }
          }
          this.tipoTareasService.actualizarTipoPeriodo(result).subscribe((res: any) => {
            Swal.fire('Actualizado!', res.message, 'success');
          });
        }
      });
    }
  }


  onToggleChange(event: MatSlideToggleChange, row: any) {
    event.source.checked = !event.checked;
    if (this.colum === 'Tareas') {
      if (row.estado === 'Activo') {
        this.confirmDelete(row.idTareasTipos, () => {
          this.delete(row.idTareasTipos, () => {
            row.estado = 'Eliminado';
            event.source.checked = false;
          });
        });
      } else {
        this.confirmEnable(row.idTareasTipos, () => {
          this.habilitarEstado(row.idTareasTipos, () => {
            row.estado = 'Activo';
            event.source.checked = true;
          });
        });
      }
    } else if (this.colum == 'Bitacora') {
      if (row.estado === 'Activo') {
        this.confirmDelete(row.idBitacorasTipos, () => {
          this.delete(row.idBitacorasTipos, () => {
            row.estado = 'Eliminado';
            event.source.checked = false;
          });
        });
      } else {
        this.confirmEnable(row.idBitacorasTipos, () => {
          this.habilitarEstado(row.idBitacorasTipos, () => {
            row.estado = 'Activo';
            event.source.checked = true;
          });
        });
      }
    } else if (this.colum == 'Informacion') {
      if (row.estado === 'Activo') {
        this.confirmDelete(row.idInformacionGeneralTipos, () => {
          this.delete(row.idInformacionGeneralTipos, () => {
            row.estado = 'Eliminado';
            event.source.checked = false;
          });
        });
      } else {
        this.confirmEnable(row.idInformacionGeneralTipos, () => {
          this.habilitarEstado(row.idInformacionGeneralTipos, () => {
            row.estado = 'Activo';
            event.source.checked = true;
          });
        });
      }
    } else if (this.colum == 'Boleta') {
      if (row.estado === 'Activo') {
        this.confirmDelete(row.idPeriodo, () => {
          this.delete(row.idPeriodo, () => {
            row.estado = 'Eliminado';
            event.source.checked = false;
          });
        });
      } else {
        this.confirmEnable(row.idPeriodo, () => {
          this.habilitarEstado(row.idPeriodo, () => {
            row.estado = 'Activo';
            event.source.checked = true;
          });
        }
        );
      }
    }
  }

  confirmDelete(id: string, callback: () => void) {
    Swal.fire({
      title: '¿Estas seguro de eliminar este registro?',
      text: "No podras revertir esta acción!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Si, eliminar!',
    }).then((result) => {
      if (result.isConfirmed) {
        callback();
      }
    });
  }

  confirmEnable(id: string, callback: () => void) {
    Swal.fire({
      title: '¿Estas seguro de habilitar este registro?',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Si, habilitar!',
    }).then((result) => {
      if (result.isConfirmed) {
        callback();
      }
    });
  }

  delete(id: string, callback: () => void) {
    if (this.colum === 'Tareas') {
      this.tipoTareasService.eliminarEstadoTT(id).subscribe((res: any) => {
        Swal.fire('Exito!', res.mensaje, 'success');
        callback();
      });
    } else if (this.colum == 'Bitacora') {
      this.tipoTareasService.eliminarEstadoTB(id).subscribe((res: any) => {
        Swal.fire('Exito!', res.mensaje, 'success');
        callback();
      });
    } else if (this.colum === 'Informacion') {
      this.tipoTareasService.eliminarEstadoTI(id).subscribe((res: any) => {
        Swal.fire('Exito!', res.mensaje, 'success');
        callback();
      });
    } else if (this.colum === 'Boleta') {
      this.tipoTareasService.eliminarEstadoTP(id).subscribe((res: any) => {
        Swal.fire('Exito!', res.mensaje, 'success');
        callback();
      });
    }
  }

  habilitarEstado(id: string, callback: () => void) {
    if (this.colum === 'Tareas') {
      this.tipoTareasService.habilitarEstadoTT(id).subscribe((res: any) => {
        Swal.fire('Exito!', res.mensaje, 'success');
        callback();
      });
    } else if (this.colum === 'Bitacora') {
      this.tipoTareasService.habilitarEstadoTB(id).subscribe((res: any) => {
        Swal.fire('Exito!', res.mensaje, 'success');
        callback();
      });
    }
    else if (this.colum === 'Informacion') {
      this.tipoTareasService.habilitarEstadoTI(id).subscribe((res: any) => {
        Swal.fire('Exito!', res.mensaje, 'success');
        callback();
      });
    } else if (this.colum === 'Boleta') {
      this.tipoTareasService.habilitarEstadoTP(id).subscribe((res: any) => {
        Swal.fire('Exito!', res.mensaje, 'success');
        callback();
      }, (error) => {
        Swal.fire('Error!', error.error.mensaje, 'error');
      });
    }
  }
}

@Component({
  selector: 'app-administracion',
  templateUrl: 'administracion.html',
  styleUrl: './tipos-tareas.component.css',
  standalone: true,
  imports: [MatDialogTitle, MatDialogContent, MatDialogActions, MatDialogClose, MatButtonModule, MatFormFieldModule, MatInputModule, MatIcon,
    MatCheckboxModule, MatSelectModule, ReactiveFormsModule, CommonModule, MatTooltipModule
  ],
})
export class BoletaComponent1 {
  colum: any;
  form!: FormGroup;
  nivel: any;
  constructor(private fb: FormBuilder, public dialog: MatDialogRef<BoletaComponent1>,
    private nivelEducativoService: NivelEducativoService, @Inject(MAT_DIALOG_DATA) public data: any) {
    this.datos();
    this.colum = data.colum;
  }

  getNiveles() {
    return this.nivelEducativoService.getHabilitados().subscribe((response) => {
      this.nivel = response;
    });
  }

  isValidField(field: string) {
    return this.form.controls[field].errors && this.form.controls[field].touched;
  }

  datos() {
    if (this.data.colum === 'Tareas') {
      this.form = this.fb.group({
        clave: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ,.][a-zA-Z0-9\\sáéíóúÁÉÍÓÚñÑ,.]*$')]],
        nombre: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ,.][a-zA-Z0-9\\sáéíóúÁÉÍÓÚñÑ,.]*$')]],
        envio: [false],
      });
    } else if (this.data.colum === 'Bitacora') {
      this.form = this.fb.group({
        clave: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ,.][a-zA-Z0-9\\sáéíóúÁÉÍÓÚñÑ,.]*$')]],
        nombre: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ,.][a-zA-Z0-9\\sáéíóúÁÉÍÓÚñÑ,.]*$')]],
        clasificar: [false],
      });
    }
    else if (this.data.colum === 'Informacion') {
      this.form = this.fb.group({
        clave: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ,.][a-zA-Z0-9\\sáéíóúÁÉÍÓÚñÑ,.]*$')]],
        nombre: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ,.][a-zA-Z0-9\\sáéíóúÁÉÍÓÚñÑ,.]*$')]],
      });
    }
    else if (this.data.colum === 'Boleta') {
      this.form = this.fb.group({
        clave: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ,.][a-zA-Z0-9\\sáéíóúÁÉÍÓÚñÑ,.]*$')]],
        nombre: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ,.][a-zA-Z0-9\\sáéíóúÁÉÍÓÚñÑ,.]*$')]],
        nivel: ['', [Validators.required]],
        orden: [, [Validators.required]],
        predeterminado: [false],
      });
      this.getNiveles();
    }
  }

  get tipoTarea(): TipoTareas {
    const tipoTarea = this.form.value as TipoTareas;
    return tipoTarea;
  }
  get tipoBitacora(): TipoRegistroBitacora {
    const tipoBitacora = this.form.value as TipoRegistroBitacora;
    return tipoBitacora;
  }
  get tipoInfo(): TipoInformacion {
    const tipoInfo = this.form.value as TipoInformacion;
    return tipoInfo;
  }
  get tipoBoleta(): PeriodoBoleta {
    const tipoBoleta = this.form.value as PeriodoBoleta;
    return tipoBoleta;
  }

  onSave() {
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    if (this.data.colum === 'Tareas') {
      this.dialog.close(this.tipoTarea);
    } else if (this.data.colum === 'Bitacora') {
      this.dialog.close(this.tipoBitacora);
    } else if (this.data.colum === 'Informacion') {
      this.dialog.close(this.tipoInfo);
    } else if (this.data.colum === 'Boleta') {
      this.dialog.close(this.tipoBoleta);
    }
  }

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

@Component({
  selector: 'app-editar',
  templateUrl: 'editar.html',
  styleUrl: './tipos-tareas.component.css',
  standalone: true,
  imports: [MatDialogTitle, MatDialogContent, MatDialogActions, MatDialogClose, MatButtonModule, MatFormFieldModule, MatInputModule, MatIcon,
    MatCheckboxModule, MatSelectModule, ReactiveFormsModule, CommonModule,
  ],
})
export class editarTarea implements OnInit {
  colum: any;
  form!: FormGroup;
  nivel: any;
  constructor(private fb: FormBuilder, public dialog: MatDialogRef<editarTarea>, @Inject(MAT_DIALOG_DATA) public data: any, private nivelEducativoService: NivelEducativoService) {
    this.colum = data.colum;
  }

  ngOnInit(): void {
    this.datos();
    if (this.data.clave) {
      this.form.get('clave')?.disable();
    }
  }

  isValidField(field: string) {
    return this.form.controls[field].errors && this.form.controls[field].touched;
  }

  getNiveles() {
    return this.nivelEducativoService.getHabilitados().subscribe((response) => {
      this.nivel = response;
    });
  }
  envios: any;
  clasificar1: any;
  predeterminado1: any;
  datos() {
    if (this.data.colum === 'Tareas') {
      this.envios = this.data.envio === 'Si' ? true : false;
      this.form = this.fb.group({
        clave: [this.data.clave],
        nombre: [this.data.nombre, [Validators.required, Validators.pattern('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ,.][a-zA-Z0-9\\sáéíóúÁÉÍÓÚñÑ,.]*$')]],
        envio: [this.envios],
      });
    } else if (this.data.colum === 'Bitacora') {
      this.clasificar1 = this.data.clasificar === 'Si' ? true : false;
      this.form = this.fb.group({
        clave: [this.data.clave],
        nombre: [this.data.nombre, [Validators.required, Validators.pattern('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ,.][a-zA-Z0-9\\sáéíóúÁÉÍÓÚñÑ,.]*$')]],
        clasificar: [this.clasificar1],
      });
    }
    else if (this.data.colum === 'Informacion') {
      this.form = this.fb.group({
        clave: [this.data.clave],
        nombre: [this.data.nombre, [Validators.required, Validators.pattern('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ,.][a-zA-Z0-9\\sáéíóúÁÉÍÓÚñÑ,.]*$')]],
      });
    }
    else if (this.data.colum === 'Boleta') {
      this.predeterminado1 = this.data.predeterminado === 'Si' ? true : false;
      this.form = this.fb.group({
        clave: [this.data.clave],
        nombre: [this.data.nombre, [Validators.required, Validators.pattern('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ,.][a-zA-Z0-9\\sáéíóúÁÉÍÓÚñÑ,.]*$')]],
        nivel: [this.data.nivel, Validators.required],
        orden: [this.data.orden, [Validators.required]],
        predeterminado: [this.predeterminado1],
      });
      this.getNiveles();
    }
  }

  onSave() {
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    if (this.colum === 'Tareas') {
      this.dialog.close(this.form.getRawValue());
    } else if (this.colum === 'Bitacora') {
      this.dialog.close(this.form.getRawValue());
    } else if (this.colum === 'Informacion') {
      this.dialog.close(this.form.getRawValue());
    } else if (this.colum === 'Boleta') {
      this.dialog.close(this.form.getRawValue());
    }
  }
}
