import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';

@Component({
  selector: 'app-workflow-fields-form',
  templateUrl: './workflow-fields-form.component.html',
  styleUrls: ['./workflow-fields-form.component.css'],
})
export class WorkflowFieldsFormComponent implements OnInit {
  formGroup: FormGroup;
  modules: any[] = [];
  fields: any[] = [
    /*   {
      id: 'ARTCOD',
      max: 10,
      tag: 'input',
      icon: null,
      name: 'Codigo del articulo',
      type: 'text',
      label: 'Código del Artículo',
      value: null,
      column: 'ARTCOD',
      num_col: 1,
      num_row: 1,
      pattern: null,
      disabled: false,
      readonly: false,
      required: true,
      placeholder: 'Ingrese el código del artículo',
    },
    {
      id: 'ARTMOD',
      max: 45,
      tag: 'input',
      icon: null,
      name: 'Modelo del articulo',
      type: 'text',
      label: 'Modelo del Artículo',
      value: null,
      column: 'ARTMOD',
      num_col: 1,
      num_row: 1,
      pattern: null,
      disabled: false,
      readonly: false,
      required: true,
      placeholder: 'Ingrese el modelo del artículo',
    },
    {
      id: 'ARTNOM',
      max: 45,
      tag: 'input',
      icon: null,
      name: 'Nombre del artículo',
      type: 'text',
      label: 'Nombre del Artículo',
      value: null,
      column: 'ARTNOM',
      num_col: 1,
      num_row: 1,
      pattern: null,
      disabled: false,
      readonly: false,
      required: true,
      placeholder: 'Nombre del artículo',
    },
    {
      id: 'ARTCAN',
      max: 45,
      tag: 'input',
      icon: null,
      name: 'Cantidad en stock',
      type: 'number',
      label: 'Cantidad en Stock',
      value: null,
      column: 'ARTCAN',
      num_col: 1,
      num_row: 1,
      pattern: null,
      disabled: false,
      readonly: false,
      required: false,
      placeholder: 'Ingrese la cantidad en stock',
    },
    {
      id: 'ARTDES',
      max: 200,
      tag: 'textarea',
      icon: null,
      name: 'Descripción del artículo',
      type: 'text',
      label: 'Descripción del artículo',
      value: null,
      column: 'ARTDES',
      height: 80,
      num_col: 2,
      num_row: 2,
      pattern: null,
      disabled: false,
      readonly: false,
      required: true,
      placeholder: 'Ingrese la descripción del artículo',
    },
    {
      id: 'ARTCPR',
      max: 200,
      tag: 'textarea',
      icon: null,
      name: 'Características principales',
      type: 'text',
      label: 'Características Principales',
      value: null,
      column: 'ARTCPR',
      height: 80,
      num_col: 1,
      num_row: 2,
      pattern: null,
      disabled: false,
      readonly: false,
      required: true,
      placeholder: 'Ingrese las características principales',
    },
    {
      id: 'ARTCSE',
      max: 200,
      tag: 'textarea',
      icon: null,
      name: 'Características secundarias',
      type: 'text',
      label: 'Características Secundarias',
      value: null,
      column: 'ARTCSE',
      height: 80,
      num_col: 1,
      num_row: 2,
      pattern: null,
      disabled: false,
      readonly: false,
      required: false,
      placeholder: 'Ingrese las características secundarias',
    },
    {
      id: 'ID_CARID',
      tag: 'select',
      icon: null,
      name: 'Categoria',
      label: 'Categoría',
      column: 'id_CATID',
      num_col: 1,
      num_row: 1,
      disabled: false,
      required: true,
      table_rel: {
        CODIGO_TABLA: 2,
        NOMBRE_TABLA: 'categoria',
      },
      column_rel: 'CATNOM',
      data_select: [
        {
          valor: 1,
          opcion: 'Categoría 1',
        },
      ],
      group_select: false,
      multi_select: false,
    },
    {
      id: 'ID_PROVID',
      tag: 'select',
      icon: null,
      name: 'Proveedor',
      label: 'Proveedor',
      column: 'id_PROVID',
      num_col: 1,
      num_row: 1,
      disabled: false,
      required: true,
      table_rel: {
        CODIGO_TABLA: 3,
        NOMBRE_TABLA: 'proveedor',
      },
      column_rel: 'PROVCOD',
      data_select: [
        {
          valor: 1,
          opcion: 'CODPROVJJB',
        },
      ],
      group_select: false,
      multi_select: false,
    },
    {
      id: 'PROVCOD',
      max: 10,
      tag: 'input',
      icon: null,
      name: 'Codigo del proveedor',
      type: 'text',
      label: 'Código del proveedor',
      value: null,
      column: 'PROVCOD',
      num_col: 1,
      num_row: 1,
      pattern: null,
      disabled: false,
      readonly: false,
      required: true,
      placeholder: 'Ingrese el código del proveedor',
    },
    {
      id: 'PROVNOM',
      max: 45,
      tag: 'input',
      icon: null,
      name: 'Nombre',
      type: 'text',
      label: 'Nombre',
      value: null,
      column: 'PROVNOM',
      num_col: 1,
      num_row: 1,
      pattern: null,
      disabled: false,
      readonly: false,
      required: true,
      placeholder: 'Ingrese el nombre del proveedor',
    },
    {
      id: 'PROVAPE',
      max: 45,
      tag: 'input',
      icon: null,
      name: 'Apellido',
      type: 'text',
      label: 'Apellidos',
      value: null,
      column: 'PROVAPE',
      num_col: 1,
      num_row: 1,
      pattern: null,
      disabled: false,
      readonly: false,
      required: true,
      placeholder: 'Ingrese los apellidos del proveedor',
    },
    {
      id: 'PROVEMP',
      max: 100,
      tag: 'input',
      icon: null,
      name: 'Empresa',
      type: 'text',
      label: 'Empresa',
      value: null,
      column: 'PROVEMP',
      num_col: 1,
      num_row: 1,
      pattern: null,
      disabled: false,
      readonly: false,
      required: false,
      placeholder: 'Ingrese el nombre de la empresa',
    }, */
  ];
  value: any[] = [];
  selectAll = false;

  users: any[] = [
    { id: 'SAM001', name: 'Alan Garcia' },
    { id: 'SAM002', name: 'Alan Carranza' },
    { id: 'SAM003', name: 'Jorge Fierro' },
    { id: 'SAM004', name: 'Fer Alpuche' },
    { id: 'SAM005', name: 'Jean Jairo' },
    { id: 'SAM006', name: 'Omar Antunez' },
    { id: 'SAM007', name: 'Jose Luis' },
  ];

  constructor(
    public dialogRef: MatDialogRef<any>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.fields = data.fields;

    this.formGroup = this.createFormGroup();
  }

  ngOnInit(): void {}

  private createFormGroup() {
    if (this.data.action == 'Registrar') {
      return new FormGroup({
        field: new FormControl(null, Validators.required),
        employeesValidate: new FormControl([], Validators.required),
        sequence: new FormControl(null),
        nextSequence: new FormControl(null),
        is_Available: new FormControl(null),
        isNotified: new FormControl(false),
      });
    } else {
      let fieldPosition = this.fields.findIndex((object: any) => {
        return object.id == this.data.item.id;
      });

      return new FormGroup({
        field: new FormControl(this.fields[fieldPosition], Validators.required),
        employeesValidate: new FormControl(
          this.employeesValidateBox(),
          Validators.required
        ),
        sequence: new FormControl(null),
        nextSequence: new FormControl(null),
        is_Available: new FormControl(this.data.item.isAvailable),
        isNotified: new FormControl(this.data.item.isNotified),
      });
    }
  }

  sendData(form: any) {
    if (this.data.action == 'Registrar') {
      let objAux = form.field;
      objAux.employeesValidate = form.employeesValidate;
      objAux.sequence = null;
      objAux.nextSequence = null;
      objAux.isAvailable = true;
      objAux.isNotified = this.isNotified?.value;
      this.dialogRef.close(objAux);
    } else {
      let objAux = form.field;
      objAux.employeesValidate = form.employeesValidate;
      objAux.sequence = this.data.item.sequence;
      objAux.nextSequence = this.data.item.nextSequence;
      objAux.isAvailable = this.data.item.isAvailable;
      objAux.isNotified = this.isNotified?.value;
      this.dialogRef.close(objAux);
    }
  }

  valueChange(id: any) {
    if (this.value.indexOf(id) > -1) {
      const pos = this.value.indexOf(id);
      this.value.splice(pos, 1);
    } else {
      this.value.push(id);
    }
  }

  toggleAllSelection() {
    this.selectAll = !this.selectAll;
    if (this.selectAll == true) {
      this.value = this.users;
      this.employeesValidate?.setValue(this.users);
    } else {
      this.value = [];
    }
  }

  employeesValidateBox() {
    let arrIndex = [];
    for (
      let indexFor = 0;
      indexFor < this.data.item.employeesValidate.length;
      indexFor++
    ) {
      let index = this.users.findIndex(
        (element) => element.id == this.data.item.employeesValidate[indexFor].id
      );
      arrIndex.push(index);
    }

    let arrUsr: any[] = [];
    arrIndex.forEach((element) => {
      arrUsr.push(this.users[element]);
    });

    return arrUsr;
  }

  get employeesValidate() {
    return this.formGroup.get('employeesValidate');
  }

  get field() {
    return this.formGroup.get('field');
  }

  get sequence() {
    return this.formGroup.get('sequence');
  }

  get nextSequence() {
    return this.formGroup.get('nextSequence');
  }

  get is_Available() {
    return this.formGroup.get('is_Available');
  }

  get isNotified() {
    return this.formGroup.get('isNotified');
  }
}
