import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Save } from '@syncfusion/ej2-angular-spreadsheet';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { AlertData } from 'src/app/interfaces/alert.interface';
import { ProviderService } from 'src/app/services/acquisition-management/provider/provider.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import {
  InformationData,
  ReferenceData,
  ContactData,
  ConditionData,
  CatalogData,
  PaymentData,
  RevisionData,
  SaveData,
  ProviderSave,
  InformationForm,
  ReferenceForm,
  ContactForm,
  ConditionForm,
  CatalogForm,
  RegisterForm,
  ResponseFormProvider,
  RegisterProvider,
  TypeForm,
  ReferencesData,
  CatalogsData
} from 'src/app/interfaces/acquisition-management/provider/provider.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-provider-form',
  templateUrl: './provider-form.component.html',
  styleUrls: ['./provider-form.component.css']
})
export class ProviderFormComponent implements OnInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;
  public btnSmall: boolean;
  public isLinear:boolean;
  public isFormLocalSave: boolean;
  public allComplete: boolean;

  public formGroupInformation: FormGroup;
  public formGroupReferences: FormGroup
  public formGroupContact: FormGroup;
  public formGroupCondition: FormGroup;
  public formGroupCatalog: FormGroup;

  public idReferencia: number;
  public idContacto: number;
  public idCondicion: number;
  public idCatalog: number;

  public task: PaymentData;
  public subtasks:Array<PaymentData>;

  public displayedColumnsReferences: Array<string>;
  public dataSourceReference: MatTableDataSource<ReferenceData>;
  public typeFormReference:string;

  public displayedColumnsContact: Array<string>;
  public dataSourceContact: MatTableDataSource<ContactData>;
  public typeFormContact:string;

  public displayedColumnsCondition: Array<string>;
  public dataSourceCondition: MatTableDataSource<ConditionData>;
  public typeFormCondition:string;

  public displayedColumnsCatalog: Array<string>;
  public dataSourceCatalog: MatTableDataSource<CatalogData>;
  public typeFormCatalog:string;

  public displayedColumnsRevision: Array<string>;
  public dataSourceRevision: MatTableDataSource<RevisionData>;

  public typeForm:TypeForm;

  constructor(
    private _resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _providerService: ProviderService,
    private _activatedRouter: ActivatedRoute,
    public _router: Router,
  ) {

    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;
    this.isLinear = false;
    this.isFormLocalSave = false;
    this.allComplete = false;

    this.task = {
      name: 'Métodos de Pago',
      completed: false,
      subtasks: [
        {name: '01: Efectivo', completed: false},
        {name: '02: Cheque nominativo', completed: false},
        {name: '03: Transferencia electrónica de fondos', completed: false},
        {name: '04: Tarjeta de crédito', completed: false},
        {name: '05: Monedero electrónico', completed: false},
        {name: '06: Dinero electrónico', completed: false},
        {name: '08: Vales de despensa', completed: false},
        {name: '12: Dación en pago', completed: false},
        {name: '13: Pago por subrogación', completed: false},
        {name: '14: Pago por consignación', completed: false},
      ],
    }

    this.subtasks = [
      {name: '15: Condonación', completed: false},
      {name: '17: Compensación', completed: false},
      {name: '23: Novación', completed: false},
      {name: '24: Confusión', completed: false},
      {name: '25: Remisión de deuda', completed: false},
      {name: '26: Prescripción o caducidad', completed: false},
      {name: '27: A satisfacción del acreedor', completed: false},
      {name: '28: Tarjeta de débito', completed: false},
      {name: '29: Tarjeta de servicios', completed: false},
      {name: '30: Aplicación de anticipos', completed: false},
      {name: '31: Intermediario pagos', completed: false},
      {name: '99: Por definir', completed: false}
    ];

    this.idReferencia = 1;
    this.typeFormReference = 'REG_REF';
    this.displayedColumnsReferences = [ 'NO', 'EMPRESA', 'CORREO', /* 'TELEFONO', */ 'RFC', 'ESTADO', 'ACCIONES' ];
    this.dataSourceReference = new MatTableDataSource();

    this.idContacto = 1;
    this.typeFormContact = 'REG_CON';
    this.displayedColumnsContact = [ 'NO', 'TIPO_CONTACTO', 'CORREO1', 'ESTADO', 'ACCIONES' ];
    this.dataSourceContact = new MatTableDataSource();

    this.idCondicion = 1;
    this.typeFormCondition = 'REG_COD';
    this.displayedColumnsCondition = [ 'NO', 'TIPO_CONDITION', 'ESTADO', 'ACCIONES' ];
    this.dataSourceCondition = new MatTableDataSource();

    this.idCatalog = 1;
    this.typeFormCatalog = 'REG_CAT';
    this.displayedColumnsCatalog = [ 'NO', 'CATALAGO', 'DESCRIPCION', 'ESTADO', 'ACCIONES' ];
    this.dataSourceCatalog = new MatTableDataSource();

    this.dataSourceRevision = new MatTableDataSource([
      {
        NO: 1,
        FORMULARIO_REV:'Información Personal',
        MENSAJE_REV:'',
        TYPE_REV: 'DEFAULT'
      },
      {
        NO: 2,
        FORMULARIO_REV:'Referencias',
        MENSAJE_REV:'',
        TYPE_REV: 'DEFAULT'
      },
      {
        NO: 3,
        FORMULARIO_REV:'Contactos',
        MENSAJE_REV:'',
        TYPE_REV: 'DEFAULT'
      },
      {
        NO: 4,
        FORMULARIO_REV:'Condiciones',
        MENSAJE_REV:'',
        TYPE_REV: 'DEFAULT'
      },
      {
        NO: 5,
        FORMULARIO_REV:'Medios de Pago',
        MENSAJE_REV:'',
        TYPE_REV: 'DEFAULT'
      },
      {
        NO: 6,
        FORMULARIO_REV:'Catálagos',
        MENSAJE_REV:'',
        TYPE_REV: 'DEFAULT'
      },
    ]);
    this.displayedColumnsRevision = [ 'NO', 'FORMULARIO', 'MENSAJE' ];

    this.typeForm = {} as TypeForm;

    this.formGroupInformation = this.createFormGroupInformation();
    this.formGroupReferences = this.createFormGroupReferences();
    this.formGroupContact = this.createFormGroupContact();
    this.formGroupCondition = this.createFormGroupCondition();
    this.formGroupCatalog = this.createFormCatalog();
  }

  ngOnInit(): void {
    // Se obtienen los borradores guardados
    this.getDataForm();
    this.getLocalProvider();
  }

  private async getDataForm(){
    let encForm:string = this._activatedRouter.snapshot.paramMap.get('form')!;
    let strForm:string = await this._encService.desencriptar(encForm);
    this.typeForm = JSON.parse(strForm);

    let informationPersonal:InformationForm = this.typeForm.element!;

    if (this.typeForm.type === 'EDIT') {
      this.NUMERO_PROVEEDOR?.setValue(informationPersonal.NUMERO_PROVEEDOR);
      this.RAZON_SOCIAL?.setValue(informationPersonal.RAZON_SOCIAL);
      this.CORREO?.setValue(informationPersonal.CORREO);
      this.NOMBRE?.setValue(informationPersonal.NOMBRE);
      this.PRIMER_APELLIDO?.setValue(informationPersonal.PRIMER_APELLIDO);
      this.SEGUNDO_APELLIDO?.setValue(informationPersonal.SEGUNDO_APELLIDO);
      this.LADA1?.setValue(informationPersonal.LADA1);
      this.TELEFONO1?.setValue(informationPersonal.TELEFONO1);
      this.LADA2?.setValue(informationPersonal.LADA2);
      this.TELEFONO2?.setValue(informationPersonal.TELEFONO2);
      this.GIRO_EMPRESARIAL?.setValue(informationPersonal.GIRO_EMPRESA);
      this.TIPO?.setValue(informationPersonal.TIPO_EMPRESA);
      this.RFC?.setValue(informationPersonal.RFC);
      this.TAXID?.setValue(informationPersonal.TAXID);
      this.SITIOWEB?.setValue(informationPersonal.SITIO_WEB);
      this.ESTADO?.setValue(informationPersonal.ESTADO)

      let arrReferences:Array<ReferenceForm> = this.typeForm.element?.REFERENCIAS!;
      let arrDataReference:Array<ReferenceData> = [];
      arrReferences.map((element:ReferenceForm) => {
        arrDataReference.push({
          NUMERO_REFERENCIA: element.NUMERO_REFERENCIA,
          EMPRESA_REF: element.EMPRESA,
          CORREO_REF: element.CORREO,
          TELEFONO_REF: element.TELEFONO?.toString(),
          RFC_REF: element.RFC,
          DIRECCION_REF: element.DIRECCION,
          ESTADO_REF: element.ESTADO,
        });
      });
      this.dataSourceReference.data = arrDataReference;
      this.NUMERO_REFERENCIA?.setValue(this.dataSourceReference.data.length + 1);

      let arrContacts:Array<ContactForm> = this.typeForm.element?.CONTACTOS!;
      let arrDataContacts:Array<ContactData> = [];
      arrContacts.map((element:ContactForm) => {
        arrDataContacts.push({
          ID_CONTACTO: element.NUMERO_CONTACTO!.toString(),
          NOMBRE_CONTACTO: element.NOMBRE_CONTACTO,
          TIPO_CONTACTO: element.TIPO_CONTACTO,
          CALLE: element.CALLE,
          NUMERO_EXTERIOR: element.NUMERO_EXTERIOR,
          NUMERO_INTERIOR: element.NUMERO_INTERIOR,
          CODIGO_POSTAL: element.CODIGO_POSTAL,
          MUNICIPIO: element.MUNICIPIO,
          ENTIDAD: element.ENTIDAD,
          PAIS: element.PAIS,
          TELEFONO_PRINCIPAL: element.TELEFONO1.toString(),
          TELEFONO_SECUNDARIO: element.TELEFONO2 === null ? '' : element.TELEFONO2.toString(),
          CORREO1: element.CORREO1,
          CORREO2: element.CORREO2,
          OBSERVACIONES: element.OBSERVACIONES,
          ESTADO_CON: element.ESTADO,
        });
      });
      this.dataSourceContact.data = arrDataContacts;
      this.ID_CONTACTO?.setValue(this.dataSourceContact.data.length + 1);

      let arrConditions:Array<ConditionForm> = this.typeForm.element?.CONDICIONES!;
      let arrDataConditions: Array<ConditionData> = [];
      arrConditions.map((element:ConditionForm) => {
        arrDataConditions.push({
          ID_CONDICION_COD: element.NUMERO_CONDICION?.toString(),
          TIPO_CONDICION_COD: element.TIPO_CONDICION,
          INFORMACION_COD: element.INFORMACION,
          ESTADO_COD: element.ESTADO,
        });
      });
      this.dataSourceCondition.data = arrDataConditions;
      this.ID_CONDICION_COD?.setValue(this.dataSourceCondition.data.length + 1);

      let arrPaymentMedia:Array<PaymentData> = this.typeForm.element?.METODOS_PAGO!;
      this.formatPayment(arrPaymentMedia);

      let arrCatalogs:Array<CatalogForm> = this.typeForm.element?.CATALAGOS!;
      let arrDataCatalogs: Array<CatalogData> = [];
      arrCatalogs.map((element:CatalogForm) => {
        arrDataCatalogs.push({
          ID_CATALOG_CAT: element.NUMERO_CATALAGO?.toString(),
          CATALAGO_CAT: element.CATALAGO,
          DESCRIPCION_CAT: element.DESCRIPCION,
          URL_CATALAGO_CAT: element.URL_CATALAGO,
          ESTADO_CAT: element.ESTADO,
        });
      });
      this.dataSourceCatalog.data = arrDataCatalogs;
      this.ID_CATALOG_CAT?.setValue(this.dataSourceCatalog.data.length + 1);
    }
  }

  private async getLocalProvider(){

    let saveProvider = localStorage.getItem('save_provider');
    let encUser: string = this._resourcesService.getUser();
    let user: string = await this._encService.desencriptar(encUser);

    if (saveProvider !== null) {
      let arrSaveLocal:Array<string> = JSON.parse(saveProvider);
      arrSaveLocal.map(async (element:string)=>{
        let decSaveProvier: string = await this._encService.desencriptar(element);
        let objSaveLocal: ProviderSave = JSON.parse(decSaveProvier);

        let userSaveLocal = await this._encService.desencriptar(objSaveLocal.USER)
        if ( userSaveLocal === user && this.typeForm.type === 'REGI') {
          this.alert('SET_REV', objSaveLocal.OBJ_DATA);
        }
      });
    }
  }

  private async setLocalProvider(elementData:SaveData){
    this.formGroupInformation.setValue( this.formatInfo(elementData.INFORMATION_PERSONAL) );
    this.dataSourceReference.data = elementData.REFERENCES;
    this.dataSourceContact.data = elementData.CONTACTS;
    this.dataSourceCondition.data = elementData.CONDITIONS;
    this.dataSourceCatalog.data = elementData.CATALOGS;
    this.formatPayment(elementData.PAYMENT_MEDIA);
    this.isFormLocalSave = true;
  }

  private formatPayment(elementPayment:Array<PaymentData>){
    let arrPayment1:Array<PaymentData> = [];
    let arrPayment2:Array<PaymentData> = [];
    elementPayment.forEach(element => {
      let arrName = element.name.split(':');
      if (parseInt(arrName[0]) < 15) {
        arrPayment1.push(element);
      }else{
        arrPayment2.push(element);
      }
    });

    this.task.subtasks?.map((elementMain:PaymentData) => {
      let arrNameMain = elementMain.name.split(':');
      arrPayment1.map((element2:PaymentData) => {
        let arrName = element2.name.split(':');
        if (arrNameMain[0] === arrName[0]) {
          elementMain.completed = element2.completed;
        }
      });
    });

    this.subtasks.map((elementMain:PaymentData) => {
      let arrNameMain = elementMain.name.split(':');
      arrPayment2.map((element2:PaymentData) => {
        let arrName = element2.name.split(':');
        if (arrNameMain[0] === arrName[0]) {
          elementMain.completed = element2.completed;
        }
      });
    });
  }

  private formatInfo(elementInformation: InformationData) : InformationData{
    if (elementInformation.TAXID === undefined) {
      elementInformation.TAXID = '';
    }
    if (elementInformation.RFC === undefined) {
      elementInformation.RFC = '';
    }
    return elementInformation;
  }

  // Creación de formulario de registro de informaciónCORREO_PRINCIPAL
  private createFormGroupInformation(): FormGroup {
    return new FormGroup({
      'NUMERO_PROVEEDOR': new FormControl(''),
      'RAZON_SOCIAL': new FormControl('', Validators.required),
      'CORREO': new FormControl('', [Validators.required, Validators.email]),
      'NOMBRE': new FormControl('', Validators.required),
      'PRIMER_APELLIDO': new FormControl('', Validators.required),
      'SEGUNDO_APELLIDO': new FormControl(''),
      'LADA1': new FormControl('', Validators.required),
      'TELEFONO1': new FormControl('', Validators.required),
      'LADA2': new FormControl(''),
      'TELEFONO2': new FormControl(''),
      'GIRO_EMPRESARIAL': new FormControl('', Validators.required),
      'TIPO': new FormControl('', Validators.required),
      'RFC': new FormControl('', [Validators.required, Validators.pattern(new RegExp(/^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/))]),
      'TAXID': new FormControl({value: '', disabled: true},[Validators.required, Validators.minLength(12)]),
      'SITIOWEB': new FormControl('', Validators.required),
      'ESTADO': new FormControl('Activo', Validators.required),
    })
  }

  // Creación de formulario de registro de referencias
  private createFormGroupReferences(): FormGroup {
    return new FormGroup({
      'NUMERO_REFERENCIA': new FormControl(this.idReferencia, Validators.required),
      'EMPRESA_REF': new FormControl('', Validators.required),
      'CORREO_REF': new FormControl('',[ Validators.required, Validators.email]),
      'TELEFONO_REF': new FormControl('', Validators.required),
      'RFC_REF': new FormControl('', [Validators.required, Validators.pattern(new RegExp(/^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/))]),
      'DIRECCION_REF': new FormControl('', Validators.required),
      'ESTADO_REF': new FormControl('Activo', Validators.required),
    });
  }

  // Creación de formulario de registro de contactos
  private createFormGroupContact(): FormGroup {
    return new FormGroup({
      'ID_CONTACTO': new FormControl( this.idContacto, Validators.required),
      'NOMBRE_CONTACTO': new FormControl('', Validators.required),
      'TIPO_CONTACTO': new FormControl('', Validators.required),
      'CALLE': new FormControl('', Validators.required),
      'NUMERO_EXTERIOR': new FormControl('', Validators.required),
      'NUMERO_INTERIOR': new FormControl(''),
      'CODIGO_POSTAL': new FormControl('', Validators.required),
      'MUNICIPIO': new FormControl('', Validators.required),
      'ENTIDAD': new FormControl('', Validators.required),
      'PAIS': new FormControl('', Validators.required),
      'TELEFONO_PRINCIPAL': new FormControl('', Validators.required),
      'TELEFONO_SECUNDARIO': new FormControl(''),
      'CORREO1': new FormControl('', [Validators.required, Validators.email]),
      'CORREO2': new FormControl('', Validators.email),
      'OBSERVACIONES': new FormControl(''),
      'ESTADO_CON': new FormControl('Activo'),
    });
  }

  // Creación de formulario de registro de condición
  private createFormGroupCondition(): FormGroup {
    return new FormGroup({
      'ID_CONDICION_COD': new FormControl( this.idCondicion, Validators.required),
      'TIPO_CONDICION_COD': new FormControl('', Validators.required),
      'INFORMACION_COD': new FormControl('', Validators.required),
      'ESTADO_COD': new FormControl('Activo', Validators.required),
    });
  }

  // Creación de formularios de registro de catálogos
  private createFormCatalog(): FormGroup {
    return new FormGroup({
      'ID_CATALOG_CAT': new FormControl( this.idCatalog, Validators.required),
      'CATALAGO_CAT': new FormControl('', Validators.required),
      'DESCRIPCION_CAT': new FormControl('', Validators.required),
      'URL_CATALAGO_CAT': new FormControl('', Validators.required),
      'ESTADO_CAT': new FormControl('Activo', Validators.required),
    });
  }

  public actionReference(typeAction:string, elementData: ReferenceData = null!){
    if (typeAction === 'REG_REF') {
      let dataTable: Array<any> = this.dataSourceReference.data;
      dataTable.push(this.formGroupReferences.value);
      this.dataSourceReference.data = dataTable;
      this.formGroupReferences.reset();
      this.idReferencia += 1;
      this.NUMERO_REFERENCIA?.setValue(this.idReferencia);
      this.ESTADO_REF?.setValue('Activo');
      this._resourcesService.openSnackBar(`Registro Exitoso`);
    }else if(typeAction === 'GET_REF'){
      this.typeFormReference = 'MOD_REF';
      this.formGroupReferences.setValue(elementData);
    }else if(typeAction === 'MOD_REF'){
      this.dataSourceReference.data.map( (element:ReferenceData) => {
        if (element.NUMERO_REFERENCIA === this.NUMERO_REFERENCIA?.value) {
          element.CORREO_REF = this.CORREO_REF?.value;
          element.DIRECCION_REF = this.DIRECCION_REF?.value;
          element.RFC_REF = this.RFC_REF?.value;
          element.EMPRESA_REF = this.EMPRESA_REF?.value;
          element.TELEFONO_REF = this.TELEFONO_REF?.value;
          this.formGroupReferences.reset();
          this.typeFormReference = 'REG_REF';
          this.NUMERO_REFERENCIA?.setValue(this.dataSourceReference.data.length + 1);
          this.ESTADO_REF?.setValue('Activo');
          this._resourcesService.openSnackBar(`Modificación Exitosa`);
        }
      });
    }else if(typeAction === 'ELI_REF'){
      let dataReference: Array<ReferenceData> = [];
      this.dataSourceReference.data.map( (element:ReferenceData) => {
        if (element.NUMERO_REFERENCIA === elementData.NUMERO_REFERENCIA) {
          element.ESTADO_REF = 'Eliminado';
        }
        dataReference.push(element);
      });
      this.dataSourceReference.data = dataReference;
      this.formGroupReferences.reset();
      this.ESTADO_REF?.setValue('Activo');
      this.NUMERO_REFERENCIA?.setValue(this.dataSourceReference.data.length + 1);
      this._resourcesService.openSnackBar(`Eliminación Exitosa`);

      /* let dataTable = this.dataSourceReference.data.filter((element:ReferenceData) => element.NUMERO_REFERENCIA !== elementData.NUMERO_REFERENCIA);
      if (this.typeForm.type === 'REGI') {
        let contId:number = 1;
        dataTable.map((element:ReferenceData)=>{
          element.NUMERO_REFERENCIA = contId;
          contId++;
        });
      }
      this.dataSourceReference.data = dataTable;
      this.formGroupReferences.reset();
      this.ESTADO_REF?.setValue('Activo');
      this.NUMERO_REFERENCIA?.setValue(this.dataSourceReference.data.length + 1);
      this._resourcesService.openSnackBar(`Eliminación Exitosa`); */
    }
  }

  public actionContact(typeAction:string, elementData: ContactData = null!){
    if (typeAction === 'REG_CON') {
      let dataTable: Array<any> = this.dataSourceContact.data;
      dataTable.push(this.formGroupContact.value);
      this.dataSourceContact.data = dataTable;
      this.formGroupContact.reset();
      this.idContacto += 1;
      this.ID_CONTACTO?.setValue(this.idContacto);
      this.ESTADO_CON?.setValue('Activo');
      this._resourcesService.openSnackBar(`Registro Exitoso`);
    }else if(typeAction === 'GET_CON'){
      this.typeFormContact = 'MOD_CON';
      this.formGroupContact.setValue(elementData);
    }else if(typeAction === 'MOD_CON'){
      this.dataSourceContact.data.map( (element:ContactData) => {
        if (element.ID_CONTACTO === this.ID_CONTACTO?.value) {
          element.NOMBRE_CONTACTO = this.NOMBRE_CONTACTO?.value;
          element.TIPO_CONTACTO = this.TIPO_CONTACTO?.value;
          element.CALLE = this.CALLE?.value;
          element.NUMERO_EXTERIOR = this.NUMERO_EXTERIOR?.value;
          element.NUMERO_INTERIOR = this.NUMERO_INTERIOR?.value;
          element.CODIGO_POSTAL = this.CODIGO_POSTAL?.value;
          element.MUNICIPIO = this.MUNICIPIO?.value;
          element.ENTIDAD = this.ENTIDAD?.value;
          element.PAIS = this.PAIS?.value;
          element.TELEFONO_PRINCIPAL = this.TELEFONO_PRINCIPAL?.value;
          element.TELEFONO_SECUNDARIO = this.TELEFONO_SECUNDARIO?.value;
          element.CORREO1 = this.CORREO1?.value;
          element.CORREO2 = this.CORREO2?.value;
          element.OBSERVACIONES = this.OBSERVACIONES?.value;
          this.formGroupContact.reset();
          this.typeFormContact = 'REG_CON'
          this.ID_CONTACTO?.setValue(this.dataSourceContact.data.length + 1);
          this.ESTADO_CON?.setValue('Activo');
          this._resourcesService.openSnackBar(`Modificación Exitosa`);
        }
      });
    }else if(typeAction === 'ELI_CON'){
      let dataContact: Array<ContactData> = [];
      this.dataSourceContact.data.map( (element:ContactData) => {
        if (element.ID_CONTACTO === elementData.ID_CONTACTO) {
          element.ESTADO_CON = 'Eliminado';
        }
        dataContact.push(element);
      });
      this.dataSourceContact.data = dataContact;
      this.formGroupContact.reset();
      this.ESTADO_CON?.setValue('Activo');
      this.ID_CONTACTO?.setValue(this.dataSourceContact.data.length + 1);
      this._resourcesService.openSnackBar(`Eliminación Exitosa`);


      /* let dataTable:Array<ContactData> = this.dataSourceContact.data.filter((element:ContactData) => element.ID_CONTACTO !== elementData.ID_CONTACTO);
      if (this.typeForm.type === 'REGI') {
        let contId:number = 1;
        dataTable.map((element:ContactData)=>{
          element.ID_CONTACTO = contId;
          contId++;
        });
      }
      this.dataSourceContact.data = dataTable;
      this.formGroupContact.reset();
      this.ESTADO_CON?.setValue('Activo');
      this.ID_CONTACTO?.setValue(this.dataSourceContact.data.length + 1);
      this._resourcesService.openSnackBar(`Eliminación Exitosa`); */
    }
  }

  public actionCondition(typeAction:string, elementData: ConditionData = null!){
    if (typeAction === 'REG_COD') {
      let dataTable: Array<any> = this.dataSourceCondition.data;
      dataTable.push(this.formGroupCondition.value);
      this.dataSourceCondition.data = dataTable;
      this.formGroupCondition.reset();
      this.idCondicion += 1;
      this.ID_CONDICION_COD?.setValue(this.idCondicion);
      this.ESTADO_COD?.setValue('Activo');
      this._resourcesService.openSnackBar(`Registro Exitoso`);
    }else if(typeAction === 'GET_COD'){
      this.typeFormCondition = 'MOD_COD';
      this.formGroupCondition.setValue(elementData);
    }else if(typeAction === 'MOD_COD'){
      this.dataSourceCondition.data.map( (element:ConditionData) => {
        if (element.ID_CONDICION_COD === this.ID_CONDICION_COD?.value) {
          element.TIPO_CONDICION_COD = this.TIPO_CONDICION_COD?.value;
          element.INFORMACION_COD = this.INFORMACION_COD?.value;
          this.formGroupCondition.reset();
          this.typeFormCondition = 'REG_COD'
          this.ID_CONDICION_COD?.setValue(this.dataSourceCondition.data.length + 1);
          this.ESTADO_COD?.setValue('Activo');
          this._resourcesService.openSnackBar(`Modificación Exitosa`);
        }
      });
    }else if(typeAction === 'ELI_COD'){
      let dataCondition: Array<ConditionData> = [];
      this.dataSourceCondition.data.map( (element:ConditionData) => {
        if (element.ID_CONDICION_COD === elementData.ID_CONDICION_COD) {
          element.ESTADO_COD = 'Eliminado';
        }
        dataCondition.push(element);
      });
      this.dataSourceCondition.data = dataCondition;
      this.formGroupCondition.reset();
      this.ESTADO_COD?.setValue('Activo');
      this.ID_CONDICION_COD?.setValue(this.dataSourceCondition.data.length + 1);
      this._resourcesService.openSnackBar(`Eliminación Exitosa`);

      /* let dataTable = this.dataSourceCondition.data.filter((element:ConditionData) => element.ID_CONDICION_COD !== elementData.ID_CONDICION_COD);
      if (this.typeForm.type === 'REGI') {
        let contId:number = 1;
        dataTable.map((element:ConditionData)=>{
          element.ID_CONDICION_COD = contId;
          contId++;
        });
      }
      this.dataSourceCondition.data = dataTable;
      this.formGroupCondition.reset();
      this.ESTADO_COD?.setValue('Activo');
      this.ID_CONDICION_COD?.setValue(this.dataSourceCondition.data.length + 1);
      this._resourcesService.openSnackBar(`Eliminación Exitosa`); */
    }
  }

  public actionCatalog(typeAction:string, elementData: CatalogData = null!){
    if (typeAction === 'REG_CAT') {
      let dataTable: Array<any> = this.dataSourceCatalog.data;
      dataTable.push(this.formGroupCatalog.value);
      this.dataSourceCatalog.data = dataTable;
      this.formGroupCatalog.reset();
      this.idCatalog += 1;
      this.ID_CATALOG_CAT?.setValue(this.idCatalog);
      this.ESTADO_CAT?.setValue('Activo');
      this._resourcesService.openSnackBar(`Registro Exitoso`);
    }else if(typeAction === 'GET_CAT'){
      this.typeFormCatalog = 'MOD_CAT';
      this.formGroupCatalog.setValue(elementData);
    }else if(typeAction === 'MOD_CAT'){
      this.dataSourceCatalog.data.map( (element:CatalogData) => {
        if (element.ID_CATALOG_CAT === this.ID_CATALOG_CAT?.value) {
          element.CATALAGO_CAT = this.CATALAGO_CAT?.value;
          element.DESCRIPCION_CAT = this.DESCRIPCION_CAT?.value;
          element.URL_CATALAGO_CAT = this.URL_CATALAGO_CAT?.value;
          this.formGroupCatalog.reset();
          this.typeFormCatalog = 'REG_CAT'
          this.ID_CATALOG_CAT?.setValue(this.dataSourceCatalog.data.length + 1);
          this.ESTADO_CAT?.setValue('Activo');
          this._resourcesService.openSnackBar(`Modificación Exitosa`);
        }
      });
    }else if(typeAction === 'ELI_CAT'){
      let dataCatalog: Array<CatalogData> = [];
      this.dataSourceCatalog.data.map( (element:CatalogData) => {
        if (element.ID_CATALOG_CAT === elementData.ID_CATALOG_CAT) {
          element.ESTADO_CAT = 'Eliminado';
        }
        dataCatalog.push(element);
      });
      this.dataSourceCatalog.data = dataCatalog;
      this.formGroupCatalog.reset();
      this.ESTADO_CAT?.setValue('Activo');
      this.ID_CATALOG_CAT?.setValue(this.dataSourceCatalog.data.length + 1);
      this._resourcesService.openSnackBar(`Eliminación Exitosa`);

      /* let dataTable = this.dataSourceCatalog.data.filter((element:CatalogData) => element.ID_CATALOG_CAT !== elementData.ID_CATALOG_CAT);
      if (this.typeForm.type === 'REGI') {
        let contId:number = 1;
        dataTable.map((element:CatalogData)=>{
          element.ID_CATALOG_CAT = contId;
          contId++;
        });
      }
      this.dataSourceCatalog.data = dataTable;
      this.formGroupCatalog.reset();
      this.ESTADO_CAT?.setValue('Activo');
      this.ID_CATALOG_CAT?.setValue(this.dataSourceCatalog.data.length + 1);
      this._resourcesService.openSnackBar(`Eliminación Exitosa`); */
    }
  }

  public validateRepeatedReference(typeInput:string) {
    if (typeInput === 'CORREO_REF') {
      let isValid:boolean = this.dataSourceReference.data.some((element:ReferenceData) => element.CORREO_REF === this.CORREO_REF?.value);
      if (isValid && this.typeFormReference !== 'MOD_REF') {
        this.CORREO_REF?.setErrors({'dataRepeated':true});
        // this._resourcesService.openSnackBar(`El correo ${this.CORREO_REF?.value} ya se encuentra registrado.`);
      }
    }else if (typeInput === 'RFC_REF') {
      let isValid:boolean = this.dataSourceReference.data.some((element:ReferenceData) => element.RFC_REF === this.RFC_REF?.value);
      if (isValid && this.typeFormReference !== 'MOD_REF') {
        this.RFC_REF?.setErrors({'dataRepeated':true});
        // this._resourcesService.openSnackBar(`El R.F.C  ${this.RFC_REF?.value} ya se encuentra registrado.`);
      }
    }
  }

  // Método para reajustar los botones según sus dimensiones
  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }

  public changeTipo() {
    if (this.TIPO?.value === 'Nacional') {
      this.RFC?.enable();
      this.TAXID?.disable();
      this.TAXID?.setValue('');
    }else if (this.TIPO?.value === 'Extranjero') {
      this.TAXID?.enable();
      this.RFC?.disable();
      this.RFC?.setValue('');
    }else{
      this.RFC?.setValue('');
      this.TAXID?.setValue('');
      this.RFC?.disable();
      this.TAXID?.disable();
    }
  }

  // Método para ejecutar una alerta
  public async alert(type: string, dataElement: any = null):Promise<void> {
    let dataDialog: AlertData = {} as AlertData;
    if (type === 'ELI_REF') {
      dataDialog = {
        icon: "warning",
        title: "Eliminar Referencia",
        description: "¿Está seguro de eliminar la referencia?"
      };
    }else if(type === 'ELI_CON'){
      dataDialog = {
        icon: "warning",
        title: "Eliminar Contacto",
        description: "¿Está seguro de eliminar el contacto?"
      };
    }else if(type === 'ELI_COD'){
      dataDialog = {
        icon: "warning",
        title: "Eliminar Condición",
        description: "¿Está seguro de eliminar la condición?"
      };
    }else if(type === 'ELI_CAT'){
      dataDialog = {
        icon: "warning",
        title: "Eliminar Catálago",
        description: "¿Está seguro de eliminar el catálago?"
      };
    }else if(type === 'REG_REV'){
      dataDialog = {
        icon: "warning",
        title: "Registro de Proveedor",
        description: "¿Está seguro de registrar el proveedor?"
      };
    }else if(type === 'SAV_REV'){
      dataDialog = {
        icon: "warning",
        title: "Guardar Información",
        description: "¿Está seguro de guardar la información del proveedor?"
      };
    }else if(type === 'SET_REV' && this.typeForm.type === 'REGI'){
      dataDialog = {
        icon: "warning",
        title: "Establecer Información",
        description: "¿Deseas establecer la información guardada del proveedor?"
      };
    }else if(type === 'EXIT' && this.typeForm.type === 'REGI'){
      dataDialog = {
        icon: "warning",
        title: "Salir",
        description: "¿Deseas guardar la información del registro antes de salir?",
        btnRechazar: true,
      };
    }else if (type === 'EXIT' && this.typeForm.type === 'EDIT') {
      dataDialog = {
        icon: "warning",
        title: "Salir",
        description: "¿Está seguro de salir? No se guardarán los cambios realizados",
      };
    }else if(type === 'UPD_REV'){
      dataDialog = {
        icon: "warning",
        title: "Modificación de Proveedor",
        description: "¿Está seguro de modificar el proveedor?",
      };
    }

    // Se ejecuta la alerta
    this._dialog.open(AlertComponent, {
      data: dataDialog,
      disableClose: true,
    }).afterClosed().subscribe((result) => {
      if (type === 'ELI_REF' && result) {
        this.actionReference(type, dataElement);
      }else if (type === 'ELI_CON' && result) {
        this.actionContact(type, dataElement);
      }else if (type === 'ELI_COD' && result) {
        this.actionCondition(type, dataElement);
      }else if (type === 'ELI_CAT' && result) {
        this.actionCatalog(type, dataElement);
      }else if (type === 'REG_REV' && result) {
        this.revisionForms();
      }else if (type === 'UPD_REV' && result) {
        this.revisionForms();
      }else if ((type === 'SAV_REV' || type === 'EXIT') && result === true && this.typeForm.type === 'REGI') {
        this.saveLocalProvider();
      }else if (type === 'SET_REV' && result) {
        this.setLocalProvider(dataElement);
      }else if (type === 'EXIT' && result === 'rechazar'){
        this._router.navigate(['/sam/providers']);
      }else if(type === 'EXIT' && result && this.typeForm.type === 'EDIT'){
        this._router.navigate(['/sam/providers']);
      }
    });

  }

  public revisionForms(){
    let hasErrorForm:boolean = false;
    this.dataSourceRevision.data.map((element:RevisionData)=>{
      switch (element.NO) {
        case 1:
          if(this.formGroupInformation.invalid){
            element.TYPE_REV = 'ERROR';
            element.MENSAJE_REV = 'Formulario incorrecto';
            hasErrorForm = true;
          }else{
            element.TYPE_REV = 'EXITO';
          }
          break;
        case 2:
          if(this.dataSourceReference.data.length < 1){
            element.TYPE_REV = 'ERROR';
            element.MENSAJE_REV = 'Debe haber al menos un registro en la tabla de Referencias';
            hasErrorForm = true;
          }else{
            element.TYPE_REV = 'EXITO';
          }
          break;
        case 3:
          if(this.dataSourceContact.data.length < 1){
            element.TYPE_REV = 'ERROR';
            element.MENSAJE_REV = 'Debe haber al menos un registro en la tabla de Contactos';
            hasErrorForm = true;
          }else{
            element.TYPE_REV = 'EXITO';
          }
          break;
        case 4:
          if(this.dataSourceCondition.data.length < 1){
            element.TYPE_REV = 'ERROR';
            element.MENSAJE_REV = 'Debe haber al menos un registro en la tabla de Condiciones';
            hasErrorForm = true;
          }else{
            element.TYPE_REV = 'EXITO';
          }
          break;
        case 5:
          let filterPayment1 = this.task.subtasks?.some((element: PaymentData) => element.completed);
          let filterPayment2 = this.subtasks?.some((element: PaymentData) => element.completed);

          if (!filterPayment1 && !filterPayment2) {
            element.TYPE_REV = 'ERROR';
            element.MENSAJE_REV = 'Debe haber al menos un registro seleccionado en los Medios de Pago';
            hasErrorForm = true;
          }else{
            element.TYPE_REV = 'EXITO';
          }
          break;
        case 6:
          if(this.dataSourceCatalog.data.length < 1){
            element.TYPE_REV = 'ERROR';
            element.MENSAJE_REV = 'Debe haber al menos un registro en la tabla de Catálagos';
            hasErrorForm = true;
          }else{
            element.TYPE_REV = 'EXITO';
          }
          break;
        default:
          hasErrorForm = true;
          break;
      }
    });
    if (!hasErrorForm) {
      this.createProvider();
    }
  }

  private async createProvider(){
    let objResponse: RegisterForm = await this.generateObjForm();
    const formulario: RegisterProvider = {
      user: this._resourcesService.getUser(),
      line: '1',
      obj_response: JSON.stringify(objResponse),
    }
    if (this.typeForm.type === 'REGI') {
      await lastValueFrom(this._providerService.registerForm(formulario)).then(
        (responseData: ResponseFormProvider) => {
          if (!responseData.error) {
            this._resourcesService.openSnackBar('¡Registro de Proveedor Correcto!');
            this._router.navigate(['/sam/providers']);
            if (this.isFormLocalSave) {
              this.removeSaveProvider();
            }
          }
        }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
      );
    }else{
      await lastValueFrom(this._providerService.updateForm(formulario)).then(
        (responseData: ResponseFormProvider) => {
          if (!responseData.error) {
            this._resourcesService.openSnackBar('¡Modificación de Proveedor Correcto!');
            this._router.navigate(['/sam/providers']);
          }
        }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
      );
    }

  }

  private async removeSaveProvider(){
    let user:string = this._resourcesService.getUser();
    let strSaveProvider:string = localStorage.getItem('save_provider')!;
    let objEncSaveProvider: Array<string> = JSON.parse(strSaveProvider);
    let arrSaveProvider: Array<string> = [];
    objEncSaveProvider.map(async(element:string) => {
      let decSaveProvider:string = await this._encService.desencriptar(element);
      let objSaveProvider: ProviderSave = JSON.parse(decSaveProvider);
      let decUser:string = await this._encService.desencriptar(objSaveProvider.USER);
      if (decUser !== user) {
        arrSaveProvider.push(element);
      }
    });
    localStorage.setItem('save_provider', JSON.stringify(arrSaveProvider));
  }

  private async generateObjForm() {
    let formPersonal: InformationForm = {
      NUMERO_PROVEEDOR: (this.NUMERO_PROVEEDOR?.value).trim(),
      RAZON_SOCIAL: (this.RAZON_SOCIAL?.value).trim(),
      CORREO: (this.CORREO?.value).trim(),
      NOMBRE: (this.NOMBRE?.value).trim(),
      PRIMER_APELLIDO: (this.PRIMER_APELLIDO?.value).trim(),
      SEGUNDO_APELLIDO:  (this.SEGUNDO_APELLIDO?.value).trim(),
      LADA1: (this.LADA1?.value).trim(),
      TELEFONO1: (this.TELEFONO1?.value.toString()).trim(),
      LADA2: this.LADA2?.value !== null ? (this.LADA2?.value).trim() : '',
      TELEFONO2: this.TELEFONO2?.value !== null ? (this.TELEFONO2?.value.toString()).trim() : '',
      GIRO_EMPRESA: (this.GIRO_EMPRESARIAL?.value).trim(),
      TIPO_EMPRESA: (this.TIPO?.value).trim(),
      RFC: (this.RFC?.value).trim(),
      TAXID: this.TAXID?.value !== null ? (this.TAXID?.value).trim() : '',
      SITIO_WEB: (this.SITIOWEB?.value).trim(),
      ESTADO: (this.ESTADO?.value).trim(),

    }

    let arrReferences: Array<ReferenceForm> = [];
    this.dataSourceReference.data.forEach((element:ReferenceData) => {
      arrReferences.push({
        NUMERO_REFERENCIA: (element.NUMERO_REFERENCIA?.toString()!).trim(),
        EMPRESA: (element.EMPRESA_REF).trim(),
        CORREO: (element.CORREO_REF).trim(),
        TELEFONO: (element.TELEFONO_REF?.toString()).trim(),
        RFC: (element.RFC_REF).trim(),
        DIRECCION: (element.DIRECCION_REF).trim(),
        ESTADO: (element.ESTADO_REF).trim(),
      });
    });

    let arrContacts: Array<ContactForm> = [];
    this.dataSourceContact.data.forEach((element: ContactData) => {
      arrContacts.push({
        NUMERO_CONTACTO: (element.ID_CONTACTO.toString()).trim(),
        NOMBRE_CONTACTO: (element.NOMBRE_CONTACTO).trim(),
        TIPO_CONTACTO: (element.TIPO_CONTACTO).trim(),
        CALLE: (element.CALLE).trim(),
        NUMERO_EXTERIOR: (element.NUMERO_EXTERIOR.toString()).trim(),
        NUMERO_INTERIOR: element.NUMERO_INTERIOR !== null ? (element.NUMERO_INTERIOR.toString()).trim() : '',
        CODIGO_POSTAL: (element.CODIGO_POSTAL.toString()).trim(),
        MUNICIPIO: (element.MUNICIPIO).trim(),
        ENTIDAD: (element.ENTIDAD).trim(),
        PAIS: (element.PAIS).trim(),
        TELEFONO1: (element.TELEFONO_PRINCIPAL.toString()).trim(),
        TELEFONO2: element.TELEFONO_SECUNDARIO !== null ? (element.TELEFONO_SECUNDARIO.toString()).trim() : '',
        CORREO1: (element.CORREO1).trim(),
        CORREO2: element.CORREO2 !== null ? (element.CORREO2).trim() : '',
        OBSERVACIONES: element.OBSERVACIONES !== null ? (element.OBSERVACIONES).trim() : '',
        ESTADO: (element.ESTADO_CON).trim(),
      });
    });

    let arrCondition: Array<ConditionForm> = [];
    this.dataSourceCondition.data.forEach((element: ConditionData) => {
      arrCondition.push({
        NUMERO_CONDICION: (element.ID_CONDICION_COD?.toString()!).trim(),
        TIPO_CONDICION: (element.TIPO_CONDICION_COD).trim(),
        INFORMACION: (element.INFORMACION_COD).trim(),
        ESTADO: (element.ESTADO_COD).trim(),
      });
    });

    let arrPaymentMedia: Array<PaymentData> = this.task.subtasks?.concat(this.subtasks)!;

    let arrCatalog: Array<CatalogForm> = [];
    this.dataSourceCatalog.data.forEach((element: CatalogData) => {
      arrCatalog.push({
        NUMERO_CATALAGO: (element.ID_CATALOG_CAT?.toString()!).trim(),
        CATALAGO: (element.CATALAGO_CAT).trim(),
        DESCRIPCION: (element.DESCRIPCION_CAT).trim(),
        URL_CATALAGO: (element.URL_CATALAGO_CAT).trim(),
        ESTADO: (element.ESTADO_CAT).trim(),
      });
    });

    let objResponse: RegisterForm = {
      INFORMACION: formPersonal,
      REFERENCIAS: arrReferences,
      CONTACTOS: arrContacts,
      CONDICIONES: arrCondition,
      METODOS_PAGO: arrPaymentMedia,
      CATALAGOS: arrCatalog,
    }

    return objResponse;
  }

  private async saveLocalProvider(type:string = null!){
    let encUser: string = this._resourcesService.getUser();
    let user: string = await this._encService.desencriptar(encUser);

    // Se guarda en un objeto la información del formulario
    let objectSaveData: SaveData = {
      INFORMATION_PERSONAL: this.formGroupInformation.value,
      REFERENCES: this.dataSourceReference.data,
      CONTACTS: this.dataSourceContact.data,
      CONDITIONS: this.dataSourceCondition.data,
      PAYMENT_MEDIA: this.formatPaymentMedia(),
      CATALOGS: this.dataSourceCatalog.data
    };

    // El objeto del formulario se guarda en otro objeto con información del usuario
    let objSaveLocal: ProviderSave = {
      USER: encUser,
      OBJ_DATA: objectSaveData,
      FERE: this._resourcesService.getDateFormat()
    }

    // El objeto se transforma a una cadena
    let strSaveLocal: string = JSON.stringify(objSaveLocal);
    // La cadena es encriptada
    let encSaveLocal: string = await this._encService.encriptar(strSaveLocal);

    // Se obtienen los borradores guardados
    let saveProvider = localStorage.getItem('save_provider');

    // Si
    if (saveProvider === null) {
      let strProvider = JSON.stringify([encSaveLocal]);
      localStorage.setItem('save_provider', strProvider);
    }else{
      let arrSaveLocal:Array<string> = JSON.parse(saveProvider);
      let isLocatedUser: boolean = false;
      let arrSaveLocalTemp: Array<string> = [];
      await Promise.all( arrSaveLocal.map(async (element:string)=>{
        let decSaveProvier: string = await this._encService.desencriptar(element);
        let objSaveLocal: ProviderSave = JSON.parse(decSaveProvier);
        let userSaveLocal = await this._encService.desencriptar(objSaveLocal.USER)
        if ( userSaveLocal === user) {
          isLocatedUser = true;
          arrSaveLocalTemp.push(encSaveLocal);
        }else{
          arrSaveLocalTemp.push(element);
        }
      }));

      arrSaveLocal = arrSaveLocalTemp;
      if (!isLocatedUser) {
        arrSaveLocal.push(encSaveLocal);
      }

      // El objeto se transforma a una cadena
      let strSaveLocal: string = JSON.stringify(arrSaveLocal);
      localStorage.setItem('save_provider', strSaveLocal);
    }
    this._resourcesService.openSnackBar('La información del proveedor ha sido guardada exitosamente');
    this._router.navigate(['/sam/providers']);
  }

  public getErrorMessage(type:string) {
    if (type === 'RAZON_SOCIAL' && this.RAZON_SOCIAL?.hasError('required')) {
      return 'El campo Razón Social es obligatorio';
    }else if(type === 'CORREO' && this.CORREO?.hasError('required')) {
      return 'El campo Correo Electrónico es obligatorio';
    }else if(type === 'NOMBRE' && this.NOMBRE?.hasError('required')) {
      return 'El campo Nombre es obligatorio';
    }else if(type === 'PRIMER_APELLIDO' && this.PRIMER_APELLIDO?.hasError('required')) {
      return 'El campo Primer Apellido es obligatorio';
    }else if(type === 'SEGUNDO_APELLIDO' && this.SEGUNDO_APELLIDO?.hasError('required')) {
      return 'El campo Segundo Apellido es obligatorio';
    }else if(type === 'LADA1' && this.LADA1?.hasError('required')) {
      return 'Obligatorio';
    }else if(type === 'TELEFONO1' && this.TELEFONO1?.hasError('required')) {
      return 'El campo Teléfono Principal es obligatorio';
    }else if(type === 'GIRO_EMPRESARIAL' && this.GIRO_EMPRESARIAL?.hasError('required')) {
      return 'El campo Giro Empresarial es obligatorio';
    }else if(type === 'TIPO' && this.TIPO?.hasError('required')) {
      return 'El campo Tipo es obligatorio';
    }else if(type === 'RFC' && this.RFC?.hasError('pattern')) {
      return 'El campo R.F.C. no es válido';
    }else if(type === 'RFC' && this.RFC?.hasError('required')) {
      return 'El campo R.F.C. es obligatorio';
    }else if(type === 'TAXID' && this.TAXID?.hasError('required')) {
      return 'El campo Tax ID es obligatorio';
    }else if(type === 'SITIOWEB' && this.SITIOWEB?.hasError('required')) {
      return 'El campo Sitio Web es obligatorio';
    } else
    if(type === 'EMPRESA_REF' && this.EMPRESA_REF?.hasError('required')) {
      return 'El campo Empresa es obligatorio';
    } else if(type === 'CORREO_REF' && this.CORREO_REF?.hasError('required')) {
      return 'El campo Correo Electrónico es obligatorio';
    } else if(type === 'CORREO_REF' && this.CORREO_REF?.hasError('dataRepeated')) {
      return 'El Correo Electrónico ya se encuentra registrado.';
    } else if(type === 'CORREO_REF' && this.CORREO_REF?.hasError('email')) {
      return 'El campo Correo Electrónico no tiene formato correcto';
    } else if(type === 'TELEFONO_REF' && this.TELEFONO_REF?.hasError('required')) {
      return 'El campo Teléfono es obligatorio';
    } else if(type === 'RFC_REF' && this.RFC_REF?.hasError('pattern')) {
      return 'El campo R.F.C. no es válido';
    } else if(type === 'RFC_REF' && this.RFC_REF?.hasError('minlength')) {
      return 'El campo R.F.C. debe  tener 12 caracteres mínimo';
    } else if(type === 'RFC_REF' && this.RFC_REF?.hasError('required')) {
      return 'El campo R.F.C. es obligatorio';
    } else if(type === 'DIRECCION_REF' && this.DIRECCION_REF?.hasError('required')) {
      return 'El campo Dirección es obligatorio';
    } else
    if(type === 'ID_CONTACTO' && this.ID_CONTACTO?.hasError('required')) {
      return 'El campo Número de Contacto es obligatorio.';
    } else if(type === 'NOMBRE_CONTACTO' && this.NOMBRE_CONTACTO?.hasError('required')) {
      return 'El campo Nombre del Contacto es obligatorio.';
    } else if(type === 'TIPO_CONTACTO' && this.TIPO_CONTACTO?.hasError('required')) {
      return 'El campo Tipo de Contacto es obligatorio.';
    } else if(type === 'CALLE' && this.CALLE?.hasError('required')) {
      return 'El campo Calle es obligatorio.';
    } else if(type === 'NUMERO_EXTERIOR' && this.NUMERO_EXTERIOR?.hasError('required')) {
      return 'El campo Número Exterior es obligatorio.';
    } else if(type === 'NUMERO_INTERIOR' && this.NUMERO_INTERIOR?.hasError('required')) {
      return 'El campo Número Interior es obligatorio.';
    } else if(type === 'CODIGO_POSTAL' && this.CODIGO_POSTAL?.hasError('required')) {
      return 'El campo Código Postal es obligatorio.';
    } else if(type === 'MUNICIPIO' && this.MUNICIPIO?.hasError('required')) {
      return 'El campo Municipio es obligatorio.';
    } else if(type === 'ENTIDAD' && this.ENTIDAD?.hasError('required')) {
      return 'El campo Entidad es obligatorio.';
    } else if(type === 'PAIS' && this.PAIS?.hasError('required')) {
      return 'El campo País es obligatorio.';
    } else if(type === 'TELEFONO_PRINCIPAL' && this.TELEFONO_PRINCIPAL?.hasError('required')) {
      return 'El campo Teléfono Principal es obligatorio.';
    } else if(type === 'CORREO1' && this.CORREO1?.hasError('required')) {
      return 'El campo Correo Principal es obligatorio.';
    } else if(type === 'CORREO2' && this.CORREO2?.hasError('email')) {
      return 'El campo Correo Electrónico Secundarios no tiene formato correcto';
    } else if(type === 'OBSERVACIONES' && this.OBSERVACIONES?.hasError('required')) {
      return 'El campo Observaciones es obligatorio.';
    } else
    if(type === 'ID_CONDICION_COD' && this.ID_CONDICION_COD?.hasError('required')) {
      return 'El campo Número de Condición es obligatorio.';
    } else if(type === 'TIPO_CONDICION_COD' && this.TIPO_CONDICION_COD?.hasError('required')) {
      return 'El campo Tipo de Condición es obligatorio.';
    } else if(type === 'INFORMACION_COD' && this.INFORMACION_COD?.hasError('required')) {
      return 'El campo Información es obligatorio.';
    } else
    if(type === 'ID_CATALOG_CAT' && this.ID_CATALOG_CAT?.hasError('required')) {
      return 'El campo Número de Catálago es obligatorio.';
    } else if(type === 'CATALAGO_CAT' && this.CATALAGO_CAT?.hasError('required')) {
      return 'El campo Catálago es obligatorio.';
    } else if(type === 'DESCRIPCION_CAT' && this.DESCRIPCION_CAT?.hasError('required')) {
      return 'El campo Descripción es obligatorio.';
    } else if(type === 'URL_CATALAGO_CAT' && this.URL_CATALAGO_CAT?.hasError('required')) {
      return 'El campo URL del Catálago es obligatorio.';
    }else{
      return '';
    }
  }

  // Método para dar formato a las fechas y horas
  public formatDate(dateRegister:string, dateUpdate:string | null):string {
    let date:string = (dateUpdate === null) ? dateRegister : dateUpdate;
    let arrDateTime:Array<string> = date.split(' ');
    let arrDate:Array<string> = arrDateTime[0].split('-');
    return `${arrDate[2]}-${arrDate[1]}-${arrDate[0]} ${arrDateTime[1]}`;
  }

  public updateAllComplete() {
    this.allComplete = this.task.subtasks != null && this.task.subtasks.every(t => t.completed);
    this.allComplete = this.subtasks != null && this.subtasks.every(t => t.completed);
  }

  public someComplete(): boolean {
    if (this.task.subtasks == null) {
      return false;
    }
    if (this.subtasks == null) {
      return false;
    }
    return this.task.subtasks.filter(t => t.completed).length > 0 && !this.allComplete || this.subtasks.filter(t => t.completed).length > 0 && !this.allComplete;
  }

  public setAll(completed: boolean) {
    this.allComplete = completed;
    if (this.task.subtasks == null) {
      return;
    }
    this.task.subtasks.forEach(t => (t.completed = completed));
    this.subtasks.forEach(t => (t.completed = completed));
  }

  public redirectLink(link: string) {
    window.open(link, '_blank');
  }

  private formatPaymentMedia(){
    let mergePaymentData: Array<PaymentData> = this.task.subtasks?.concat(this.subtasks)!;
    let arrPaymentData:Array<PaymentData> = mergePaymentData.filter((element:PaymentData) => element.completed);
    return arrPaymentData;
  }

  public validateNumber(numberText:number){
    let strNumber = numberText.toString();

    this.TELEFONO1?.setValue(strNumber.substring(0, 10));
    /* if (strNumber.length > 10) {
       strNumber.substring(0, 10);
    }
    return strNumber.substring(0, 10); */
  }

  get NUMERO_PROVEEDOR() { return this.formGroupInformation.get('NUMERO_PROVEEDOR'); }
  get RAZON_SOCIAL() { return this.formGroupInformation.get('RAZON_SOCIAL'); }
  get CORREO() { return this.formGroupInformation.get('CORREO'); }
  get NOMBRE() { return this.formGroupInformation.get('NOMBRE'); }
  get PRIMER_APELLIDO() { return this.formGroupInformation.get('PRIMER_APELLIDO'); }
  get SEGUNDO_APELLIDO() { return this.formGroupInformation.get('SEGUNDO_APELLIDO'); }
  get LADA1() { return this.formGroupInformation.get('LADA1'); }
  get TELEFONO1() { return this.formGroupInformation.get('TELEFONO1'); }
  get LADA2() { return this.formGroupInformation.get('LADA2'); }
  get TELEFONO2() { return this.formGroupInformation.get('TELEFONO2'); }
  get GIRO_EMPRESARIAL() { return this.formGroupInformation.get('GIRO_EMPRESARIAL'); }
  get TIPO() { return this.formGroupInformation.get('TIPO'); }
  get RFC() { return this.formGroupInformation.get('RFC'); }
  get TAXID() { return this.formGroupInformation.get('TAXID'); }
  get SITIOWEB() { return this.formGroupInformation.get('SITIOWEB'); }
  get ESTADO() { return this.formGroupInformation.get('ESTADO'); }

  get NUMERO_REFERENCIA() { return this.formGroupReferences.get('NUMERO_REFERENCIA'); }
  get EMPRESA_REF() { return this.formGroupReferences.get('EMPRESA_REF'); }
  get CORREO_REF() { return this.formGroupReferences.get('CORREO_REF'); }
  get TELEFONO_REF() { return this.formGroupReferences.get('TELEFONO_REF'); }
  get RFC_REF() { return this.formGroupReferences.get('RFC_REF'); }
  get DIRECCION_REF() { return this.formGroupReferences.get('DIRECCION_REF'); }
  get ESTADO_REF() { return this.formGroupReferences.get('ESTADO_REF'); }

  get ID_CONTACTO() { return this.formGroupContact.get('ID_CONTACTO') }
  get NOMBRE_CONTACTO() { return this.formGroupContact.get('NOMBRE_CONTACTO') }
  get TIPO_CONTACTO() { return this.formGroupContact.get('TIPO_CONTACTO') }
  get CALLE() { return this.formGroupContact.get('CALLE') }
  get NUMERO_EXTERIOR() { return this.formGroupContact.get('NUMERO_EXTERIOR') }
  get NUMERO_INTERIOR() { return this.formGroupContact.get('NUMERO_INTERIOR') }
  get CODIGO_POSTAL() { return this.formGroupContact.get('CODIGO_POSTAL') }
  get MUNICIPIO() { return this.formGroupContact.get('MUNICIPIO') }
  get ENTIDAD() { return this.formGroupContact.get('ENTIDAD') }
  get PAIS() { return this.formGroupContact.get('PAIS') }
  get TELEFONO_PRINCIPAL() { return this.formGroupContact.get('TELEFONO_PRINCIPAL') }
  get TELEFONO_SECUNDARIO() { return this.formGroupContact.get('TELEFONO_SECUNDARIO') }
  get CORREO1() { return this.formGroupContact.get('CORREO1') }
  get CORREO2() { return this.formGroupContact.get('CORREO2') }
  get OBSERVACIONES() { return this.formGroupContact.get('OBSERVACIONES') }
  get ESTADO_CON() { return this.formGroupContact.get('ESTADO_CON') }

  get ID_CONDICION_COD() { return this.formGroupCondition.get('ID_CONDICION_COD') }
  get TIPO_CONDICION_COD() { return this.formGroupCondition.get('TIPO_CONDICION_COD') }
  get INFORMACION_COD() { return this.formGroupCondition.get('INFORMACION_COD') }
  get ESTADO_COD() { return this.formGroupCondition.get('ESTADO_COD') }

  get ID_CATALOG_CAT() { return this.formGroupCatalog.get('ID_CATALOG_CAT') }
  get CATALAGO_CAT() { return this.formGroupCatalog.get('CATALAGO_CAT') }
  get DESCRIPCION_CAT() { return this.formGroupCatalog.get('DESCRIPCION_CAT') }
  get URL_CATALAGO_CAT() { return this.formGroupCatalog.get('URL_CATALAGO_CAT') }
  get ESTADO_CAT() { return this.formGroupCatalog.get('ESTADO_CAT') }
}
