import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MaintenancePlansListItem, MaintenancePlansListResponse } from '../../../interfaces/corrective-maintenance.interface';
import { PriorityInterface } from '../../system-admin/system-params/system-params.component';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { Router } from '@angular/router';
import { EncService } from '../../../services/enc.service';
import { CorrectiveMaintenanceService } from '../../../services/corrective-maintenance.service';
import { SystemAdminService } from '../../../services/system-admin.service';
import { MatDialog } from '@angular/material/dialog';
import { ResourcesService } from '../../../services/resources.service';
import { lastValueFrom } from 'rxjs';
import { PlanDetailsComponent } from './plan-details/plan-details.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-maintenance-planning',
    templateUrl: './maintenance-planning.component.html',
    styleUrl: './maintenance-planning.component.css',
    standalone: false
})
export class MaintenancePlanningComponent implements OnInit {
  public btnSmall: boolean = false;
  public txtBuscador:string;

  dataSource: MatTableDataSource<MaintenancePlansListItem>;
  displayedColumns = ['ID', 'EQUIP', 'TIEINM', 'DURATOT', 'CLASIF', 'CONTADOR', 'ACTIVADOR', 'PRIORIDAD', 'ESTADO', 'ACCIONES'];

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  priorities: PriorityInterface[];

  @ViewChild(MatPaginator) paginator?: MatPaginator;
  @ViewChild(MatSort) sort?: MatSort;

  constructor(
    private _router: Router,
    private _encService: EncService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _systemAdminService: SystemAdminService,
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
  ) {
    this.btnSmall = window.innerWidth <= 1405;
    this.txtBuscador = '';

    this.dataSource = new MatTableDataSource();

    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.priorities = [];
  }

  ngOnInit(): void {
    this.getPriorities();
  }

  async getPriorities(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let priorities = await lastValueFrom(this._systemAdminService.getOrderPriorities(idUser, 1));

      this.hasError = priorities.error;
      this.errorStr = priorities.msg;

      if(this.hasError){
        this.isLoading = false;
      }else{
        let prioritiesArr: PriorityInterface[] = [];
        for(const priority of priorities.response.order_priorities as PriorityInterface[]){
          let valueEnc = await this._encService.encrypt(priority.value);

          priority.label = `${priority.label} (${priority.value})`;
          priority.value = valueEnc;

          prioritiesArr.push(priority);
        }

        this.priorities = prioritiesArr;
        this.getMaintenancePlans();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (1).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (2).';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async getMaintenancePlans(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';
      
      let idUser = localStorage.getItem('idusuario')!;
      let maintenancePlans: MaintenancePlansListResponse = await lastValueFrom(this._correctiveMaintenanceService.getMaintenancePlans(idUser, 1));

      this.hasError = maintenancePlans.error;
      this.errorStr = maintenancePlans.msg;

      if(!this.hasError){
        let maintenancePlansArr: MaintenancePlansListItem[] = [];
        for(const plan of maintenancePlans.response){
          plan.ID_PLAN = await this._encService.decrypt(plan.ID_PLAN);
          plan.EQUIPAMIENTO = await this._encService.decrypt(plan.EQUIPAMIENTO);

          if(plan.LRU != null){
            plan.LRU = await this._encService.decrypt(plan.LRU);
          }

          plan.CONTADOR = await this._encService.decrypt(plan.CONTADOR);
          plan.ACTIVADOR = await this._encService.decrypt(plan.ACTIVADOR);

          let priorityDec = await this._encService.decrypt(plan.PRIORIDAD);
          for(const priority of this.priorities){
            let valDec = await this._encService.decrypt(priority.value);
            if(valDec == priorityDec){
              plan.PRIORIDAD_OBJ = priority;
            }
          }

          maintenancePlansArr.push(plan);
        }

        this.dataSource = new MatTableDataSource(maintenancePlansArr);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (3).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (4).';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  applyFilter(event: any, type: string){
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource!.filter = filterValue.trim().toLowerCase();

    if(this.dataSource?.paginator){
      this.dataSource.paginator.firstPage();
    }
  }

  async openMaintenancePlan(action: string, idPlan: string | null) {
    if(action == 'nuevo'){
      this._router.navigate(['sam/GMCO/GEME/PLAN/nuevo']);
    }else{
      let idPlanEnc = await this._encService.encrypt(idPlan!);
      this._router.navigate(['sam/GMCO/GEME/PLAN/editar'], {
        queryParams: {
          data: idPlanEnc,
        }
      });
    }
  }

  async openPlanDetails(idPlan: string){
    let idPlanEnc = await this._encService.encrypt(idPlan);
    let dialogRef = this._dialog.open(PlanDetailsComponent, {
      width: '540px',
      maxWidth: '540px',
      data: {
        idPlan: idPlanEnc
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      console.log(res);
    });
  }

  openConfirmDelete(idPlan: string){
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '420px',
      maxWidth: '420px',
      data: {
        title: 'Confirmación',
        icon: 'warning',
        description: `¿Está seguro de eliminar el plan de mantenimiento #${idPlan}?`,
        description2: 'Esta acción no se puede deshacer.'
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res == true){
        this.deleteMaintenancePlan(idPlan);
      }
    });
  }

  async deleteMaintenancePlan(idPlan: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idPlanEnc = await this._encService.encrypt(idPlan);
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_plan', idPlanEnc);

      await lastValueFrom(this._correctiveMaintenanceService.deleteMaintenancePlan(formData));

      this._resourcesService.openSnackBar('El plan de mentenimiento se eliminó correctamente.');
      this.getMaintenancePlans();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
