import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom, map } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { DataFormDetails, DataMoneda, DetailsArtitle, FamiliesAndSubfamilies, InformationArtitle, ResponseArtitle, ResponseDataById, ResponseDataFamilies, ResponseDetails, ResponseFormDetails, ResponseInformation, TypeForm } from 'src/app/interfaces/acquisition-management/acquisition/artitle.interface';
import { ProviderInformation } from 'src/app/interfaces/acquisition-management/provider/provider.interface';
import { AlertData } from 'src/app/interfaces/alert.interface';
import { ArtitleService } from 'src/app/services/acquisition-management/acquisition/artitle.service';
import { ProviderService } from 'src/app/services/acquisition-management/provider/provider.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { ArtitleDetailsFormComponent } from '../artitle-details-form/artitle-details-form.component';
import { ArtitleDescriptionFormComponent } from '../artitle-description-form/artitle-description-form.component';
import { ArtitleDetailsComponent } from '../artitle-details/artitle-details.component';
import { ActivatedRoute, Router } from '@angular/router';
import { EncService } from 'src/app/services/enc/enc.service';
import * as catalogoMonedas from 'src/assets/json/catalogo_monedas.json';
import { ResponseData } from 'src/app/interfaces/response-data';

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

  public btnSmall:boolean;
  public isLoading:boolean;
  public txtBuscador: string;
  private isChangeImg: boolean;


  public displayedColumnsInformation: Array<string>;
  public dataSourceInformation: MatTableDataSource<InformationArtitle>;

  public arrFamilies: Array<FamiliesAndSubfamilies>;
  public arrSubfamilies: Array<FamiliesAndSubfamilies>;
  public arrProvider: Array<ResponseArtitle>;

  public formGroup: FormGroup;
  public typeForm:TypeForm;
  public arrArtitle: Array<any>;

  public arrCatalogoMonedas: Array<DataMoneda>;

  constructor(
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _resourcesService: ResourcesService,
    private _artitleServices: ArtitleService,
    private _activatedRouter: ActivatedRoute,
    private _router: Router,
  ) {
    this.displayedColumnsInformation = ['IMAGEN','PROVEEDOR','DESCRIPCION','CARACTERISTICAS','CANTIDAD_DETALLES','ESTADO','ACCIONES'];
    this.dataSourceInformation = new MatTableDataSource<InformationArtitle>();
    this.typeForm = {} as TypeForm;
    this.arrFamilies = [];
    this.arrSubfamilies = [];
    this.arrProvider = [];
    this.arrArtitle = [];
    this.arrCatalogoMonedas = [];
    this.txtBuscador = '';
    this.btnSmall = false;
    this.isLoading = false;
    this.isChangeImg = false;

    this.formGroup = this.createFormGroup();
  }

  ngOnInit(): void {
    let catalogo = catalogoMonedas;
    this.arrCatalogoMonedas = catalogo.arrMoneda;
    this.arrCatalogoMonedas.sort((a,b) => a.moneda.localeCompare(b.moneda));

    this.getFamiliesAndSubfamilies();
    this.getDataForm();
  }

  private async getDataForm() {
    this.isLoading = true;
    let encForm:string = this._activatedRouter.snapshot.paramMap.get('form')!;
    let strForm:string = await this._encService.desencriptar(encForm);
    this.typeForm = JSON.parse(strForm);
    if (this.typeForm.type === 'EDIT') {
      this.getArtitleById(this.typeForm.element!.ID_ARTICULO);
    }else{
      this.isLoading = false;
    }

  }

  private async getArtitleById(idArtitle:string) {
    await lastValueFrom(this._artitleServices.getArtitleById({ lineNumber: 1, idArtitle: await this._encService.encriptar(idArtitle)})).then(
      (responseData:ResponseDataById) => {
        this.setFormData(responseData.response);
      },
      (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  private setFormData(arrArtitle:ResponseArtitle) {

    this.NO?.setValue(arrArtitle.NUMERO_ARTICULO);
    this.CODIGO?.setValue(arrArtitle.CODIGO);
    this.ARTICULO?.setValue(arrArtitle.ARTICULO);
    let objFamily:FamiliesAndSubfamilies = this.arrFamilies.find((element:FamiliesAndSubfamilies) => element.ID === arrArtitle.ID_FAMILIA)!;
    this.FAMILIA?.setValue(objFamily);
    let objSubfamily = objFamily.SUBFAMILIAS.find((element:FamiliesAndSubfamilies) => element.ID === arrArtitle.ID_SUBFAMILIA);
    this.SUBFAMILIA?.setValue(objSubfamily);

    let arrInformationTemp:Array<InformationArtitle> = []
    arrArtitle.INFORMACION.map((element:ResponseInformation) => {
      let arrDetailsTemp: Array<DetailsArtitle> = [];
      element.DETALLES.map((elementDetails:ResponseDetails) => {
        let objMoneda:DataMoneda = this.arrCatalogoMonedas.find((element:DataMoneda) => element.codigo === elementDetails.MONEDA)!;
        arrDetailsTemp.push({
          NO: elementDetails.NUMERO_DETALLE,
          CODIGO: elementDetails.CODIGO,
          MODELO: elementDetails.MODELO,
          MONEDA: objMoneda,
          CANTIDAD: elementDetails.CANTIDAD,
          PRECIO: elementDetails.PRECIO,
          CARACTERISTICAS: elementDetails.CARACTERISTICAS,
          ESTADO: elementDetails.ESTADO,
        });
      });
      arrInformationTemp.push({
        NO: element.NUMERO_DESCRIPCION,
        IMAGEN: null,
        URLIMAGE: element.IMAGEN,
        DESCRIPCION: element.DESCRIPCION!,
        CARACTERISTICAS: element.CARACTERISTICAS === null ? '' : element.CARACTERISTICAS,
        TIPO: element.TIPO,
        PROVEEDOR: element.PROVEEDOR,
        COMPRA_WEB: element.COMPRA_WEB,
        ESTADO: element.ESTADO,
        DETAILS: arrDetailsTemp,
      });
    });

    this.dataSourceInformation.data = arrInformationTemp;
    this.isLoading = false;
  }

  private createFormGroup() {
    return new FormGroup({
      'NO': new FormControl('1', Validators.required),
      'CODIGO': new FormControl('', Validators.required),
      'ARTICULO': new FormControl('', Validators.required),
      'FAMILIA': new FormControl('', Validators.required),
      'SUBFAMILIA': new FormControl({ value: '', disabled: true }, Validators.required),
    });
  }

  private async getFamiliesAndSubfamilies() {
    await lastValueFrom(this._artitleServices.getFamiliesAndSubfamilies()).then(
      (responseData:ResponseDataFamilies) => {
        this.arrFamilies = responseData.response
      },
      (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  public getSubfamily(){
    let family:FamiliesAndSubfamilies = this.FAMILIA?.value;
    this.arrSubfamilies = family.SUBFAMILIAS;
    this.SUBFAMILIA?.enable();
  }

  public openDialog(type:string, elementData?:any) {
    // Abrir el formulario de información
    if (type === 'FORM_INFO') {
      this._dialog.open(ArtitleDescriptionFormComponent, {
        disableClose: true,
        width: '1200px',
        data: elementData,
      }).afterClosed().subscribe((result:InformationArtitle) => {
        if (result && elementData === undefined) {
          let dataSource:Array<InformationArtitle> = this.dataSourceInformation.data;
          result.NO = (this.dataSourceInformation.data.length + 1).toString();
          dataSource.push(result);
          this.dataSourceInformation.data = dataSource;

        } else if (result && elementData !== undefined) {
          let arrInformation: Array<InformationArtitle> = [];
          this.dataSourceInformation.data.map((element:InformationArtitle) => {
            if (element.NO === result.NO) {
              element = result;
            }
            arrInformation.push(element)
          });
          this.dataSourceInformation.data = arrInformation;
        }
      });
    // Abrir la alerta de la eliminación de información
    } else if (type === 'ELIM_INFO') {
      let objElement: AlertData = { title: 'Eliminar Información', description: '¿Está seguro de eliminar esta información?', icon: 'warning' };
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data:objElement
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.dataSourceInformation.data = this.dataSourceInformation.data.map(
            (element:InformationArtitle) => {
              if (element.NO === elementData.NO) {
                element.ESTADO = 'Eliminado';
              }
              return element;
            }
          );
        }
        // this.openDialog('DETAILS', this.dataSourceInformation.data);
      });
    } else if (type === 'REST_INFO') {
      let objElement: AlertData = { title: 'Restaurar Información', description: '¿Está seguro de restaurar esta información?', icon: 'warning' };
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data:objElement
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.dataSourceInformation.data = this.dataSourceInformation.data.map(
            (element:InformationArtitle) => {
              if (element.NO === elementData.NO) {
                element.ESTADO = 'Activo';
              }
              return element;
            }
          );
        }
        // this.openDialog('DETAILS', this.dataSourceInformation.data);
      });
    // Abre el formulario de detalles
    } else if (type === 'FORM_DETAILS') {
      let objElement: DataFormDetails = { element: elementData.element, itemElement: elementData.itemElement }
      this._dialog.open(ArtitleDetailsFormComponent, {
        disableClose: true,
        width: '500px',
        data: objElement,
      }).afterClosed().subscribe((result) => {
        this.openDialog('DETAILS', result);
      });
    // Abrir la alerta de la eliminación de detalle
    } else if (type === 'ELIM_DETAILS') {
      let objElement: AlertData = { title: 'Eliminar Detalle', description: '¿Está seguro de eliminar el detalle?', icon: 'warning' };
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data:objElement
      }).afterClosed().subscribe((result) => {
        let tableInformation:InformationArtitle = elementData.element;
        if (result) {
          let arrTableInformation: Array<DetailsArtitle> = tableInformation.DETAILS.map(
            (element:DetailsArtitle) => {
              if (element.NO === elementData.itemElement.NO) {
                element.ESTADO = 'Eliminado';
              }
              return element;
            }
          );
          tableInformation.DETAILS = arrTableInformation;
        }
        this.openDialog('DETAILS', tableInformation);
      });
    } else if (type === 'REST_DETAILS') {
      let objElement: AlertData = { title: 'Restaurar Detalle', description: '¿Está seguro de restaurar el detalle?', icon: 'warning' };
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data:objElement
      }).afterClosed().subscribe((result) => {
        let tableInformation:InformationArtitle = elementData.element;
        if (result) {
          let arrTableInformation: Array<DetailsArtitle> = tableInformation.DETAILS.map(
            (element:DetailsArtitle) => {
              if (element.NO === elementData.itemElement.NO) {
                element.ESTADO = 'Activo';
              }
              return element;
            }
          );
          tableInformation.DETAILS = arrTableInformation;
        }
        this.openDialog('DETAILS', tableInformation);
      });
    // Abrir el dialogo de consulta de detalles
    } else if (type === 'DETAILS') {
      this._dialog.open(ArtitleDetailsComponent, {
        disableClose: true,
        width: '1300px',
        data: elementData,
      }).afterClosed().subscribe((result:ResponseFormDetails) => {
        if (result.typeForm === 'FORM_DETAILS') {
          let objElement = { element: result.element, itemElement: result.itemElement }
          this.openDialog(result.typeForm, objElement);
        } else if (result.typeForm === 'CLOSE') {
          let elementDataResult: InformationArtitle = result.element;
          this.dataSourceInformation.data = this.dataSourceInformation.data.map((element:InformationArtitle) => {
            if (element.NO === elementDataResult.NO){
              element = elementDataResult;
            }
            return element;
          });
        } else if (result.typeForm === 'ELIM_DETAILS') {
          let objElement = {
            element: result.element,
            itemElement: result.itemElement
          }
          this.openDialog(result.typeForm, objElement);
        } else if (result.typeForm === 'REST_DETAILS') {
          let objElement = {
            element: result.element,
            itemElement: result.itemElement
          }
          this.openDialog(result.typeForm, objElement);
        }
      });
    } else if (type === 'REGI') {
      let objElement: AlertData = { title: 'Registro de artículo', description: '¿Está seguro de registrar el artículo?', icon: 'warning' };
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: objElement
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.register();
        }
      });
    } else if (type === 'EDIT') {
      let objElement: AlertData = { title: 'Modificación de artículo', description: '¿Está seguro de modificar el artículo?', icon: 'warning' };
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: objElement
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.update();
        }
      });
    }
  }

  public countDetails(arrDetails:Array<DetailsArtitle>){
    let count:number = 0;
    arrDetails.map((element:DetailsArtitle) => {
      if (element.ESTADO === 'Activo') {
        count++;
      }
    });
    let response: string = '';
    if (count === 0) {
      response = 'Sin detalles';
    } else if (count === 1) {
      response = '1 Detalle';
    } else {
      response = count + ' Detalles';
    }
    return response;
  }

  public checkValidation(): boolean {
    if (this.formGroup.valid) {
      if (this.dataSourceInformation.data.length > 0) {
        return !this.dataSourceInformation.data.every((element:InformationArtitle) => element.DETAILS.length > 0);
      } else {
        return true;
      }
    }else{
      return true;
    }
  }

  public async register() {
    await lastValueFrom(this._artitleServices.registerArtitle(this.createObjectResponse())).then(
      (request: ResponseData) => {
        this.resourcesService.openSnackBar('¡Registro Exitoso!');
        this._router.navigate(['/sam/artitles']);
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  public async update() {
    await lastValueFrom(this._artitleServices.updateArtitle(this.createObjectResponse())).then(
      (request: ResponseData) => {
        this.resourcesService.openSnackBar('¡Modificación Exitosa!');
        this._router.navigate(['/sam/artitles']);
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  private createObjectResponse () {
    let arrObjInformation: Array<any> = [];
    this.dataSourceInformation.data.map((elementInformation:InformationArtitle) => {
      let arrObjDetails: Array<any> = [];
      elementInformation.DETAILS.map((elementDetails:DetailsArtitle) => {
        arrObjDetails.push({
          NO: (elementDetails.NO).toString().trim(),
          CODIGO: (elementDetails.CODIGO).toString().trim(),
          MODELO: (elementDetails.MODELO).toString().trim(),
          MONEDA: elementDetails.MONEDA.codigo,
          CANTIDAD: (elementDetails.CANTIDAD).toString().trim(),
          PRECIO: (elementDetails.PRECIO).toString().trim(),
          ESTADO: (elementDetails.ESTADO).toString().trim(),
          CARACTERISTICAS: (elementDetails.CARACTERISTICAS).toString().trim(),
        });
      });
      arrObjInformation.push({
        NO: elementInformation.NO,
        IMAGEN: elementInformation.IMAGEN,
        URLIMAGE: elementInformation.URLIMAGE,
        DESCRIPCION: (elementInformation.DESCRIPCION).toString().trim(),
        CARACTERISTICAS: elementInformation.CARACTERISTICAS === '' ? null : (elementInformation.CARACTERISTICAS!).toString().trim(),
        TIPO: elementInformation.TIPO,
        PROVEEDOR: elementInformation.PROVEEDOR.NUMERO_PROVEEDOR,
        COMPRA_WEB: elementInformation.COMPRA_WEB,
        ESTADO: elementInformation.ESTADO,
        DETAILS: arrObjDetails,
      });
    });

    let objectResponse = {
      NO: (this.NO?.value).toString().trim(),
      CODIGO: (this.CODIGO?.value).toString().trim(),
      ARTICULO: (this.ARTICULO?.value).toString().trim(),
      FAMILIA: this.FAMILIA?.value.ID,
      SUBFAMILIA: this.SUBFAMILIA?.value.ID,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: '1',
      INFORMATION: arrObjInformation
    }

    return objectResponse;
  }

  public setImage (image:string, element:InformationArtitle) {
    if (element.NO.length === 10 && image.includes('01-GEAD-FO') ) {
      return 'http://192.168.1.4:8000/storage/GEAD/FO/' + image;
    } else {
      return image;
    }
  }

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

  get NO () { return this.formGroup.get('NO'); }
  get CODIGO () { return this.formGroup.get('CODIGO'); }
  get ARTICULO () { return this.formGroup.get('ARTICULO'); }
  get FAMILIA () { return this.formGroup.get('FAMILIA'); }
  get SUBFAMILIA () { return this.formGroup.get('SUBFAMILIA'); }

}

