import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { CdkDragDrop, moveItemInArray, transferArrayItem, } from '@angular/cdk/drag-drop';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { GETBFONEWFORMComponent } from 'src/app/components/resources/dialogs/getb/getbfo/getbfo-newform/getbfo-newform.component';
import { GETBFOVIEWEXAMPLEComponent } from 'src/app/components/resources/dialogs/getb/getbfo/getbfo-viewexample/getbfo-viewexample.component';
import { GETBFOINPUTComponent } from 'src/app/components/resources/dialogs/getb/getbfo/getbfo-input/getbfo-input.component';
import { GETBFOSELECTComponent } from 'src/app/components/resources/dialogs/getb/getbfo/getbfo-select/getbfo-select.component';
import { GETBFOCHECKBOXComponent } from 'src/app/components/resources/dialogs/getb/getbfo/getbfo-checkbox/getbfo-checkbox.component';
import { GETBFORADIOComponent } from 'src/app/components/resources/dialogs/getb/getbfo/getbfo-radio/getbfo-radio.component';
import { GETBFOTEXTAREAComponent } from 'src/app/components/resources/dialogs/getb/getbfo/getbfo-textarea/getbfo-textarea.component';
import { GETBFOUSERSDATESComponent } from 'src/app/components/resources/dialogs/getb/getbfo/getbfo-usersdates/getbfo-usersdates.component';
import { GETBGMService } from 'src/app/services/getb/getbgm/getbgm.service';
import { GETBSMService } from 'src/app/services/getb/getbsm/getbsm.service';
import { GETBMEService } from 'src/app/services/getb/getbme/getbme.service';
import { lastValueFrom } from 'rxjs';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { GETBTBService } from 'src/app/services/getb/getbtb/getbtb.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { GETBFOService } from 'src/app/services/getb/getbfo/getbfo.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { ActivatedRoute, Router } from '@angular/router';
import { GETBREService } from 'src/app/services/getb/getbre/getbre.service';
import { GETBGTService } from 'src/app/services/getb/getbgt/getbgt.service';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-form-dynamic-management-form',
  templateUrl: './form-dyn-management-form.component.html',
  styleUrls: ['./form-dyn-management-form.component.css']
})
export class FormDynManagementFormComponent implements OnInit {
  public step = 0;

  public opciones: Array<string> = ['input', 'select', 'checkbox', 'radio', 'textarea'];
  private auxiliar: Array<string> = ['input', 'select', 'checkbox', 'radio', 'textarea'];

  public fields: Array<any> = [];
  public connectedTo: Array<any> = [];
  public data_form: DataForm = {} as DataForm;
  public isLoading: boolean = false;

  public formGroupUbication: FormGroup;
  public formGroupTableDB: FormGroup;

  public arr_modulo: ModuloResponse[] = [];
  public arr_submodulo: SubmoduloResponse[] = [];
  public arr_menu: MenuResponse[] = [];

  public arr_table: Array<TableData> = [];
  public arr_relationship: Array<any> = [];
  public arr_columns: any = [];

  public data_table: Array<any> = [];
  public model: Array<any> = [];

  public aux_columns: Array<String> = [];

  // Variable con los datos del formulario
  public data_json: any = {};

  // Variable guarda los campos y fechas que se registrarán en la bd
  public arr_users_dates: Array<any> = [];

  // Variable ID del formulario
  public id_form: number;

  public main_table_form: string = '';

  constructor(
    private dialog: MatDialog,
    private _getbfoService: GETBFOService,
    private _getbgmService: GETBGMService,
    private _getbsmService: GETBSMService,
    private _getbmeService: GETBMEService,
    private _getbgtService: GETBGTService,
    private _resourceService: ResourcesService,
    private _getbreService: GETBREService,
    private _encService: EncService,
    private _router: Router,
    private _activatedRouter: ActivatedRoute
  ) {
    // Obtener el ID del formulario de la URL
    let id_form = this._activatedRouter.snapshot.paramMap.get('id');
    this.id_form = id_form == null ? 0 : parseInt(id_form);
    // Obtener el formulario de la bd

    this.formGroupUbication = this.createFormUbication();
    this.formGroupTableDB = this.createFormTableDB();

    for (let item of this.fields) {
      this.connectedTo.push(item.id);
    }
  }

  ngOnInit(): void {
    this.dataTable();
  }

  // Formulario de ubicación de la tabla | Accordion 1
  private createFormUbication() {

    return new FormGroup({
      modulo_data: new FormControl({ value: '', disabled: this.id_form > 0 }, Validators.required),
      // submodulo_data: new FormControl({ value: '', disabled: true }, Validators.required),
      // menu_data: new FormControl({ value: '', disabled: true },Validators.required),
      form_name: new FormControl('', Validators.required),
      workflow: new FormControl(false),
    });
  }

  // Formulario de tablas de la base de datos | Accordion 1
  private createFormTableDB() {
    return new FormGroup({
      main_table: new FormControl({}, Validators.required),
      relation_table: new FormControl({ value: [], disabled: true }),
      columns: new FormControl({ value: [], disabled: true }, Validators.required),
    });
  }

  private async dataTable() {
    await lastValueFrom(this._getbgtService.getTables()).then(
      (data: any) => {
        if (!data.error) {
          this.arr_table = data.response;
          this.id_form > 0 ? this.getDataFormDataBase(this.id_form) : this.dataModule();
        }
      },(error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );

  }

  // Obtener datos del formulario
  public async getDataFormDataBase(codigo_form: number) {
    await lastValueFrom(this._getbfoService.getFormData(codigo_form)).then(
      async (data: ResponseData) => {
        this.data_json = data.response;
        this.workflow?.setValue(data.response.WORKFLOW == 'PARA WORKFLOW' || data.response.WORKFLOW == 'CON WORKFLOW' ? true : false);
        this.form_name?.setValue(data.response.NOMBRE_FORM);
        this.setDataTable();
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
  }

  public async setDataTable() {
    // Asignar nombre de la tabla principal
    let main_table = this.data_json.DATA_FORM.table_main;
    await this._encService.desencriptar(main_table).then((data: string) => (main_table = data));
    this.main_table?.setValue(main_table);

    // Asignar tablas relacionales
    let table_relationship = this.data_json.DATA_FORM.table_relationship;
    await this._encService.desencriptar(table_relationship).then((data: string) => (table_relationship = data));
    table_relationship = JSON.parse(table_relationship);
    this.dataRelationship();
    this.relation_table?.setValue(table_relationship);

    // Asignar columnas
    this.dataColumns();
    let arr_columns: Array<string> = [];
    this.data_json.DATA_FORM.fields.map((fields: any) => { fields.form.map((forms: any) => { arr_columns.push(forms.column); }); });
    this.columns?.setValue(arr_columns);
    this.generateModel();


    // Se asignan los campos
    this.fields = this.data_json.DATA_FORM.fields;
    this.form_name?.setValue(this.data_json.NOMBRE_FORM);
    for (let item of this.fields) {
      this.connectedTo.push(item.step);
    }

    // Asignación de usuarios y fechas
    this.arr_users_dates = this.data_json.DATA_FORM.info_users_dates;

    this.validateDataColumns();
  }

  private async dataModule() {
    await lastValueFrom(this._getbgmService.getModuleAviable()).then(
      (data: ResponseData) => {
        this.arr_modulo = !data.error ? data.response : [];
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
  }

  //Obtener submódulo por módulo | Accordion 2
 /*  public async dataSubmodule() {
    await lastValueFrom(this._getbsmService.getOneSubmodule(this.modulo_data?.value.CODIGO_MODULO)).then(
      (data: ResponseData) => {
        if (!data.error) {
          this.arr_submodulo = data.response;
          data.response.length > 0 && this.id_form == 0  ? this.submodulo_data?.enable() : this.submodulo_data?.disable();
        }
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
  } */

  //Obtener menú por submódulo | Accordion 2
  /* public async dataMenu() {
    await lastValueFrom(this._getbmeService.getMenuByForm(this.submodulo_data?.value.CODIGO_SUBMODULO)).then(
      (data: ResponseData) => {
        if (!data.error) {
          this.arr_menu = data.response;
          data.response.length > 0 ? this.menu_data?.enable() : this.menu_data?.disable();
        }
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
  } */

  // Obtener tablas relacionales | Accordion 2
  public async dataRelationship() {

    await lastValueFrom(this._getbreService.getRelationshipEsp(this.main_table?.value)).then(
      (data: any) => {
        if (!data.error) {
          this.arr_relationship = data.response;
          data.response.length > 0 ? this.relation_table?.enable() : this.relation_table?.disable();
          this.columns?.enable();
          this.dataColumns();
        }
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
  }

  // Obtener columnas | Accordion 2
  public async dataColumns() {
    this.data_table = [];
    let aux_columns = this.relation_table?.value;
    aux_columns.unshift(this.main_table?.value);
    await lastValueFrom(this._getbgtService.getColumns({ tables: aux_columns })).then(
      (data: any) => {
        if (!data.error) {
          this.arr_columns = data.response;

          // Se deshabilitan las opciones seleccionadas
          let new_cols: any = []
          this.arr_columns.map((data_columns: any) => {
            let new_columns: any = [];
            data_columns.columns.map((column: any) => {
              let obj = { column: column, disable: true };
              obj.disable = this.columns?.value.includes(column);
              column = obj;
              new_columns.push(column);
            });
            data_columns.columns = new_columns;
            new_cols.push(data_columns);
          });
          this.arr_columns = new_cols;
          data.response.length > 0 ? this.columns?.enable() : this.columns?.disable();
        }
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );

  }

  // Generación de NgModel para cada dato del formulario
  public generateModel() {

    this.model = [];
    this.columns?.value.map((colum: string) => {
      this.arr_columns.map((data: any) => {
        if (data !== 'Acciones') {
          data.columns.map((item: string) => {
            if (colum !== 'Acciones' && item === colum)
              this.model.push({ new_column: '', column: colum, db: data.table });
          });
        }
      });
    });

    this.fields.map((fields: any) => {
      let new_form: any = [];
      fields.form.map((forms: any) => {
        if (this.columns?.value.includes(forms.column)) {
          new_form.push(forms);
        }
      });
      fields.form = new_form;
    });

    this.aux_columns = this.columns?.value;

    this.validateDataColumns();
  }

  // Generar datos de la tabla
  /*  public async generateDataForm() {
     let obj_res = {
       tabla_principal: this.main_table?.value,
       tablas_relacion: this.relation_table?.value,
       menu: this.menu_data?.value,
       model: this.model,
       table_name: this.form_name?.value,
     };
     await lastValueFrom(this._getbtbService.saveTable(obj_res)).then(
       (data: any) => {
         if (!data.error) {
           this.data_table = data.response;
           this._router.navigate(['sam/getbtb']);
           this._resourceService.openSnackBar('¡Registro exitoso!');
         }
       },
       (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
     );
   } */

  public drop(event: CdkDragDrop<any[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data,event.previousIndex,event.currentIndex);
    } else {
      let findIndexField = this.fields.findIndex((element) => element.step == event.container.id);
      let num_col = this.fields[findIndexField].num_cols;
      if (event.previousContainer.data[event.previousIndex].num_col > num_col) {
        this._resourceService.openSnackBar('No se puede ingresar este elemento a este formulario');
      } else {
        transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex);
        let elemento = event.container.data[event.currentIndex];
        this.opciones = [];
        this.auxiliar.forEach((item) => { this.opciones.push(item); });
        let dialogRef = null;
        let sinMovimiento: boolean = false;
        //let findIndexField = this.fields.findIndex(element => element.step == event.container.id);
        switch (elemento) {
          case 'input':
            dialogRef = this.dialog.open(GETBFOINPUTComponent, {
              disableClose: true,
              width: '1000px',
              data: {
                num_cols: this.fields[findIndexField].num_cols,
                column: this.aux_columns,
              },
            });
            break;
          case 'select':
            let filter_columns = this.arr_columns.filter((element: any) => element.table !== this.main_table?.value && element !== 'Acciones');
            dialogRef = this.dialog.open(GETBFOSELECTComponent, {
              disableClose: true,
              data: {
                num_cols: this.fields[findIndexField].num_cols,
                column: this.aux_columns,
                table_main: this.main_table?.value,
                tables_rel: this.arr_relationship,
                columns: filter_columns,
              },
              width: '1000px',
            });
            break;
          case 'checkbox':
            dialogRef = this.dialog.open(GETBFOCHECKBOXComponent, {
              disableClose: true,
              data: {
                num_cols: this.fields[findIndexField].num_cols,
                column: this.aux_columns,
              },
              width: '700px',
            });
            break;
          case 'radio':
            dialogRef = this.dialog.open(GETBFORADIOComponent, {
              disableClose: true,
              width: '600px',
              data: {
                num_cols: this.fields[findIndexField].num_cols,
                column: this.aux_columns,
              },
            });
            break;
          case 'textarea':
            dialogRef = this.dialog.open(GETBFOTEXTAREAComponent, {
              disableClose: true,
              width: '1000px',
              data: {
                num_cols: this.fields[findIndexField].num_cols,
                column: this.aux_columns,
              },
            });
            break;
          default:
            sinMovimiento = true;
        }
        if (!sinMovimiento) {
          dialogRef!.afterClosed().subscribe((result) => {
            if (result) {
              let resp = this.validateIDs(result);
              if (resp === -1) {
                let id = event.container.id;
                let index = this.fields.findIndex((element: any) => element.step == id);
                this.fields[index].form[event.currentIndex] = result;
                let index_col = this.aux_columns.findIndex((element: any) => element === result.column);
                this.aux_columns.splice(index_col, 1);
              } else {
                let id = event.container.id;
                let index = this.fields.findIndex((element: any) => element.step == id);
                this.fields[index].form.splice(event.currentIndex, 1);
                this._resourceService.openSnackBar('Los identificadores no se pueden repetir');
              }
            } else {
              let id = event.container.id;
              let index = this.fields.findIndex((element: any) => element.step == id);
              this.fields[index].form.splice(event.currentIndex, 1);
            }
          });
        }
      }
    }
  }

  public addForm() {
    const dialogRef = this.dialog.open(GETBFONEWFORMComponent, {
      disableClose: true,
      width: '350px',
    });
    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        let filter = this.fields.filter((element: any) => element.step == result.step);
        if (filter.length == 0) {
          this.connectedTo = [];
          this.fields.push({
            //id: `Registro de proveedores - ${result} - ${this.weeks.length + 1}`,
            step: result.step,
            multi_data: result.multi_data,
            table_name: result.table_name,
            num_cols: result.num_cols,
            form: [],
          });
          for (let item of this.fields) {
            this.connectedTo.push(item.step);
          }
        } else {
          this._resourceService.openSnackBar('No se pueden repetir los nombres de los formularios');
        }
      }
    });

  }

  public viewExample() {
    let data_form: string = JSON.stringify(this.data_form);
    let json: string = JSON.stringify({ name: this.data_form.formulario, fields: this.fields });
    let screenWidth: number = window.innerWidth * 0.9;
    this.dialog.open(GETBFOVIEWEXAMPLEComponent, {
      width: `${screenWidth.toString()}px`,
      data: {
        data_form: data_form,
        json: json,
      },
    });
  }

  public async save() {
    let arrRelationshipTable: Array<string> = []
    this.fields.map((itmFields: any) => {
      itmFields.form.map((itmForm: any) => {
        let data_table = {};

        this.arr_columns.map((itmColumns: any) => {
          if (itmColumns.columns.some((item: any) => item.column == itmForm.column)) {
            if (itmForm.tag == 'select' && itmForm.columnMMtoMain != null && itmForm.columnMMtoMain != undefined) {
              data_table = {
                table: itmColumns.table,
                column: itmForm.column,
                columnMM: itmForm.columnMM,
                columnMMtoMain: itmForm.columnMMtoMain
              }
            } else {
              data_table = {
                table: itmColumns.table,
                column: itmForm.column
              }
            }
            arrRelationshipTable.push();

          }
        });
        itmForm['data_table'] = data_table;
      });
    });
    let tabla_principal = this.main_table?.value;
    let tabla_relaciones: string = '';

    let arrTables: any = this.relation_table?.value;
    let arrRelationshipsTable = arrTables.filter((element: any) => element != tabla_principal);

    await this._encService.encriptar(tabla_principal).then((data: string) => (tabla_principal = data));
    await this._encService.encriptar(JSON.stringify(arrRelationshipsTable)).then((data: string) => (tabla_relaciones = data));

    this.fields.map((fields: any) => {
      fields.form.map((form: any) => {
        form.deleted = false;
      });
    });

    let json: any = {
      FORM_NAME: this.form_name?.value,
      MODULE: this.modulo_data?.value.CODIGO_MODULO,
      USER: this._resourceService.getUser(),
      WORKFLOW: this.workflow?.value,
      DATA_FORM: {
        fields: this.fields,
        table_main: tabla_principal,
        table_relationship: tabla_relaciones,
        info_users_dates: this.arr_users_dates
      },
    };

    let validForm: boolean = true;
    this.fields.forEach((element: FieldsForm) => {
      if (element.form.length == 0) {
        validForm = false;
      }
    });

    // Se indica si es un registro o modificación
    let opc = this.id_form == 0 ? 'REG' : 'UPD';
    validForm ? this.alert(opc, json) : this._resourceService.openSnackBar('Los formularos deben tener al menos 1 elemento');
  }

  private async registerData(json: any) {
    await lastValueFrom(this._getbfoService.createForm(json)).then(
      (data: ResponseData) => {
        if (!data.error) {
          this._resourceService.openSnackBar('¡Registro de formulario exitoso!');
          this._router.navigate(['/sam/form-dyn-management']);
        } else {
          this._resourceService.openSnackBar(data.msg);
        }
      }, (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
  }

  private async updateDate(json: any) {
    await lastValueFrom(this._getbfoService.updateForm(json, this.id_form)).then(
      (data: ResponseData) => {
        if (!data.error) {
          this._resourceService.openSnackBar('¡Modificación de formulario exitoso!');
          this._router.navigate(['/sam/getbfo']);
        } else {
          this._resourceService.openSnackBar(data.msg);
        }
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
  }

  public numColumn(type: string, index: number) {
    if (type == 'add') {
      if (this.fields[index].num_cols + 1 <= 8) {
        this.fields[index].num_cols += 1;
      }
    } else {
      if (this.fields[index].num_cols - 1 >= 1) {
        this.fields[index].num_cols -= 1;
      }
    }
  }

  public alert(type: string, data: any = null) {
    let info: AlertData = {} as AlertData;
    let validForm: boolean = true;
    switch (type) {
      case 'ELM':
        info = {
          icon: 'warning',
          title: 'Eliminar Elemento',
          description: '¿Está seguro de eliminar este elemento?',
        };
        break;
      case 'ELM-FORM':
        info = {
          icon: 'warning',
          title: 'Eliminar Formulario',
          description: '¿Está seguro de eliminar este formulario?',
        };
        break;
      case 'REG':
        info = {
          icon: 'warning',
          title: 'Registrar Formulario',
          description: '¿Está seguro de registrar este formulario?',
        };
        break;
      case 'UPD':
        info = {
          icon: 'warning',
          title: 'Modificar Formulario',
          description: '¿Está seguro de modificar este formulario?',
        };
        break;
      case 'exit':
        info = {
          icon: 'warning',
          title: 'Salir del Formulario',
          description: '¿Está seguro de salir del formulario? Se perderán todos tus cambios.',
        };
        break;
    }

    if (validForm) {
      this.dialog.open(AlertComponent, {
        data: info,
        disableClose: true,
        width: '350px',
      }).afterClosed().subscribe((result) => {
        if (result) {
          switch (type) {
            case 'ELM':
              this.deleteElement(data.i0, data.i1);
              break;
            case 'ELM-FORM':
              this.deleteForm(data);
              break;
            case 'REG':
              this.registerData(data);
              break;
            case 'UPD':
              this.updateDate(data);
              break;
            case 'exit':
              //this._router.navigate(['sam/form-dyn-management']);
              this.goBack(1);
              break;
          }
        }
      });
    }
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  public deleteElement(stepIndex: number, formIndex: number) {
    this.fields[stepIndex].form[formIndex].column;
    this.aux_columns.push(this.fields[stepIndex].form[formIndex].column);
    this.fields[stepIndex].form.splice(formIndex, 1);
    this._resourceService.openSnackBar('¡Elemento eliminado!');
  }

  private deleteForm(indexForm: number) {
    this.fields.splice(indexForm, 1);
    this._resourceService.openSnackBar('¡Formulario eliminado!');
  }

  private validateIDs(new_form: any): number {
    // Por Formulario
    for (let index_form = 0; index_form < this.fields.length; index_form++) {
      // Campos del formulario
      for (let index_campos = 0; index_campos < this.fields[index_form].form.length; index_campos++) {
        if (this.fields[index_form].form[index_campos].id == new_form.id) {
          return index_form;
        }
      }
    }
    return -1;
  }

  public validateDataColumns() {
    // Se identifica que si todas las columas ya se encuentran en el formulario
    let columns_selected: Array<any> = [];
    this.fields.map((fields: any) => {
      fields.form.map((forms: any) => {
        columns_selected.push(forms.column);
      });
    });

    this.aux_columns = this.aux_columns.filter(x => !columns_selected.includes(x));
  }

  public setStep(index: number) {
    this.step = index;
  }

  public nextStep() {
    this.step++;
    if (this.step == 2) {
      this.validateDataColumns();
    }
  }

  public prevStep() {
    this.step--;
    if (this.step === 1) {
      // this.fields = [];
    }
  }

  public openDialogUsersDates() {
    // Se eliminan elementos duplicados
    let arrData: any = [];
    let arrDataElement: any = [];
    this.arr_columns.map((element: any) => {
      if (!arrData.includes(element.table)) {
        arrData.push(element.table);
        arrDataElement.push(element);
      }
    });
    this.arr_columns = arrDataElement;

    let dialogRef = this.dialog.open(GETBFOUSERSDATESComponent, {
      disableClose: true,
      data: { data_table: this.arr_columns },
      width: '400px',
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        let arr_data = result;

        arr_data.table = arr_data.table.table;
        arr_data.date_mod = arr_data.date_mod.column == undefined ? null : arr_data.date_mod.column;
        arr_data.date_reg = arr_data.date_reg.column == undefined ? null : arr_data.date_reg.column;
        arr_data.timestamp = arr_data.timestamp.column == undefined ? null : arr_data.timestamp.column;
        arr_data.user_mod = arr_data.user_mod.column == undefined ? null : arr_data.user_mod.column;
        arr_data.user_reg = arr_data.user_reg.column == undefined ? null : arr_data.user_reg.column;
        arr_data.where = arr_data.where.column == undefined ? null : arr_data.where.column;

        let isExist = false;
        this.arr_users_dates.map((element: any) => {
          if (element.table == arr_data.table) {
            this._resourceService.openSnackBar('Ya existe un registro con esa tabla, favor de borrar el registro anterior para poder registrar nuevos datos.')
            isExist = true;
          }
        });
        if (!isExist) {
          let newItems = this.arr_users_dates;
          newItems.push(arr_data);
          this.arr_users_dates = newItems;
        }
      }
    });
  }

  public deleteUserDate(table: any) {
    this.arr_users_dates = this.arr_users_dates.filter((element: any) => element.table !== table);
  }

  // Formulario 1
  get modulo_data() { return this.formGroupUbication.get('modulo_data'); }
  get submodulo_data() { return this.formGroupUbication.get('submodulo_data'); }
  get menu_data() { return this.formGroupUbication.get('menu_data'); }
  get form_name() { return this.formGroupUbication.get('form_name'); }
  get workflow() { return this.formGroupUbication.get('workflow'); }

  // Formulario 2
  get main_table() { return this.formGroupTableDB.get('main_table'); }
  get relation_table() { return this.formGroupTableDB.get('relation_table'); }
  get columns() { return this.formGroupTableDB.get('columns'); }
}

export interface DataForm {
  modulo: any;
  submodulo: any;
  menu: any;
  nombre_tabla: string;
  formulario: string;
}

export interface JsonForm {
  form_name: string;
  module: string;
  submodule: string;
  table: string;
  primary_key: string;
  fields: Array<FieldsForm>;
}

export interface FieldsForm {
  step: string;
  multi_data: boolean;
  form: Array<any>;
  num_cols: number;
}

export interface AlertData {
  icon: string;
  title: string;
  description: string;
}

export interface MenuResponse {
  CODIGO_MENU: number;
  NOMBRE_MENU: string;
  MODULO: string;
  SUBMODULO: string;
  ESTADO: string;
}

export interface SubmoduloResponse {
  CODIGO_SUBMODULO: string;
  SUBMODULO: string;
  ESTADO: string;
}

export interface TableData {
  CODIGO_TABLA: number;
  NOMBRE_TABLA: string;
}

export interface ResponseData {
  error: boolean;
  msg: string;
  response: Array<any> | any;
}
export interface ModuloResponse {
  MODULO_CODIGO: string;
  MODULO: string;
  ESTADO: string;
}
