import { PreventiveMaintenanceService } from 'src/app/services/preventive-maintenance.service';
import { MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { EncService } from './../../../services/enc/enc.service';
import { Router } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { PreventiveWorkOrders, PreventiveWorkOrdersResponse } from 'src/app/interfaces/preventive-work-orders.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { Permissions } from 'src/app/interfaces/permissions.interface';
import { lastValueFrom } from 'rxjs';
import { SocketService } from 'src/app/services/socket.service';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { UsersProfilesService } from 'src/app/services/users-profiles.service';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';
import { CopyOrderComponent } from './copy-order/copy-order.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { OrderDetailsComponent } from './order-details/order-details.component';
import { SystemAdminService } from 'src/app/services/system-admin.service';
import { PriorityInterface } from '../../system-admin/system-params/system-params.component';

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

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

  dataSource?: MatTableDataSource<PreventiveWorkOrders>;
  displayedColumns = ['ID', 'EQUIPO', 'FECINI', 'HORINI', 'FECFIN', 'HORFIN', 'ACTIVADOR', 'PRIORIDAD', 'ESTADO', 'ACCIONES'];
  MONTHS = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];

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

  createOrdersEnabled: boolean;
  ordersHistoryEnabled: boolean;
  copyOrderEnabled: boolean;
  orderPriorities: PriorityInterface[];

  constructor(
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _router: Router,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _snackBar: MatSnackBar,
    private _dialog: MatDialog,
    private _sysAdminService: SystemAdminService,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.txtBuscador = '';

    this.createOrdersEnabled = true;
    this.ordersHistoryEnabled = true;
    this.copyOrderEnabled = true;
    this.btnSmall = window.innerWidth <= 1405;
    this.orderPriorities = [];
  }

  ngOnInit(): void {
    this.getOrderPriorities();
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      let idUser = localStorage.getItem('idusuario')!;
      let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesSevice.getUser(idUser, idUser, 1));
      let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

      if(parseInt(currentProfile) != usrInfo.response.PERFIL){
        this._router.navigate(['/sam/home']);
      }

      let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
      if(profileUpdated == currentProfile){
        try{
          let profile = localStorage.getItem('perfil')!;
          let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesSevice.getProfile(
            profile,
            idUser,
            1
          ));

          let modPerm = profInfo.response.PERMISOS.permissions.filter(item => item.id == 'S002V01M10GMPR')[0];
          let subPerm = modPerm.children.filter(item => item.id == 'S002V01S01ORTR')[0];
          let funPerm = subPerm.children.filter(item => item.id == 'S002V01F01COTP')[0];
    
          this.createOrdersEnabled = funPerm.children.filter(item => item.id == 'S002V01P02ROTP')[0].access > 0;
          this.ordersHistoryEnabled = funPerm.children.filter(item => item.id == 'S002V01P01HOTP')[0].access > 0;
          this.copyOrderEnabled = subPerm.children.filter(item => item.id == 'S002V01F03COVE')[0].access > 0;
        }catch(error: any){
          if(error.error == undefined){
            this.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else if(error.error.msg == undefined){
            this.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else{
            this.openSnackBar(error.error.msg);
          }
        }
      }
    });
  }

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

      if(priorities.error){
        this.errorStr = priorities.msg;
        this.hasError = true;
        this.isLoading = false;
      }else{
        this.orderPriorities = priorities.response.order_priorities;
        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 = error.error.msg;
      }

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

  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 getWorkOrders(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';

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

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

      let permissionsEnc = localStorage.getItem('permisos');
      let permissionsDec = await this._encService.decrypt(permissionsEnc!);
      let permissionsArr: Permissions = JSON.parse(permissionsDec);

      let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M10GMPR')[0];
      let subPerm = modPerm.children.filter(item => item.id == 'S002V01S01ORTR')[0];
      let funPerm = subPerm.children.filter(item => item.id == 'S002V01F01COTP')[0];

      this.createOrdersEnabled = funPerm.children.filter(item => item.id == 'S002V01P02ROTP')[0].access > 0;
      this.ordersHistoryEnabled = funPerm.children.filter(item => item.id == 'S002V01P01HOTP')[0].access > 0;
      this.copyOrderEnabled = subPerm.children.filter(item => item.id == 'S002V01F03COVE')[0].access > 0;

      if(!this.hasError){
        if(workOrders.response.length > 0){
          let orders: PreventiveWorkOrders[] = [];
          let cont = 0;
          workOrders.response.forEach(async (item) => {
            let idDec = await this._encService.decrypt(item.IDORDEN);
            let order: PreventiveWorkOrders = {
              IDORDEN: idDec,
              DESCRIPCION: item.DESCRIPCION,
              EQUIPO: item.EQUIPO,
              FECHAINICIO: item.FECHAINICIO,
              HORAINICIO: item.HORAINICIO,
              FECHAFINAL: item.FECHAFINAL,
              HORAFINAL: item.HORAFINAL,
              ACTIVATOR: item.ACTIVATOR,
              TIPOACTIVADOR: item.TIPOACTIVADOR,
              PRIORIDAD: item.PRIORIDAD,
              ESTATUS: item.ESTATUS,
            };
  
            orders.push(order);
            cont++;
            if(cont >= workOrders.response.length){
              this.dataSource = new MatTableDataSource(orders);
              this.dataSource.paginator = this.paginator!;
              this.dataSource.sort = this.sort!;
              this.isLoading = false;
            }
          });
        }else{
          let orders: PreventiveWorkOrders[] = [];
          this.dataSource = new MatTableDataSource(orders);
          this.isLoading = false;
        }
      }else{
        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.hasError = true;
      this.isLoading = false;
    }
  }

  getFormattedDate(date: string): string{
    let dateArr = date.split('-').reverse();
    return `${dateArr[0]} de ${this.MONTHS[parseInt(dateArr[1]) - 1]} del ${dateArr[2]}`;
  }

  async openWorkOrder(action: string, idOrder: number | null){
    if(action == 'nuevo'){
      this._router.navigate(['sam/GMPR/ORTR/COTP/nuevo']);
    }else{
      let idEnc = await this._encService.encrypt(`${idOrder}`);
      this._router.navigate(['sam/GMPR/ORTR/COTP/editar'], {
        queryParams: {
          idOrder: idEnc,
        }
      });
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500,
    });
  }

  getStatusText(status: string): string{
    if(status == 'B'){
      return "Borrador";
    }else if(status == 'R'){
      return "Revisión";
    }else if(status == 'A'){
      return "Activo";
    }else if(status == 'E'){
      return "Eliminado";
    }
    return "";
  }

  async openCopyDialog(idOrder: string, equipment: string){
    let dialogRef = this._dialog.open(CopyOrderComponent, {
      data: {
        idOrder: idOrder,
        equipment: equipment,
      },
      width: '480px'
    });

    dialogRef.afterClosed().subscribe((_) => {
      this.getWorkOrders();
    });
  }

  confirmReturn(id: number){
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '320px',
      disableClose: true,
      data: {
        title: '¡Confirmación requerida!',
        icon: 'warning',
        description: '¿Está seguro de ejecutar esta acción?',
        description2: 'Esta acción devolverá la orden al estado \'Borrador\' nuevamente.'
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ""){
        this.changeOrderStatus(id, 'B');
      }
    })
  }

  async changeOrderStatus(idOrder: number, newStatus: 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('status', newStatus);

      await lastValueFrom(this._prevMaintService.updateOrderStatus(formData));

      this.openSnackBar('La orden se actualizó correctamente.');
      this.getWorkOrders();
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

  async openAnalysisDialog(idOrder: number){
    let idEnc = await this._encService.encrypt(`${idOrder}`);
    this._router.navigate(['sam/GMPR/ORTR/COTP/analisis'], {
      queryParams: {
        data: idEnc,
      }
    })
  }

  openOrderDetails(idOrder: number){
    let dialogRef = this._dialog.open(OrderDetailsComponent, {
      width: '820px',
      data: {
        idOrder: idOrder,
      }
    })

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

  getPriorityStr(priorityStr: string): string{
    let priorityFiltered = this.orderPriorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "-";
    
    let priority = priorityFiltered[0];
    return priority.label;
  }

  getFontColor(priorityStr: string): string{
    let priorityFiltered = this.orderPriorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "rgb(0, 0, 0)";
    
    let priority = priorityFiltered[0];
    return priority.color;
  }

  openActionConfirm(idOrder: number){
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '480px',
      disableClose: true,
      data: {
        title: 'Confirmar acción',
        icon: 'warning',
        description: `¿Seguro que desea eliminar la orden de trabajo preventivo #${idOrder}?`,
        description2: 'Esta acción no se puede deshacer'
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res == true){
        this.deleteWorkOrder(idOrder);
      }
    });
  }

  async deleteWorkOrder(idOrder: number){
    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._prevMaintService.deleteWorkOrder(formData));
      
      this.openSnackBar('La orden se eliminó correctamente.');
      this.getWorkOrders();
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }
}
