import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { CalendarEvent, CalendarEventsResponse } from '../../../interfaces/calendar-events.interface';
import { MatTableDataSource } from '@angular/material/table';
import { PreventiveWorkOrdersActive, PreventiveWorkOrdersActiveResponse } from '../../../interfaces/preventive-work-orders-active.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { PriorityInterface } from '../../system-admin/system-params/system-params.component';
import { DOCUMENT } from '@angular/common';
import { EncService } from '../../../services/enc.service';
import { PreventiveMaintenanceService } from '../../../services/preventive-maintenance.service';
import { FunctionsService } from '../../../services/functions.service';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { SystemAdminService } from '../../../services/system-admin.service';
import { lastValueFrom } from 'rxjs';
import { ResourcesService } from '../../../services/resources.service';
import { ExecutionDialogComponent } from './execution-dialog/execution-dialog.component';
import { OrderExecutionConfigComponent } from './order-execution-config/order-execution-config.component';
import { CompleteEventsComponent } from './complete-events/complete-events.component';

interface ActivatorType{
  name: string;
  checked: boolean;
  value: string;
  subactivators?: ActivatorType[];
}
interface CalendarDay{
  day: number,
  date: string,
  isActualMonth: boolean,
  isActualDay: boolean,
}
@Component({
    selector: 'app-active-orders',
    templateUrl: './active-orders.component.html',
    styleUrl: './active-orders.component.css',
    standalone: false
})
export class ActiveOrdersComponent implements OnInit {
  btnSmall: boolean = false;
  floatToolbar: boolean = false;
  txtBuscador:string;

  isLoading: boolean;
  hasError: boolean;
  gettingEvents: boolean;
  allActivatorsChecked: boolean;
  allStatesChecked: boolean;
  errorStr: string;
  actionTooltip: string;
  actionIcon: string;
  displayedScreen: string;
  selected?: Date | null;
  displayedMonth: number;
  displayedYear: number;
  currentDay: number;
  currentMonth: number;
  currentYear: number;
  monthDays: Array<Array<CalendarDay>>;
  calendarEvents: CalendarEvent[];

  MONTHS = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
  displayedColumns = ['ID', 'EQUIPO', 'FECINI', 'FECFIN', 'TIEEST', 'TIETOT', 'PRIORIDAD', 'TIPOACT'];
  dataSource?: MatTableDataSource<PreventiveWorkOrdersActive>;
  activeOrders: PreventiveWorkOrdersActive[];

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

  activators: ActivatorType = {
    name: 'Todos',
    checked: true,
    value: '',
    subactivators: [
      {name: 'Calendario', checked: true, value: 'C'},
      {name: 'Sintoma', checked: true, value: 'S'},
      {name: 'Medida', checked: true, value: 'M'},
      {name: 'Valor', checked: true, value: 'V'},
    ]
  };

  states: ActivatorType = {
    name: 'Todos',
    checked: true,
    value: '',
    subactivators: [
      {name: 'Programada', checked: true, value: 'P'},
      {name: 'Ejecución', checked: true, value: 'E'},
      {name: 'Finalizado', checked: true, value: 'F'},
      {name: 'Cancelación', checked: true, value: 'C'},
    ]
  };

  showToolbar: boolean;
  hiddingToolbar: boolean;
  showingToolbar: boolean;
  iconToogle: boolean;

  orderPriorities: PriorityInterface[];

  constructor(
    @Inject(DOCUMENT) private _document: Document,
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _funcService: FunctionsService,
    private _dialog: MatDialog,
    private _router: Router,
    private _sysAdminService: SystemAdminService,
    private _resourcesServices: ResourcesService,
  ) { 
    this.txtBuscador = '';
    this.isLoading = true;
    this.hasError = false;
    this.gettingEvents = false;
    this.allActivatorsChecked = true;
    this.allStatesChecked = true;
    this.errorStr = '';
    this.actionTooltip = '';
    this.actionIcon = '';
    this.displayedScreen = "CALEJE";
    this.selected = new Date();
    this.displayedMonth = 0;
    this.displayedYear = 0;
    this.currentDay = 0;
    this.currentMonth = 0;
    this.currentYear = 0;
    this.monthDays = [];
    this.calendarEvents = [];
    this.activeOrders = [];
    this.floatToolbar = window.innerWidth <= 1135;

    this.showToolbar = false;
    this.hiddingToolbar = false;
    this.showingToolbar = false;
    this.iconToogle = true;
    this.orderPriorities = [];
  }

  ngOnInit(): void {
    let now = new Date();
    this.displayedMonth = now.getMonth();
    this.displayedYear = now.getFullYear();
    this.currentDay = now.getDate();
    this.currentMonth = now.getMonth();
    this.currentYear = now.getFullYear();

    this.btnSmall = window.innerWidth <= 1405;
    this.getOrderPriorities();
    this.getPreventiveCalendar();
  }

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

      if(priorities.error){
        this.hasError = true;
        this.errorStr = priorities.msg;
        this.isLoading = false;
      }else{
        this.orderPriorities = priorities.response.order_priorities;
        this.getActiveWorkOrders();
      }
    }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{
        let msgArr = error.error.msg.split(':');
        if(msgArr[0] == 'ERR_GLB_USU003'){
          this.getOrderPriorities();
          return;
        }else{
          this.errorStr = error.error.msg;
        }
      }

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

  async getPreventiveCalendar(){
    try{
      this.monthDays = [];
      this.calendarEvents = [];
      this.calcCalendarDays();
      this.gettingEvents = true;

      let idUser = localStorage.getItem('idusuario')!;
      let monthDaysAux: Array<Array<CalendarDay>> = [];
      this.monthDays.forEach(item => monthDaysAux.push(item));

      let fecIni = monthDaysAux[0][0].date;
      let fecIniArr = fecIni.split('-').reverse();
      let fecIniStr = `${fecIniArr[0]}-`;

      fecIniStr += parseInt(fecIniArr[1]) + 1 < 10 ? `0${parseInt(fecIniArr[1]) + 1}-` : `${parseInt(fecIniArr[1]) + 1}-`;
      fecIniStr += parseInt(fecIniArr[2]) < 10 ? `0${parseInt(fecIniArr[2])}` : `${parseInt(fecIniArr[2])}`;

      let fecFinAux: Array<CalendarDay> = [];
      monthDaysAux.reverse()[0].forEach(item => fecFinAux.push(item));

      let fecFin = fecFinAux.reverse()[0].date;
      let fecFinArr = fecFin.split('-').reverse();
      let fecFinStr = `${fecFinArr[0]}-`;

      fecFinStr += parseInt(fecFinArr[1]) + 1 < 10 ? `0${parseInt(fecFinArr[1]) + 1}-` : `${parseInt(fecFinArr[1]) + 1}-`;
      fecFinStr += parseInt(fecFinArr[2]) < 10 ? `0${parseInt(fecFinArr[2])}` : `${parseInt(fecFinArr[2])}`;

      let events: CalendarEventsResponse = await lastValueFrom(this._prevMaintService.getPreventiveCalendar(fecIniStr, fecFinStr, idUser, 1));

      if(events.error){
        this._resourcesServices.openSnackBar(events.msg);
      }else{
        this.calendarEvents = events.response;
      }

      this.gettingEvents = false;
      this.updateAsyncColors();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesServices.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesServices.openSnackBar('Ocurrió un error inesperado.');
      }else{
        let msgArr = error.error.msg.split(':');
        if(msgArr[0] == 'ERR_GLB_USU003'){
          this.getPreventiveCalendar();
        }else{
          this._resourcesServices.openSnackBar(error.error.msg);
        }
      }

      this.gettingEvents = false;
    }
  }

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

      let idUser = localStorage.getItem('idusuario')!;
      let orders: PreventiveWorkOrdersActiveResponse = await lastValueFrom(this._prevMaintService.getActiveWorkOrders(idUser, 1));

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

      if(!this.hasError){
        this.activeOrders = orders.response;
        this.dataSource = new MatTableDataSource(orders.response);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;
      }

      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{
        let msgArr = error.error.msg.split(':');
        if(msgArr[0] == 'ERR_GLB_USU003'){
          this.getActiveWorkOrders();
          return;
        }else{
          this.errorStr = error.error.msg;
        }
      }

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

  calcCalendarDays(){
    let completeDays: string[] = [];
    let firstDay = new Date(this.displayedYear, this.displayedMonth, 1);
    let lastDay = new Date(this.displayedYear, this.displayedMonth + 1, 0);

    let dayInd = firstDay.getDay();
    let startDays: string[] = [];
    for(let i = dayInd; i > 0; i--){
      let dayNum = i - dayInd;
      let dayObj = new Date(this.displayedYear, this.displayedMonth, dayNum);

      startDays.push(`${dayObj.getDate()}-${dayObj.getMonth()}-${dayObj.getFullYear()}`);
    }

    startDays = startDays.reverse();
    startDays.forEach(day => completeDays.push(day));

    let fdNum = firstDay.getDate();
    let ldNum = lastDay.getDate();
    for(let i = fdNum; i <= ldNum; i++){
      completeDays.push(`${i}-${this.displayedMonth}-${this.displayedYear}`);
    }

    let indLast = lastDay.getDay();
    if(indLast < 6){
      let cont = 1;
      for(let i = indLast; i < 6; i++){
        let dayObj = new Date(this.displayedYear, this.displayedMonth, ldNum + cont);
        completeDays.push(`${dayObj.getDate()}-${dayObj.getMonth()}-${dayObj.getFullYear()}`)
        cont++;
      }
    }

    let rows = completeDays.length / 7;
    let cont = 0;
    let currentDate = new Date();

    for(let i = 0; i < rows; i++){
      let rowDays: CalendarDay[] = [];

      for(let j = 0; j < 7; j++){
        let dayArr = completeDays[cont].split('-');
        
        let dayObj: CalendarDay = {
          day: parseInt(dayArr[0]),
          date: completeDays[cont],
          isActualMonth: parseInt(dayArr[1]) == this.displayedMonth && parseInt(dayArr[2]) == this.displayedYear,
          isActualDay: parseInt(dayArr[0]) == currentDate.getDate() && parseInt(dayArr[1]) == currentDate.getMonth() && parseInt(dayArr[2]) == currentDate.getFullYear(),
        };
        
        rowDays.push(dayObj);
        cont++;
      }

      this.monthDays.push(rowDays);
    }
  }

  updateAsyncColors(){
    setTimeout(() => {
      this.states.subactivators?.forEach(item => {
        let checkBox = this._document.getElementById(`c_box_${item.value}`);
        
        switch(item.value){
          case "P": 
            checkBox?.children[0].children[0].children[3].classList.add('amber_primary_background'); 
            checkBox?.children[0].children[0].children[3].classList.add('amber_primary_border'); 
          break;
          case "E": 
            checkBox?.children[0].children[0].children[3].classList.add('blue_primary_background'); 
            checkBox?.children[0].children[0].children[3].classList.add('blue_primary_border'); 
          break;
          case "F": 
            checkBox?.children[0].children[0].children[3].classList.add('green_primary_background'); 
            checkBox?.children[0].children[0].children[3].classList.add('green_primary_border'); 
          break;
          case "C": 
            checkBox?.children[0].children[0].children[3].classList.add('red_primary_background'); 
            checkBox?.children[0].children[0].children[3].classList.add('red_primary_border'); 
          break;
        }
      });
    }, 250);
  }

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

  animateToolbar(){
    if(this.showToolbar){
      this.hiddingToolbar = true;
      this.iconToogle = true;
      setTimeout(() => {
        this.showToolbar = false;
        this.hiddingToolbar = false;
      }, 500);
    }else{
      this.showingToolbar = true;
      this.iconToogle = false;
      setTimeout(() => {
        this.showToolbar = true;
        this.showingToolbar = false;
      }, 500);
    }
  }

  changeDisplayedMonth(action: string){
    if(action == 'backward'){
      let month = this.displayedMonth - 1;
      if(month < 0){
        this.displayedMonth = 11;
        this.displayedYear--;
      }else{
        this.displayedMonth = month;
      }
    }else if(action == 'forward'){
      let month = this.displayedMonth + 1;
      if(month > 11){
        this.displayedMonth = 0;
        this.displayedYear++;
      }else{
        this.displayedMonth = month;
      }
    }else if(action == 'today'){
      let now = new Date();
      this.displayedYear = now.getFullYear();
      this.displayedMonth = now.getMonth();
    }else if(action == 'calendar'){
      this.displayedYear = this.selected?.getFullYear()!;
      this.displayedMonth = this.selected?.getMonth()!;
    }

    this.getPreventiveCalendar();
  }

  screenChange(event: any){
    if(event != undefined){
      this.displayedScreen = event;
    }
  }

  someActivatorsChecked(): boolean{
    if(this.activators.subactivators == null){
      return false;
    }
    return this.activators.subactivators.filter(t => t.checked).length > 0 && !this.allActivatorsChecked;
  }

  setAllActivators(completed: boolean){
    this.allActivatorsChecked = completed;
    if(this.activators.subactivators == null){
      return;
    }
    this.activators.subactivators.forEach(t => (t.checked = completed));
  }

  updateAllActivatorsChecked(){
    this.allActivatorsChecked = this.activators.subactivators != null && this.activators.subactivators.every(t => t.checked);
  }

  someStatesChecked(): boolean{
    if(this.states.subactivators == null){
      return false;
    }
    return this.states.subactivators.filter(t => t.checked).length > 0 && !this.allStatesChecked;
  }

  setAllStates(completed: boolean){
    this.allStatesChecked = completed;
    if(this.states.subactivators == null){
      return;
    }
    this.states.subactivators.forEach(t => {
      (t.checked = completed);
      this.updateSyncColor(t.value);
    });
  }

  updateSyncColor(value: string){
    let checkBox = this._document.getElementById(`c_box_${value}`);
    let val = this.states.subactivators?.filter(item => item.value == value)[0];

    if(val?.checked){
      switch(val.value){
        case "P": 
          checkBox?.children[0].children[0].children[3].classList.add('amber_primary_background'); 
          checkBox?.children[0].children[0].children[3].classList.add('amber_primary_border'); 
        break;
        case "E": 
          checkBox?.children[0].children[0].children[3].classList.add('blue_primary_background'); 
          checkBox?.children[0].children[0].children[3].classList.add('blue_primary_border'); 
        break;
        case "F": 
          checkBox?.children[0].children[0].children[3].classList.add('green_primary_background'); 
          checkBox?.children[0].children[0].children[3].classList.add('green_primary_border'); 
        break;
        case "C": 
          checkBox?.children[0].children[0].children[3].classList.add('red_primary_background'); 
          checkBox?.children[0].children[0].children[3].classList.add('red_primary_border'); 
        break;
      }
    }else{
      switch(val!.value){
        case "P": 
          checkBox?.children[0].children[0].children[3].classList.remove('amber_primary_background'); 
          checkBox?.children[0].children[0].children[3].classList.remove('amber_primary_border'); 
        break;
        case "E": 
          checkBox?.children[0].children[0].children[3].classList.remove('blue_primary_background'); 
          checkBox?.children[0].children[0].children[3].classList.remove('blue_primary_border'); 
        break;
        case "F": 
          checkBox?.children[0].children[0].children[3].classList.remove('green_primary_background'); 
          checkBox?.children[0].children[0].children[3].classList.remove('green_primary_border'); 
        break;
        case "C": 
          checkBox?.children[0].children[0].children[3].classList.remove('red_primary_background'); 
          checkBox?.children[0].children[0].children[3].classList.remove('red_primary_border'); 
        break;
      }
    }
  }

  updateAllStatesChecked(){
    this.allStatesChecked = this.states.subactivators != null && this.states.subactivators.every(t => t.checked);
  }

  isSelected(row: number, col: number): boolean{
    let rowSel = this.monthDays[row];
    let dayArr = rowSel[col].date.split('-').reverse();
    let dayObj = new Date(parseInt(dayArr[0]), parseInt(dayArr[1]), parseInt(dayArr[2]));
    let selected = new Date(this.selected?.getFullYear()!, this.selected?.getMonth()!, this.selected?.getDate()!);
    
    return +dayObj == +selected!;
  }

  getDayEvents(i: number, j: number): CalendarEvent[]{
    let day = this.monthDays[i][j];
    let dateArr = day.date.split('-').reverse();
    let dateStr = `${dateArr[0]}-`;

    dateStr += parseInt(dateArr[1]) + 1 < 10 ? `0${parseInt(dateArr[1]) + 1}-` : `${parseInt(dateArr[1]) + 1}-`;
    dateStr += parseInt(dateArr[2]) < 10 ? `0${parseInt(dateArr[2])}` : `${parseInt(dateArr[2])}`;

    let dayEvents = this.calendarEvents.filter(event => event.DATE == dateStr);
    let events: CalendarEvent[] = [];
    let cont = 0;
    dayEvents.forEach(event => {
      let status = event.REGEST == 'Ejecucion' ? 'Ejecución' : event.REGEST;
      status = status == 'Cancelacion' ? 'Cancelación' : status;
      
      let statusChecked = this.states.subactivators?.filter(item => item.name == status)[0].checked;
      let typeChecked = this.activators.subactivators?.filter(item => item.name == event.TYPE)[0].checked;

      if(statusChecked && typeChecked && events.length < 5){
        events.push(event);
      }

      if(cont == 6 && events.length >= 5){
        let seeMore: CalendarEvent = {
          IDORDEN: '0',
          EVENTCOLOR: 'rgba(0, 0, 0, 0)',
          DATE: '',
          TYPE: '',
          REGEST: '',
          SEEMORE: true,
        };

        events.push(seeMore);
      }
      cont++;
    });

    return events;
  }

  openExecution(idOrder: string, status: string, i: number, j: number){
    let date = this.monthDays[i][j].date;
    let dateArr = date.split('-').reverse();
    let dateStr = `${dateArr[0]}-`;

    dateStr += parseInt(dateArr[1]) + 1 < 10 ? `0${parseInt(dateArr[1]) + 1}-` : `${parseInt(dateArr[1]) + 1}-`;
    dateStr += parseInt(dateArr[2]) < 10 ? `0${parseInt(dateArr[2])}` : `${parseInt(dateArr[2])}`;
    if(status != 'Programada'){
      dateStr = `${dateStr}|R`;
    }else{
      dateStr = `${dateStr}|O`;
    }

    let dialogRef = this._dialog.open(ExecutionDialogComponent, {
      width: '480px',
      maxWidth: '480px',
      data: {
        idOrder: idOrder,
        date: dateStr,
      }
    });

    let order = this.activeOrders.filter(item => item.IDORDEN == idOrder)[0];
    let startHour = order.FECHAINICIO.split(' ')[1];

    dialogRef.afterClosed().subscribe(res => {
      if(res != '' && res != undefined && res != null){
        let resArr = res.split('|');
        if(res == 'execute'){
          this.openOrderExecutionConfig(idOrder, true, `${dateStr} ${startHour}`)
        }else if(resArr[0] == 'end'){
          this.endExecution(idOrder, dateStr, resArr[2], resArr[1]);
        }else if(resArr[0] == 'cancel'){
          this.cancelOrderExecution(idOrder, dateStr, resArr[1]);
        }
      }
    });
  }

  openOrderExecutionConfig(idOrder: string, isCalendar: boolean, date: string){
    let dialogRef = this._dialog.open(OrderExecutionConfigComponent, {
      disableClose: true,
      width: '640px',
      maxWidth: '640px',
      data: {
        idOrder: idOrder,
        date: date,
      }
    });

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

  async endExecution(idOrder: string, date: string, idReg: string, observations: 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('execution_date', date);
      formData.append('id_reg', idReg);
      formData.append('observations', observations);

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

      this._resourcesServices.openSnackBar(`La ejecución de la orden #${idOrder} para la fecha ${date} fue finalizada correctamente.`);
      this.getPreventiveCalendar();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesServices.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesServices.openSnackBar('Ocurrió un error inesperado.');
      }else{
        let msgArr = error.error.msg.split(':');
        if(msgArr[0] == 'ERR_GLB_USU003'){
          this.endExecution(idOrder, date, idReg, observations);
        }else{
          this._resourcesServices.openSnackBar(error.error.msg);
        }
      }
    }
  }

  async cancelOrderExecution(idOrder: string, date: string, observations: 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('execution_date', date);
      formData.append('observations', observations);

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

      this._resourcesServices.openSnackBar(`La ejecucución del día ${date} fue cancelada correctamente`);
      this.getPreventiveCalendar();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesServices.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesServices.openSnackBar('Ocurrió un error inesperado.');
      }else{
        let msgArr = error.error.msg.split(':');
        if(msgArr[0] == 'ERR_GLB_USU003'){
          this.cancelOrderExecution(idOrder, date, observations);
        }else{
          this._resourcesServices.openSnackBar(error.error.msg);
        }
      }
    }
  }

  private async activateWorkOrder(idOrder: string, isCalendar: boolean, date: string, configuration: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let now = new Date();
      let formData = new FormData();
      let idOrderEnc = await this._encService.encrypt(`${idOrder}`);

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

      if(isCalendar){
        formData.append('execution_date', date!);
      }else{
        formData.append('execution_date', `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`);
      }

      await lastValueFrom(this._prevMaintService.executePreventiveWorkOrder(formData));
      
      this._resourcesServices.openSnackBar(`La orden #${idOrder} se ejecutó correctamente.`);
      this.getPreventiveCalendar();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesServices.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesServices.openSnackBar('Ocurrió un error inesperado.');
      }else{
        let msgArr = error.error.msg.split(':');
        if(msgArr[0] == 'ERR_GLB_USU003'){
          this.activateWorkOrder(idOrder, isCalendar, date, configuration);
        }else{
          this._resourcesServices.openSnackBar(error.error.msg);
        }
      }
    }
  }

  openAllEvents(i: number, j: number){
    let day = this.monthDays[i][j];
    let dateArr = day.date.split('-').reverse();
    let dateStr = `${dateArr[0]}-`;

    dateStr += parseInt(dateArr[1]) + 1 < 10 ? `0${parseInt(dateArr[1]) + 1}-` : `${parseInt(dateArr[1]) + 1}-`;
    dateStr += parseInt(dateArr[2]) < 10 ? `0${parseInt(dateArr[2])}` : `${parseInt(dateArr[2])}`;

    let dayEvents = this.calendarEvents.filter(event => event.DATE == dateStr);
    let dialogRef = this._dialog.open(CompleteEventsComponent, {
      width: '560px',
      maxWidth: '560px',
      data: {
        events: dayEvents,
        dateStr: dateStr
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != '' && res != undefined && res != null){
        let resArr = res.split('|');
        let idOrder = resArr[0];
        let order = this.activeOrders.filter(item => item.IDORDEN == idOrder)[0];
        let startHour = order.FECHAINICIO.split(' ')[1];
        
        if(resArr[1] == 'execute'){
          this.openOrderExecutionConfig(idOrder, true, `${dateStr} ${startHour}`);
        }else if(resArr[1] == 'end'){
          this.endExecution(idOrder, dateStr, resArr[3], resArr[2]);
        }else if(resArr[1] == 'cancel'){
          this.cancelOrderExecution(idOrder, dateStr, resArr[2]);
        }
      }
    });
  }

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

  registerVisit(){
    this._router.navigate(['sam/GMPR/AOTR/RVTP/register']); 
  }

  orderDate(date: string): string{
    return this._funcService.orderDate(date)!;
  }

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