import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DetailsProduct, GroupRequestLine } from 'src/app/interfaces/acquisition-management/acquisition/order.interface';

@Component({
  selector: 'app-info-group',
  templateUrl: './info-group.component.html',
  styleUrls: ['./info-group.component.css']
})
export class InfoGroupComponent implements OnInit {

  public formGroup: FormGroup;
  public dataSource:Array<DetailsProduct>;
  public displayedColumns: Array<string>;

  constructor(@Inject(MAT_DIALOG_DATA) public groupRequest: GroupRequestLine) {
    this.formGroup = this.createFormGroup();
    this.dataSource = groupRequest.PRODUCTOS;
    this.displayedColumns = ['NO','MODELO','CODIGO','CARACTERISTICAS','CANTIDAD','PRECIO_UNITARIO','PRECIO_TOTAL'];
  }

  ngOnInit(): void {
  }

  public getTotalCost() {
    return this.dataSource.map(t => t.PRECIO_TOTAL * t.CANTIDAD).reduce((acc, value) => acc + value, 0);
  }

  private createFormGroup(){
    let provider: string = this.groupRequest.PROVEEDOR;
    let date:string = this.groupRequest.FECHA_MODIFICA === null ? this.groupRequest.FECHA_REGISTRA : this.groupRequest.FECHA_MODIFICA;
    let user:string = this.groupRequest.USUARIO_MODIFICA === null ? this.groupRequest.USUARIO_REGISTRA : this.groupRequest.USUARIO_MODIFICA;
    let quantity: string = `${this.groupRequest.PRODUCTOS.length} ${this.groupRequest.PRODUCTOS.length === 1 ? 'producto' : 'productos'} ` ;
    let price: string = `$ ${this.groupRequest.PRECIO_TOTAL}`;
    let dispach: string = `${this.groupRequest.DESPACHO === '' ? 'Sin asignar' : this.groupRequest.DESPACHO}`;
    let method: string = `${this.groupRequest.METODO_PAGO === '' ? 'Sin asignar' : this.groupRequest.METODO_PAGO}`;
    let purpose: string = `${this.groupRequest.PROPOSITO === '' ? 'Sin asignar' : this.groupRequest.PROPOSITO}`;

    return new FormGroup({
      nombreProveedor: new FormControl(provider, Validators.required),
      cantidadProductos: new FormControl(quantity, Validators.required),
      precioTotal: new FormControl(price, Validators.required),
      fechaEmision: new FormControl(date, Validators.required),
      usuarioRegistro: new FormControl(user, Validators.required),
      despacho: new FormControl(dispach, Validators.required),
      metodoPago: new FormControl(method, Validators.required),
      proposito: new FormControl(purpose, Validators.required),
    });
  }
}
