import { HttpErrorResponse } from '@angular/common/http';
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 { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { DispatchData, ResponseDataDispatch } from 'src/app/interfaces/acquisition-management/dispatch.interface';
import { RequestLines, RequestOrder } from 'src/app/interfaces/acquisition-management/order.interface';
import { PreventiveWorkOrdersActive, PreventiveWorkOrdersActiveResponse } from 'src/app/interfaces/preventive-work-orders-active.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { DispatchService } from 'src/app/services/acquisition-management/dispatch.service';
import { OrderService } from 'src/app/services/acquisition-management/order.service';
import { PreventiveMaintenanceService } from 'src/app/services/preventive-maintenance.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-form-purchase-line',
  templateUrl: './form-purchase-line.component.html',
  styleUrls: ['./form-purchase-line.component.css']
})
export class FormPurchaseLineComponent implements OnInit {
  public arrPreventiveMaintenance: Array<PreventiveWorkOrdersActive>;
  public arrCorrectiveMaintenance: Array<any>;
  public arrProject: Array<any>;
  public formGroup: FormGroup;
  public arrDispatch: Array<DispatchData>;
  public isLoadingForm: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public requestLines: RequestLines,
    public resourcesService: ResourcesService,
    private _preventiveMaintenanceService: PreventiveMaintenanceService,
    private _dialogRef: MatDialogRef<boolean>,
    private _dialog: MatDialog,
    private _orderService: OrderService,
    private _router: Router,
    private _distpachService: DispatchService,
  ) {
    this.arrPreventiveMaintenance = [];
    this.arrCorrectiveMaintenance = [];
    this.arrProject = [];
    this.arrDispatch = [];
    this.formGroup = this.createFormGroup();
    this.isLoadingForm = true;
    
  }
  async ngOnInit() {
    this.isLoadingForm = true;
    await this.getPreventiveMaintenance();
    await this.getDispatchActive();
    this.isLoadingForm = false;
  }

  private createFormGroup() {
    return new FormGroup({
      PROPOSITO: new FormControl( 'NA', Validators.required),
      DESPACHO: new FormControl( '', Validators.required),
    });
  }

  public alert() {
    this._dialog.open(AlertComponent, {
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de registrar la orden de compra?`,
        icon: `warning`,
      }
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.createOrder()
      }
    });
  }

  private async createOrder() {
    this.isLoadingForm = true;
    const objRequestOrder: RequestOrder = await this.createRequestOrder();    
    await lastValueFrom(this._orderService.generateOrders(objRequestOrder)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Registro de Orden Exitosa!`);
          this._router.navigate(['/sam/GEAD/ADQU/SEPE']);
          this._dialogRef.close(true);
        } else {
          this.resourcesService.openSnackBar(`${responseData.error}`);
        }
      }, (httpErrorResponse:HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoadingForm = false;
  }

  private async createRequestOrder():Promise<RequestOrder> {
    let requestOrder:RequestOrder = {
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
      NUMERO_SOLICITUD: this.requestLines.LINE_IDLI.toString(),
      DESPACHO: this.formGroup.controls['DESPACHO'].value,
      USUARIO: this.resourcesService.getUser(),
    }
    return requestOrder;
  }

  private async getPreventiveMaintenance() {
    const idUser:string = this.resourcesService.getUser();
    const line:number = parseInt(this.resourcesService.getLineNumber());
    await lastValueFrom(this._preventiveMaintenanceService.getActiveWorkOrders(idUser, line)).then(
      (responseData: PreventiveWorkOrdersActiveResponse) => {
        if ( !responseData.error ) {
          this.arrPreventiveMaintenance = responseData.response;          
          if (this.arrPreventiveMaintenance.length > 0) {
            this.arrProject.push({
              codeMaintenance: 'MTPR',
              typeMaintenance: 'Mantenimiento Preventivo',
              dataMaintenance: this.arrPreventiveMaintenance
            });
          }
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      },(error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  private async getDispatchActive() {
    await lastValueFrom(this._distpachService.getDispatchActive()).then(
      (responseData: ResponseDataDispatch) => {
        if ( !responseData.error ) {
          this.arrDispatch = responseData.response;
          if (this.arrDispatch.length === 0) {
            this.resourcesService.openSnackBar('No hay Despachos registrados en SAM');
          }
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      },(error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }
}
