import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { GetExecuteTask, RequestFormRequestWorkflow } from '../../../../interfaces/process-managementv/workflow-management.interface';
import { ResourcesService, ResponseData } from '../../../../services/resources.service';
import { InternationalizationService } from '../../../../services/internationalization/internationalization.service';
import { ProcessManagementService } from '../../../../services/process-management/process-management.service';
import { EncService } from '../../../../services/enc.service';
import { ShowInformationWorkflowComponent } from '../show-information-workflow/show-information-workflow.component';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-change-request-workflow',
    templateUrl: './change-request-workflow.component.html',
    styleUrl: './change-request-workflow.component.css',
    standalone: false
})
export class ChangeRequestWorkflowComponent implements OnInit {
  public isLoading: boolean;
  public formGroup: FormGroup;
  public isResponsible: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public requestWorkflow: GetExecuteTask,
    public resourcesService: ResourcesService,
    public interService: InternationalizationService,
    private _processManagementService: ProcessManagementService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<boolean>,
    private _encService: EncService,
    ) {
    this.isResponsible = false;
    this.isLoading = false;
    this.formGroup = this._createFormGroup();
  }

  private _createFormGroup(): FormGroup {
    return new FormGroup({
      'FLUJO': new FormControl(null),
      'TAREA': new FormControl(null),
      'PROCESO': new FormControl(null),
      'ESTADO': new FormControl({ value: null, disabled: this.requestWorkflow.ESTADO === 'En espera' && this.isResponsible }, Validators.required),
      'MENSAJE_RECHAZO': new FormControl({ value: null, disabled: true }, Validators.required),
    });
  }
  
  async ngOnInit() {
    this.isLoading = true;
    
    this.formGroup.controls['FLUJO'].setValue(this.requestWorkflow.NOMBRE_WORKFLOW);
    this.formGroup.controls['TAREA'].setValue(this.requestWorkflow.NOMBRE_TAREA);
    this.formGroup.controls['PROCESO'].setValue(this.requestWorkflow.NOMBRE_PROCESO);
    this.isLoading = false;

    this.formGroup.controls['ESTADO'].valueChanges.subscribe((state) => {
      if (state === 'Rechazado') {
        this.formGroup.controls['MENSAJE_RECHAZO'].enable();
      } else {
        this.formGroup.controls['MENSAJE_RECHAZO'].disable();
      }
    });

    const responsibleUser = this.requestWorkflow.USUARIO_RESPONSABLE.toString().trim();

    if (responsibleUser.includes('(')) {
      const idResponsibleUser = responsibleUser.split('(')[1].split(')')[0];
      const user: string = await this._encService.decrypt(this.resourcesService.getUser());
      this.isResponsible = user === idResponsibleUser;
    }
  
  }

  public async verInformacion() {    
    let encInfoForm: string = this.requestWorkflow.INFORMACION_FORMULARIO;    
    encInfoForm = encInfoForm.trim();
    let strInfoForm: string = await this._encService.decrypt(encInfoForm);
    strInfoForm = strInfoForm.trim();
    let arrInfoForm = JSON.parse(strInfoForm);    

    this._dialog.open(ShowInformationWorkflowComponent, {
      disableClose: true,
      width: '800px',
      maxWidth: '800px',
      data: arrInfoForm
    });
  }

  public save() {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        title: this.interService.get('confirmacion'),
        description: this.interService.get('update_request_alert'),
        icon: `warning`,
      }
    }).afterClosed().subscribe(async (result) => {
      if (result) {
        await this.updateRequestWorkflow();
      }
    });
  }

  public async updateRequestWorkflow() {

    const strExecuteTask: string =  this.requestWorkflow.ID_EJECUCION_TAREA.toString();
    const encExecuteTask: string = await this._encService.encrypt(strExecuteTask);

    let estado = this.formGroup.controls['ESTADO'].value;
    estado = estado.toString().trim();

    let mensajeRechazo = this.formGroup.controls['MENSAJE_RECHAZO'].value;
    if (mensajeRechazo !== null) {
      mensajeRechazo = mensajeRechazo.toString().trim();
    }

    const requestFormRequestWorkflow: RequestFormRequestWorkflow = {
      ESTADO: estado,
      MENSAJE_RECHAZO: mensajeRechazo,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
  
    }
    await lastValueFrom(this._processManagementService.updateRequestWorkflow(encExecuteTask, requestFormRequestWorkflow)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this._dialogRef.close(true);
          this.resourcesService.openSnackBar(`¡Modificación exitosa!`);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.updateRequestWorkflow();
        }
      }
    )
  }
}
