import { Component, Inject, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { PriorityInterface } from '../../system-admin/system-params/system-params.component';
import { AssociatedWorkOrder, AssociatedWorkOrdersResponse } from '../../../interfaces/associated-work-orders.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { GdelService } from '../../../services/gdel.service';
import { SystemAdminService } from '../../../services/system-admin.service';
import { PreventiveMaintenanceService } from '../../../services/preventive-maintenance.service';
import { lastValueFrom } from 'rxjs';
import { PreventiveWorkOrdersActiveResponse } from '../../../interfaces/preventive-work-orders-active.interface';
import { ResourcesService } from '../../../services/resources.service';

@Component({
    selector: 'app-order-associaton',
    templateUrl: './order-associaton.component.html',
    styleUrl: './order-associaton.component.css',
    standalone: false
})
export class OrderAssociatonComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  idFile: string;

  displayedColumns = ['ID', 'EQUIPAMIENTO', 'ACTIVADOR', 'CLASIFICACION', 'PRIORIDAD', 'ACCIONES'];
  dataSource: MatTableDataSource<AssociatedWorkOrder>;
  orderPriorities: PriorityInterface[];

  dataSourceOrders: MatTableDataSource<AssociatedWorkOrder>;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _gdelService: GdelService,
    private _sysAdminService: SystemAdminService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _resourcesService: ResourcesService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.idFile = '';

    this.dataSource = new MatTableDataSource();
    this.orderPriorities = [];

    this.dataSourceOrders = new MatTableDataSource();
  }

  ngOnInit(): void {
    this.idFile = this._data.idFile;
    this.getAssociatedOrders();
  }

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

      let idUser = localStorage.getItem('idusuario')!;
      let idFileEnc = await this._encService.encrypt(this.idFile)!;

      let orders: AssociatedWorkOrdersResponse = await lastValueFrom(this._gdelService.getAssociatedWorkOrders(
        idFileEnc,
        idUser,
        1
      ));

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

      if(this.hasError){
        this.isLoading = false
      }else{
        this.dataSource = new MatTableDataSource(orders.response);
        this.getPriorities();
      }
    }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 getPriorities(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let priorities = await lastValueFrom(this._sysAdminService.getOrderPriorities(idUser, 1));

      if(priorities.error){
        this.hasError = priorities.error;
        this.errorStr = priorities.msg;
        this.isLoading = false;
      }else{
        this.orderPriorities = priorities.response.order_priorities;
        this.getActiveOrders();
      }
    }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 getActiveOrders(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let activeOrders: PreventiveWorkOrdersActiveResponse = await lastValueFrom(this._prevMaintService.getActiveWorkOrders(idUser, 1));

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

      if(!this.hasError){
        let nonAssociatedOrders: AssociatedWorkOrder[] = [];
        let associatedOrders = this.dataSource.data;

        activeOrders.response.forEach(order => {
          let filt = associatedOrders.filter(item => order.IDORDEN == item.IDORDEN);
          if(filt.length <= 0){
            let nonAssociatedOrder: AssociatedWorkOrder = {
              IDORDEN: order.IDORDEN,
              EQUIPAMIENTO: order.EQUIPAMIENTO,
              ACTIVADOR: order.ACTIVADOR,
              CLASIFICACION: order.CLASIFICACION,
              PRIORIDAD: order.PRIORIDAD,
              TIPOACTIVADOR: order.TIPOACTIVADOR
            };

            nonAssociatedOrders.push(nonAssociatedOrder);
          }
        });

        this.dataSourceOrders = new MatTableDataSource(nonAssociatedOrders);
      }

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

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

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

  async changeAssociationStatus(newStatus: string, idOrder: number){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idFileEnc = await this._encService.encrypt(this.idFile);
      let idOrderEnc = await this._encService.encrypt(`${idOrder}`);
      let formData = new FormData();

      formData.append('id_user', idUser!);
      formData.append('linea', '1');
      formData.append('id_file', idFileEnc);
      formData.append('action', newStatus);
      formData.append('id_order', idOrderEnc);

      await lastValueFrom(this._gdelService.changeAssociationStatus(formData));

      this._resourcesService.openSnackBar('La asociación del documento se actualizó correctamente');
      this.getAssociatedOrders();
    }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);
      }
    }
  }
}
