import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { SubcontratistItem, SubcontratistsResponse } from '../../../interfaces/personal-managment/subcontratists.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ResourcesService } from '../../../services/resources.service';
import { SubcontratistService } from '../../../services/personal-management/subcontratist.service';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { EncService } from '../../../services/enc.service';
import { FunctionsService } from '../../../services/functions.service';
import { ProviderService } from '../../../services/acquisition-management/provider.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { TypeFormSubcontract } from '../../../interfaces/personal-managment/subcontractist.interface';
import { SubcontratistDetailsDialogComponent } from './subcontratist-details-dialog/subcontratist-details-dialog.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-subcontratist',
    templateUrl: './subcontratist.component.html',
    styleUrl: './subcontratist.component.css',
    standalone: false
})
export class SubcontratistComponent implements OnInit, AfterViewInit {
  public screenMode: string;

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public changeOnTab : boolean = false;
  public hasError: boolean;
  public errorStr: string;

  public btnSmall: boolean;
  public cardSmall: boolean;

  public txtBuscadorSubcontratists: string;
  public displayedColumnsSubcontratists: Array<string>;
  public dataSourceSubcontratists: MatTableDataSource<SubcontratistItem>;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor(
    public resourcesService: ResourcesService,
    private _subcontratistService: SubcontratistService,
    private _dialog: MatDialog,
    private _router: Router,
    private _encService: EncService,
    private _functionsService: FunctionsService,
    private _providerService: ProviderService,
  ) {
    this.screenMode = 'subcontratists';
    this.isLoading = true;
    this.isLoadingForm = false;
    this.btnSmall = false;
    this.cardSmall = false;
    this.hasError = false;
    this.errorStr = "";

    this.txtBuscadorSubcontratists = '';
    this.displayedColumnsSubcontratists = [
      'NAME',
      'TIPO',
      'INTERVENTIONS_COUNT',
      'UPDATE_DATE',
      'UPDATED_BY_USER',
      'STATUS',
      'ACCIONES'
    ];
    this.dataSourceSubcontratists = new MatTableDataSource<any>();
  }
  
  ngAfterViewInit() {
    this.dataSourceSubcontratists.paginator = this.paginator;
    this.dataSourceSubcontratists.sort = this.sort;
  }
  
  async ngOnInit() {
    await this.getSubcontratists();
  }

  public async getSubcontratists() {
    this.isLoading = true;
    
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._subcontratistService.getConsultOfSubcontratists(USER, LINE)).then(
      (responseData: SubcontratistsResponse) => {
        this.hasError = responseData.error;
        if (!responseData.error) {

          let subcontratistsArr: SubcontratistItem[] = [];
          responseData.response.forEach(item => {
            let regFormatted = this._functionsService.orderDate(item.REGISTER_DATE);
            let modFormatted = null;

            if(item.UPDATE_DATE != null){
              modFormatted = this._functionsService.orderDate(item.UPDATE_DATE);
            }
            
            item.REGISTER_DATE = regFormatted!;
            item.UPDATE_DATE = modFormatted!;

            subcontratistsArr.push(item);
          }),

          this.dataSourceSubcontratists.data = subcontratistsArr;

        } else {
          this.errorStr = responseData.msg;
          this.resourcesService.openSnackBar(`${ responseData.msg }`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getSubcontratists();
        }
      }
    );

    this.isLoading = false;
  }

  public async openDialog(typeForm: string, element?: any) {
    if (typeForm === 'REG') {

      const typeFormSubcontract: TypeFormSubcontract = {
        type: 'REG',
        idSubcontract: null,
        idProvider: null,
      }

      const strFormSubcontract:string = JSON.stringify(typeFormSubcontract);
      const encFormSubcontract: string = await this._encService.encrypt(strFormSubcontract);

      this._router.navigate([`sam/GPRS/GESU/GESU/subcontratist/form/${encFormSubcontract}`]);

    } else if (typeForm === 'UPD') {

      const typeFormSubcontract: TypeFormSubcontract = {
        type: 'UPD',
        idSubcontract: element.ID_SUBCONTRATIST,
        idProvider: null,
      }

      const strFormSubcontract: string = JSON.stringify(typeFormSubcontract);
      const encFormSubcontract: string = await this._encService.encrypt(strFormSubcontract);

      this._router.navigate([`sam/GPRS/GESU/GESU/subcontratist/form/${encFormSubcontract}`]);

    } else if (typeForm === 'DET') {
      this._dialog.open(SubcontratistDetailsDialogComponent, {
        width: '520px',
        maxWidth: '520px',
        data: {
          idSub: element.ID_SUBCONTRATIST,
        }
      });
    } else if (typeForm === 'DEL') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Eliminación de Subcontratista',
          description: '¿Está seguro que desea eliminar al subcontratista?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.deleteSubcontratist(element!.ID_SUBCONTRATIST);
        }
      });
    } else if (typeForm === 'ACT') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Activación de Subcontratista',
          description: '¿Está seguro que desea activar al subcontratista?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.activateSubcontratist(element!.ID_SUBCONTRATIST);
        }
      });
    }
  }

  private async deleteSubcontratist(subcontratistId: string) {
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_subcontratist', subcontratistId);

      await lastValueFrom(this._subcontratistService.updateToInactiveStatus(formData));
      this.resourcesService.openSnackBar('Eliminación exitosa.');
      this.getSubcontratists();
    }catch(error: any){
      if(error.error == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  private async activateSubcontratist(subcontratistId: string) {
    await lastValueFrom(this._subcontratistService.updateToActiveStatus({
      ID_SUBCONTRATIST: subcontratistId,
      LINE_NUMBER: '01',
      SAVED_BY_USER: this.resourcesService.getUser()
    })).then(
      (responseData: any) => {
        if (!responseData.error) {
          this.getSubcontratists();
          this.resourcesService.openSnackBar('¡Activación Exitosa!');
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.activateSubcontratist(subcontratistId);
        }
      }
    );
  }
}
