import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { SystemAdminService } from 'src/app/services/system-admin.service';
import { PriorityInterface } from '../../system-admin/system-params/system-params.component';
import { EncService } from 'src/app/services/enc/enc.service';
import { CorrectiveMaintenanceService } from 'src/app/services/corrective-maintenance.service';
import { CorrectiveWorkOrdersListItem, CorrectiveWorkOrdersListResponse } from 'src/app/interfaces/corrective-maintenance.interface';
import { FunctionsService } from 'src/app/services/functions.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatDialog } from '@angular/material/dialog';
import { CorrectiveOrderDetailsComponent } from './corrective-order-details/corrective-order-details.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { CommnetsDialogComponent } from './commnets-dialog/commnets-dialog.component';
import { TransferOrderDialogComponent } from './transfer-order-dialog/transfer-order-dialog.component';
import { StatusTimelineComponent } from './status-timeline/status-timeline.component';

@Component({
  selector: 'app-operations-management',
  templateUrl: './operations-management.component.html',
  styleUrls: ['./operations-management.component.css']
})
export class OperationsManagementComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  orderPriorities: PriorityInterface[];

  public btnSmall: boolean = false;
  public txtBuscador:string;

  dataSource?: MatTableDataSource<CorrectiveWorkOrdersListItem>;
  displayedColumns = ['ID', 'EQUIP', 'FECINI', 'FECFIN', 'CONT', 'TIPACT', 'PRIO', 'RESP', 'ESTA', 'ACCIONES'];

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

  constructor(
    private _router: Router,
    private _sysAdminService: SystemAdminService,
    private _encService: EncService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _functionsService: FunctionsService,
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.orderPriorities = [];
    
    this.txtBuscador = '';
    this.btnSmall = window.innerWidth <= 1405;
  }

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

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

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

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

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

          prioritiesArr.push(priority);
        }

        this.orderPriorities = prioritiesArr;
        this.getworkOrders();
      }
    }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 = 'Ocurrió un error inesperado.';
      }

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

  async getworkOrders(){
    try{
      this.isLoading = true;
      this.hasError = false
      this.errorStr = '';

      let idUser = localStorage.getItem('idusuario')!;
      let workOrders: CorrectiveWorkOrdersListResponse = await lastValueFrom(this._correctiveMaintenanceService.getWorkOrders(idUser, 1));

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

      if(!this.hasError){
        let workOrdersArr: CorrectiveWorkOrdersListItem[] = [];
        for(const order of workOrders.response){
          let idOrderDec = await this._encService.decrypt(order.ID_ORDEN);
          order.ID_ORDEN = idOrderDec;

          let equipmentCodeDec = await this._encService.decrypt(order.CODIGO_EQUIPAMIENTO);
          order.TIPO_EQUIPAMIENTO = `${equipmentCodeDec} - ${order.TIPO_EQUIPAMIENTO}`;

          let idEquipmentDec = await this._encService.decrypt(order.ID_EQUIPAMIENTO);
          order.MODELO_EQUIPAMIENTO = `${order.MODELO_EQUIPAMIENTO} (${idEquipmentDec})`;
          order.FECHA_INICIO = this._functionsService.orderDate(order.FECHA_INICIO)!;

          let counterDec = await this._encService.decrypt(order.CONTADOR);
          order.CONTADOR = counterDec;

          let priorityObj = await this.getPriorityObj(order.PRIORIDAD);
          order.PRIORIDAD_OBJ = priorityObj == null ? undefined : priorityObj;

          if(order.FECHA_FIN != null){
            order.FECHA_FIN = this._functionsService.orderDate(order.FECHA_FIN)!;
          }
          
          workOrdersArr.push(order);
        }

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

      this.isLoading = false;
    }catch(error: any){
      console.log(error);
      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 = 'Ocurrió un error inesperado.';
      }

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

  async getPriorityObj(priority: string): Promise<PriorityInterface | null>{
    let priorityStr = await this._encService.decrypt(priority);
    let priorityFilt: PriorityInterface | null = null;
    
    for(const priorityObj of this.orderPriorities){
      let idPriorityDec = await this._encService.decrypt(priorityObj.value);
      if(idPriorityDec == priorityStr){
        priorityFilt = priorityObj;
      }
    }

    return priorityFilt;
  }

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

  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 openWorkOrder(type: string, idOrder: string | null){
    let idOrderEnc = '';
    if(idOrder != null){
      idOrderEnc = await this._encService.encrypt(idOrder);
    }else{
      idOrderEnc = await this._encService.encrypt('-');
    }
    
    this._router.navigate([`sam/GMCO/ORTR/GEOP/${type}`], {
      queryParams: {
        idOrder: idOrderEnc
      }
    });
  }

  async openOrderDetails(idOrder: string){
    let idOrderEnc = await this._encService.encrypt(idOrder);
    this._dialog.open(CorrectiveOrderDetailsComponent, {
      width: '480px',
      data: {
        idOrder: idOrderEnc,
      }
    })
  }

  openConfirmDialog(action: string, idOrder: string){
    let actionStr = '';
    let desc2 = '';

    switch(action){
      case 'DEL':
        actionStr = 'eliminar';
        desc2 = 'Esta acción no se puede deshacer.';
      break;
      case 'APR':
        actionStr = 'aprobar';
        desc2 = 'Esta acción enviará la OT por notificación a los involucrados.';
      break;
    }

    let dialogRef = this._dialog.open(AlertComponent, {
      width: '420px',
      disableClose: true,
      data: {
        title: 'Confirmación',
        icon: 'warning',
        description: `¿Está seguro de ${actionStr} la orden de mantenimiento correctivo #${idOrder}?`,
        description2: desc2
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res == true){
        switch(action){
          case 'DEL': 
            this.deleteWorkOrder(idOrder);
          break;
          case 'APR':
            this.approveWorkOrder(idOrder);
          break;
        }
      }
    });
  }

  private async deleteWorkOrder(idOrder: string){
    try{
      let idOrderEnc = await this._encService.encrypt(idOrder);
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

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

      await lastValueFrom(this._correctiveMaintenanceService.deleteWorkOrder(formData));
      this._resourcesService.openSnackBar('La orden de trabajo se eliminó correctamente.');
      this.getworkOrders();
    }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 async approveWorkOrder(idOrder: string){
    try{
      let idOrderEnc = await this._encService.encrypt(idOrder);
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

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

      await lastValueFrom(this._correctiveMaintenanceService.approveWorkOrder(formData));
      this._resourcesService.openSnackBar('La orden de trabajo se aprobó correctamente.');
      this.getworkOrders();
    }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);
      }
    }
  }

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

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_order', idOrderEnc);
      
      await lastValueFrom(this._correctiveMaintenanceService.startWorkOrder(formData));

      this._resourcesService.openSnackBar('La ejecución de la orden de trabajo se inició correctamente.');
      this.getworkOrders();
    }catch(error: any){
      if(error.error.msg == 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('Ocurrió un error inesperado.');
      }

      this.getworkOrders();
    }
  }

  openCommentsDialog(idOrder: string, status: string){
    let dialogRef = this._dialog.open(CommnetsDialogComponent, {
      width: '480px',
      disableClose: true,
      data: {
        idOrder: idOrder,
        status: status,
      }
    });
    
    dialogRef.afterClosed().subscribe(res => {
      if(res != undefined && res != null && res != ''){
        this.updateWorkOrderStatus(idOrder, status, res);
      }
    });
  }

  private async updateWorkOrderStatus(idOrder: string, status: string, comments: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idOrderEnc = await this._encService.encrypt(idOrder);
      let statusKey = status.toUpperCase().substring(0, 2);
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_order', idOrderEnc);
      formData.append('status', statusKey);
      formData.append('comments', comments);

      let response = await lastValueFrom(this._correctiveMaintenanceService.updateWorkOrderStatus(formData));
      
      this._resourcesService.openSnackBar(response.msg);
      this.getworkOrders();
    }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);
      }

      this.getworkOrders();
    }
  }

  openTransferDialog(idOrder: string){
    let dialogRef = this._dialog.open(TransferOrderDialogComponent, {
      width: '420px',
      disableClose: true,
      data: {
        idOrder: idOrder
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != undefined && res != null && res != ''){
        let resArr = res.split('|');
        if(resArr.length < 3){
          this._resourcesService.openSnackBar('La acción seleccionada es inválida.');
        }else if(resArr[0] == 'transfer'){
          this.transferOrder(idOrder, resArr[1], resArr[2]);
        };
      }
    });
  }

  private async transferOrder(idOrder: string, idNewUser: string, type: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idOrderEnc = await this._encService.encrypt(idOrder);
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_order', idOrderEnc);
      formData.append('id_new_user', idNewUser);
      formData.append('type', type.charAt(0).toUpperCase());

      await lastValueFrom(this._correctiveMaintenanceService.transferWorkOrder(formData));
      this._resourcesService.openSnackBar('La orden se transifirió correctamente.');
      this.getworkOrders();
    }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);
      }
    }
  }

  openStatusTimeline(idOrder: string){
    this._dialog.open(StatusTimelineComponent, {
      width: '480px',
      data: {
        idOrder: idOrder
      }
    });
  }
}
