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

const ID_MODULE = "S002V01M10GMPR";
@Component({
    selector: 'app-work-orders',
    templateUrl: './work-orders.component.html',
    styleUrl: './work-orders.component.css',
    standalone: false
})
export class WorkOrdersComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  filterEquipment: boolean;
  equipmentFiltered: string;

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

  dataSource?: MatTableDataSource<PreventiveWorkOrders>;
  displayedColumns = ['ID', 'EQUIPO', 'FECINI', 'FECFIN', '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 _dialog: MatDialog,
    private _sysAdminService: SystemAdminService,
    private _functionsService: FunctionsService,
    private _resourcesService: ResourcesService,
    private _activatedRoute: ActivatedRoute,
  ) { 
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.filterEquipment = false;
    this.txtBuscador = '';
    this.equipmentFiltered = '';

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

  ngOnInit(): void {
    this._activatedRoute.queryParams.subscribe(params => {
      let data = params['data'];
      if(data != undefined){
        this.filterEquipment = true;
        this.equipmentFiltered = data;
      }
    });

    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(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._resourcesService.openSnackBar('0001: Ocurrió un error al actualizar su perfil');
          }else if(error.error.msg == undefined){
            this._resourcesService.openSnackBar('0002: Ocurrió un error al actualizar su perfil');
          }else{
            this._resourcesService.openSnackBar(error.error.msg);
          }
        }
      }
    });

    this._socketService.refreshModules().subscribe(async () => this._functionsService.consultModuleStatus(ID_MODULE));
  }

  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{
        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.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 = error.error.msg;
      }

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

  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){
        let workOrdersArr: PreventiveWorkOrders[] = [];
        for(const order of workOrders.response){
          order.IDORDEN = await this._encService.decrypt(order.IDORDEN);
          order.EQUIPO = await this._encService.decrypt(order.EQUIPO);
          order.ESTATUS = this.getStatusText(order.ESTATUS);

          if(order.ACTIVADOR != null){
            order.ACTIVADOR = await this._encService.decrypt(order.ACTIVADOR);
          }

          if(order.FECHAINICIO != null){
            order.FECHAINICIO = this._functionsService.orderDate(order.FECHAINICIO);
          }

          if(order.FECHAFINAL != null){
            order.FECHAFINAL = this._functionsService.orderDate(order.FECHAFINAL);
          }

          if(order.PRIORIDAD != null){
            let priorityDec = await this._encService.decrypt(order.PRIORIDAD);
            for(const priority of this.orderPriorities){
              let valueDec = await this._encService.decrypt(priority.value);
              if(priorityDec == valueDec){
                order.PRIORIDAD_OBJ = priority;
              }
            }
          }

          workOrdersArr.push(order);
        }

        this.dataSource = new MatTableDataSource(workOrdersArr);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;
      }
      
      this.isLoading = false;
      if(this.filterEquipment){
        this.initEquipmentSearch();
      }
    }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 = error.error.msg;
      }

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

  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 initEquipmentSearch(){
    let equipmentCode = await this._encService.decrypt(this.equipmentFiltered);
    this.applyFilter(equipmentCode, 'AUT');
  }

  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();
    }
  }

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

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

  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,
        }
      });
    }
  }

  confirmReturn(id: number){
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '320px',
      maxWidth: '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._resourcesService.openSnackBar('La orden se actualizó 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);
      }
    }
  }

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

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

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

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

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

  openActionConfirm(idOrder: number){
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '480px',
      maxWidth: '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._resourcesService.openSnackBar('La orden 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);
      }
    }
  }
}
