import { Component, OnInit } from '@angular/core';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { MatStepper } from '@angular/material/stepper';
import { ActivatedRoute, Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { EncService } from 'src/app/services/enc/enc.service';
import { GenericService } from 'src/app/services/generic/generic.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { SHOWMULTIFORMComponent } from '../../resources/dialogs/test/showmultiform/showmultiform.component';
import { OneMenuResponse } from '../plantilla1/plantilla1.component';

@Component({
  selector: 'app-plantilla4',
  templateUrl: './plantilla4.component.html',
  styleUrls: ['./plantilla4.component.css']
})
export class Plantilla4Component implements OnInit {
  public name_form: string = "";
  public fields: Array<FieldsForm> = [];

  public data!: OneMenuResponse;
  public data_form!: DataForm;


  public model: Array<any> = [];
  private arr_resp: Array<any> = [];
  private response: Array<any> = [];

  public isLoading: boolean = false;
  public isRegister: boolean;

  public data_file: Array<any> = [];

  public idForm: string;

  // ---- SmartPage ----
  public card_size = 'card-size-normal mat-elevation-z8';

  constructor(
    public dialog: MatDialog,
    private _router: Router,
    private _encService: EncService,
    private _genericService: GenericService,
    private _resourceService: ResourcesService,
    private _dialogRef: MatDialogRef<any>
  ) {
    this.isRegister = true;
    this.idForm = '0000000002'
    this.generateForm();
  }

  ngOnInit() { }

  private async generateForm() {
    this.isLoading = true;
    if (this.isRegister) {
      await lastValueFrom(this._genericService.generateForm(this.idForm)).then(
        (data: any) => {
          if (!data.error) {
            this.fields = data.response.FIELDS;
            this.name_form = data.response.NOMBRE_FORM;
            this.generateModel();

          }
        }, (error: any) => this._resourceService.checkErrors(error)
      );
    } else {
      let data_table = {
        tables: {
          main_table: "1",
          secondary_table: [
            {
              table: "ts002v01tprov",
              id: "26"
            }
          ]
        }
      }
      await lastValueFrom(this._genericService.generateFormEdit(this.idForm, data_table)).then(
        (data: any) => {
          if (!data.error) {
            this.fields = data.response.FIELDS;
            this.name_form = data.response.NOMBRE_FORM;
            this.generateModel();
          }
        }, (error: any) => this._resourceService.checkErrors(error)
      );
    }

    this.isLoading = false;
  }

  // Generación de NgModel para cada dato del formulario
  private async generateModel() {
    let index: number = 0;
    this.fields.map((element0) => {
      this.model.push([]);
      element0.form.map((element1) => {

        if (!this.isRegister && element1.tag === 'input' && element1.type === 'date' && (element1.value !== '' || element1.value !== null)) {
          let arr_date = element1.value.split(" ");
          element1.value = arr_date[0];
        }
        this.model[index].push({
          value: element1.value,
          id: element1.id,
          name: element1.name,
          required: element1.required,
          pattern: element1.pattern,
          column: element1.column,
          data_table: element1.data_table
        });
      });
      index++;
    });
  }

  // Registro de datos
  public registerDataStep(step: number, stepper: MatStepper, multi_data: boolean) {
    let validation = this.model[step].some(
      (element: any) => element.value == '' && element.required
    );
    if (validation && this.validDataStep(step)) {
      this._resourceService.openSnackBar('Ingrese valores correctos para continuar');
      return;
    }

    if (!multi_data) {
      this.response[step] = this.model[step];
    } else {
      if (this.arr_resp[step].length > 0) {
        let arr_data: Array<any> = [];
        this.arr_resp[step].map((element: any) => arr_data.push(JSON.parse(element)));
        this.response[step] = arr_data;
      } else this._resourceService.openSnackBar('Ingrese datos a la tabla para continuar');
    }

    if (step !== this.model.length - 1) {
      stepper.next();
    } else {
      this.register();
      // this.update();
    }
  }

  // Registro de todos los datos
  public async register() {

    const data_response = new FormData();
    data_response.append('CODIGO_FORM', this.idForm);
    data_response.append('DATA_VALUE', JSON.stringify(this.response));
    data_response.append('USER', this._resourceService.getUser());
    this.data_file.map((element: any, index: number) => {
      data_response.append(element.column, element.file);
    });

    await lastValueFrom(this._genericService.registerData(data_response)).then(
      (data: ResponseData) => {
        if (!data.error) {
          this._resourceService.openSnackBar("¡Datos Registrados!");
          this._dialogRef.close(true);
          // this._router.navigate(['sam/template-table', { data: JSON.stringify(this.data) }]);
        }
      },
      (error: any) => this._resourceService.checkErrors(error)
    );
  }

  // Modificación de todos los datos
  public async update() {
    let data_response = {
      codigo_form: this.idForm,
      data_value: this.response,
      user: localStorage.getItem('idusuario')!,
      tables: {
        main_table: "1",
        secondary_table: [
          {
            table: "ts002v01tprov",
            id: "26"
          }
        ]
      }
    }
    await lastValueFrom(this._genericService.updateData(data_response)).then(
      (data: ResponseData) => {
        if (!data.error) {
          this._resourceService.openSnackBar("¡Datos Registrados!");
          this._router.navigate(['sam/template-table', {
            data: JSON.stringify(this.data)
          }]);
        }
      },
      (error: any) => this._resourceService.checkErrors(error)
    );
  }

  // Agregar datos a la tabla
  public addDataTable(step: number) {
    let validation = this.model[step].some((element: any) => element.value.length === 0 && element.required);
    if (validation && this.validDataStep(step)) {
      this._resourceService.openSnackBar('Ingrese valores correctos para continuar');
      return;
    } else if (this.arr_resp[step] === undefined) {
      this.arr_resp[step] = [];
    }
    let str = JSON.stringify(this.model[step]);
    this.arr_resp[step].push(str);
    this._resourceService.openSnackBar('¡Datos agregados!');
  }

  // Ver tabla
  public showMultidataRegister(step: number) {
    if (this.arr_resp[step].length == 0) {
      this._resourceService.openSnackBar(
        'No ha ingresado ningún dato a la tabla'
      );
    } else {
      let aux_data: Array<any> = [];

      this.arr_resp[step].map((element: string) => {
        aux_data.push(JSON.parse(element))
      });

      let modal = {
        estructura: this.fields[step],
        datos: aux_data,
      };

      const dialogRef = this.dialog.open(SHOWMULTIFORMComponent, {
        data: modal,
        width: '1200px',
        disableClose: true
      });

      dialogRef.afterClosed().subscribe(result => {

        let aux: Array<any> = [];
        result.map((element: string) => {
          aux.push(JSON.stringify(element));
        });

        this.arr_resp[step] = aux;
      });
    }
  }

  // Método de reacomodo de los elementos
  public onResize(event: any) {
    if (event.target.innerWidth <= 700) {
      this.card_size = 'card-size-small';
    } else if (event.target.innerWidth > 700) {
      this.card_size = 'card-size-normal mat-elevation-z8';
    }
  }

  // Validar datos del step
  private validDataStep(step: number) {
    let valid_input: Array<any> = [];
    this.model[step].map((element: any) => {
      if (element.pattern !== null) {
        if (!new RegExp(element.pattern).test(element.value)) {
          valid_input.push(element);
        }
      }
    });
    return valid_input.length > 0;
  }

  public getDataFile(event: any, index_field: number, index_form: number) {
    this.data_file.push({ file: event.target.files[0], column: this.model[index_field][index_form].column });
    this.model[index_field][index_form].value = this.data_file;
  }
}

export interface DataForm {
  fields: Array<FieldsForm>;
  form_name: string;
  menu: number;
  primary_key: string;
  table: string;
}

export interface RelationshipData {
  columns: Array<string>;
  foreign_key: string;
  primary_key: string;
  table: string;
}

export interface DataTable {
  columns: Array<string>;
  data: Array<any>;
  primary_key: string;
  relationship: Array<RelationshipData>;
  table: string;
}


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

export interface ResponseData {
  error: string;
  msg: string;
  response: DataTable;
}


