import { Component, Inject, OnInit } from '@angular/core';
import { NotificationAction, NotificationDetailsResponse, NotificationsListItem } from '../../../interfaces/notification.interface';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { NotificationsService } from '../../../services/notifications.service';
import { ResourcesService } from '../../../services/resources.service';
import { CorrectiveMaintenanceService } from '../../../services/corrective-maintenance.service';
import { lastValueFrom } from 'rxjs';
import { CorrectiveOrderDetailsComponent } from '../../corrective-maintenance/operations-management/corrective-order-details/corrective-order-details.component';
import { AgreeOrderComponent } from './agree-order/agree-order.component';
import { SignatureViewComponent } from './signature-view/signature-view.component';
import { StaffSelectionComponent } from '../../corrective-maintenance/operations-management/staff-selection/staff-selection.component';
import { CommentsViewComponent } from './comments-view/comments-view.component';

@Component({
    selector: 'app-notification-dialog',
    templateUrl: './notification-dialog.component.html',
    styleUrl: './notification-dialog.component.css',
    standalone: false
})
export class NotificationDialogComponent implements OnInit {
  idNotification: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  notification: NotificationsListItem | null;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _notificationsService: NotificationsService,
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _dialogRef: MatDialogRef<NotificationDialogComponent>,
  ) {
    this.idNotification = '';
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.notification = null;
  }

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

  async init(){
    this.idNotification = await this._encService.decrypt(this._data.idNotification);
    this.getNotification();
  }

  async getNotification(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let notification: NotificationDetailsResponse = await lastValueFrom(this._notificationsService.getNotification(
        this._data.idNotification, 
        'S',
        idUser, 
        1
      ));

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

      if(!this.hasError){
        let notificationActionsArr: NotificationAction[] = JSON.parse(notification.response.ACCIONES);
        
        notification.response.ACCIONES_ARR = notificationActionsArr;
        if (notification.response.ID_ORDEN !== null) {
          notification.response.ID_ORDEN = await this._encService.decrypt(notification.response.ID_ORDEN);
        }

        this.notification = notification.response;
      }

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

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

  executeNotificationAction(func: string, params: string){
    let paramsArr = JSON.parse(params);
    switch(func){
      case "openCorrectiveWorkOrderDetails":
        this.openCorrectiveWorkOrderDetails(paramsArr[0]);
      break;
      case "validateCorrectiveWorkOrder":
        this.validateCorrectiveWorkOrder(paramsArr[0]);
      break;
      case "openModule":
        this._dialogRef.close(`go|${paramsArr[0]}`);
      break;
      case "attendCorrectiveWorkOrder":
        this.attendCorrectiveWorkOrder(paramsArr[0]);
      break;
      case "reviewSignatureInCorrectiveWorkOrder":
        this.reviewSignatureInCorrectiveWorkOrder(paramsArr[0], paramsArr[1]);
      break;
      case "reviewCommentsInCorrectiveWorkOrder":
        this.reviewCommentsInCorrectiveWorkOrder(paramsArr[0], paramsArr[1]);
      break;
      case "revalidateCorrectiveWorkOrder":
        this.revalidateCorrectiveWorkOrder(paramsArr[0]);
      break;
      default:
        this._resourcesService.openSnackBar('La función seleccionada no existe.');
      break;
    }
  }

  //FUNCIONES POSIBLES PARA LAS NOTIFICACIONES
  openCorrectiveWorkOrderDetails(idOrder: string){
    this._dialog.open(CorrectiveOrderDetailsComponent, {
      width: '480px',
      data: {
        idOrder: idOrder,
      }
    })
  }

  private validateCorrectiveWorkOrder(idOrder: string){
    let dialogRef = this._dialog.open(StaffSelectionComponent, {
      disableClose: true,
      width: '540px',
      maxWidth: '540px',
      data: {
        idOrder: idOrder,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.approveWorkOrder(idOrder, res);
      }
    });
  }

  private revalidateCorrectiveWorkOrder(idOrder: string){
    let dialogRef = this._dialog.open(StaffSelectionComponent, {
      disableClose: true,
      width: '540px',
      maxWidth: '540px',
      data: {
        idOrder: idOrder,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.updateApprovedWorkOrder(idOrder, res);
      }
    });
  }

  private async approveWorkOrder(idOrder: string, config: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_order', idOrder);
      formData.append('config', config);

      await lastValueFrom(this._correctiveMaintenanceService.approveWorkOrder(formData));
      this._resourcesService.openSnackBar('La orden de trabajo se aprobó correctamente.');
      this._dialogRef.close();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (14).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (15).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  private async updateApprovedWorkOrder(idOrder: string, config: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_order', idOrder);
      formData.append('config', config);

      await lastValueFrom(this._correctiveMaintenanceService.updateApprovedWorkOrder(formData));
      this._resourcesService.openSnackBar('La orden de trabajo se actualizó correctamente.');
      this._dialogRef.close();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (14).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (15).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  attendCorrectiveWorkOrder(idOrder: string){
    let dialogRef = this._dialog.open(AgreeOrderComponent, {
      disableClose: true,
      width: "560px",
      maxWidth: "560px",
      data: {
        idOrder: idOrder,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.saveAttendanceCorrectiveOrder(idOrder, res);
      }
    })
  }

  private async saveAttendanceCorrectiveOrder(idOrder: string, dataEnc: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let dataDec = await this._encService.decrypt(dataEnc);
      let dataArr = JSON.parse(dataDec);
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_order', idOrder);
      formData.append('attendance', dataArr[0]);
      formData.append('data', dataArr[1]);

      await lastValueFrom(this._correctiveMaintenanceService.setWorkOrderAttendance(formData));
      this._resourcesService.openSnackBar('La atención a la orden de trabajo se registró correctamente.');
      this._dialogRef.close();
    }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);
      }
    }
  }

  private reviewSignatureInCorrectiveWorkOrder(idOrder: string, idUserAction: string){
    this._dialog.open(SignatureViewComponent, {
      width: '420px',
      maxWidth: '420px',
      data: {
        idOrder: idOrder,
        idUserAction: idUserAction,
      }
    });
  }

  private reviewCommentsInCorrectiveWorkOrder(idOrder: string, idUserAction: string){
    this._dialog.open(CommentsViewComponent, {
      width: '420px',
      maxWidth: '420px',
      data: {
        idOrder: idOrder,
        idUserAction: idUserAction,
      }
    });
  }
}
