import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { DeleteProvider, InformationsData, ProviderData, ResponseDataProvider, TypeForm } from '../../../../interfaces/acquisition-management/provider.interface';
import { GetPaymentMethod } from '../../../../interfaces/payment-method.interface';
import { MatDialog } from '@angular/material/dialog';
import { ResourcesService } from '../../../../services/resources.service';
import { ProviderService } from '../../../../services/acquisition-management/provider.service';
import { SocketService } from '../../../../services/socket.service';
import { EncService } from '../../../../services/enc.service';
import { Router } from '@angular/router';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { UserConsultResponse } from '../../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../../interfaces/profile.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { InformationProviderComponent } from './information-provider/information-provider.component';
import { ReferencesProviderComponent } from './references-provider/references-provider.component';
import { ReferencesFormComponent } from './references-provider/references-form/references-form.component';
import { ContactProviderComponent } from './contact-provider/contact-provider.component';
import { ContactProviderFormComponent } from './contact-provider/contact-provider-form/contact-provider-form.component';
import { ConditionProviderComponent } from './condition-provider/condition-provider.component';
import { ConditionProviderFormComponent } from './condition-provider/condition-provider-form/condition-provider-form.component';
import { PaymentMethodsProviderComponent } from './payment-methods-provider/payment-methods-provider.component';
import { CatalogsProviderComponent } from './catalogs-provider/catalogs-provider.component';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { ResponseData } from '../../../../interfaces/response-data';
import { GenerateSheetComponent } from '../../../resources/dialogs/generate-sheet/generate-sheet.component';
import { FunctionsService } from '../../../../services/functions.service';

const ID_MODULE = "S002V01M05GEAD";
@Component({
    selector: 'app-providers',
    templateUrl: './providers.component.html',
    styleUrl: './providers.component.css',
    standalone: false
})
export class ProvidersComponent implements AfterViewInit, OnInit {
  public isLoading: boolean = false;
  public isLoadingForm: boolean = false;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public displayedColumns: Array<string>;
  public dataSource:MatTableDataSource<InformationsData>;
  public arrPaymentMethod: Array<GetPaymentMethod>;

  public idFunction: string;

  public getReferencesEnabled: boolean;
  public websiteLinkEnabled: boolean;
  public contactEnabled: boolean;
  public conditionPaymentEnabled: boolean;
  public conditionPurchaseEnabled: boolean;
  public webCatalogEnabled: boolean;

  constructor(
    public resourcesService: ResourcesService,
    private _providerService: ProviderService,
    private _socketService: SocketService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _router: Router,
    private _usersProfilesSevice: UsersProfilesService, 
    private _functionsService: FunctionsService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.arrPaymentMethod = [];
    this.displayedColumns = ['NUMERO_PROVEEDOR', 'RAZON_SOCIAL', 'NOMBRE', 'RFC', 'CORREO', 'TELEFONO1', 'FECHA_MODIFICA', 'ESTADO', 'ACTION'];
    this.dataSource = new MatTableDataSource<InformationsData>();

    this.getReferencesEnabled = false;
    this.websiteLinkEnabled = false;
    this.contactEnabled = false;
    this.conditionPaymentEnabled = false;
    this.conditionPurchaseEnabled = false;
    this.webCatalogEnabled = false;

    this.idFunction = '';
  }

  async ngOnInit() {
    await this.refreshPermissions();
    await this.setPermissions();
    await this.getAllProvider();
  }

  ngAfterViewInit(): void {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  private async refreshPermissions() {
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      let idUser = localStorage.getItem('idusuario')!;
      let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesSevice.getUser(idUser, idUser, 1));
      let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

      if(currentProfile != usrInfo.response.PERFIL){
        this._router.navigate(['/sam/home']);
      }

      let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
      if(profileUpdated == currentProfile){
        let profile = localStorage.getItem('perfil')!;
        
        await lastValueFrom(this._usersProfilesSevice.getProfile( profile, idUser, 1 )).then(
          (responseData: ProfileInterface) => {
            if (!responseData.error) {
              let modPerm = responseData.response.PERMISOS.permissions.filter(item => item.id == 'S002V01M05GEAD')[0];
              let funPerm = modPerm.children.filter(item => item.id == 'S002V02S02PROV')[0];
              
              if (this.idFunction === 'CRPR') {
                let panPerm = funPerm.children.filter(item => item.id == "S002V01F02CRPR")[0];
                this.getReferencesEnabled = panPerm.children.filter(item => item.id == 'S002V01P01REPR')[0].access > 0;
              }
              if (this.idFunction === 'ESWP') {
                let panPerm = funPerm.children.filter(item => item.id == "S002V01F03ESWP")[0];
                this.websiteLinkEnabled = panPerm.children.filter(item => item.id == 'S002V01P01REPR')[0].access > 0;
                this.websiteLinkEnabled = panPerm.access > 0;;
              }
              if (this.idFunction === 'COPR') {
                let panPerm = funPerm.children.filter(item => item.id == "S002V01F04COPR")[0];
                this.contactEnabled = panPerm.access > 0;;
              }
              if (this.idFunction === 'DCMP') {
                let panPerm = funPerm.children.filter(item => item.id == "S002V01F06DCMP" )[0];
                this.conditionPaymentEnabled = panPerm.access > 0;
              }
              if (this.idFunction === 'DCCE') {
                let panPerm = funPerm.children.filter(item => item.id == "S002V01F07DCCE")[0];
                this.conditionPurchaseEnabled = panPerm.access > 0;
              }
              if (this.idFunction === 'CCPR') {
                let panPerm = funPerm.children.filter(item => item.id == "S002V01F08CCPR")[0];
                this.webCatalogEnabled = panPerm.access > 0;;
              }


              if (funPerm.access === 0) {
                this._router.navigate(['/sam/home']);
              }

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

    this._socketService.refreshModules().subscribe(async () => this._functionsService.consultModuleStatus(ID_MODULE));
  }

  private async setPermissions() {
    const navigate:string = this._router.routerState.snapshot.url;
    let arrNavigate: Array<string> = navigate.split(`/`);
    if (arrNavigate.length !== 5) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener el URL.`);
      this._router.navigate(['/sam/home']);
      return;
    }
    let functionTemp = arrNavigate.pop()!;
    if (functionTemp === undefined) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener la función del módulo.`)
      this._router.navigate(['/sam/home']);
      return ;
    }
    this.idFunction = functionTemp;
    
    if (this.idFunction === 'CRPR') {
      this.getReferencesEnabled = true;
    }
    if (this.idFunction === 'ESWP') {
      this.websiteLinkEnabled = true;
    }
    if (this.idFunction === 'COPR') {
      this.contactEnabled = true;
    }
    if (this.idFunction === 'DCMP') {
      this.conditionPurchaseEnabled = true;
    }
    if (this.idFunction === 'DCCE') {
      this.conditionPaymentEnabled = true;
    }
    if (this.idFunction === 'CCPR') {
      this.webCatalogEnabled = true;
    }
  }

  public async getAllProvider(){
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._providerService.getAllProvider(user, line)).then(
      (responseData : ResponseDataProvider) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getAllProvider();
        }
      }
    );
    this.isLoading = false;
  }

  public async openDialog(action: string, elementData: any = null) {
    if (action === 'REGI' || action === 'EDIT') {
      this.isLoadingForm = true;
      let form:TypeForm = { type: action, element: elementData, subcontract: null }
      let strForm: string = JSON.stringify(form);
      let encForm: string = await this._encService.encrypt(strForm);
      
      this.isLoadingForm = false;

      this._router.navigate([`/sam/GEAD/PROV/${this.idFunction}/${encForm}`]);
    } else if (action === 'INFO') {
      this._dialog.open(InformationProviderComponent, {
        width: '1300px',
        maxWidth: '1300px',
        disableClose: true,
        data: elementData.NUMERO_PROVEEDOR,
      });
    } else if (action === 'REFE') {
      this._dialog.open(ReferencesProviderComponent, {
        width: '1200px',
        maxWidth: '1200px',
        disableClose: true,
        data: elementData,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this._dialog.open(ReferencesFormComponent, {
            width: '500px',
            maxWidth: '500px',
            disableClose: true,
            data: {
              typeDialog: 'ONLYREAD',
              dataElement: result,
              dataSource: [],
            },
          }).afterClosed().subscribe((result) => {
            this.openDialog(action, elementData);
          });
        }
      });
    } else if (action === 'CONT') {
      this._dialog.open(ContactProviderComponent, {
        width: '1200px',
        maxWidth: '1200px',
        disableClose: true,
        data: elementData,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this._dialog.open(ContactProviderFormComponent, {
            width: '1300px',
            maxWidth: '1300px',
            disableClose: true,
            data: {
              typeDialog: 'ONLYREAD',
              dataElement: result,
              dataSource: [],
            },
          }).afterClosed().subscribe((result) => {
            this.openDialog(action, elementData);
          });
        }
      });
    } else if (action === 'COND') {
      this._dialog.open(ConditionProviderComponent, {
        width: '500px',
        maxWidth: '500px',
        disableClose: true,
        data: elementData,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this._dialog.open(ConditionProviderFormComponent, {
            width: '800px',
            maxWidth: '800px',
            disableClose: true,
            data: {
              typeDialog: 'ONLYREAD',
              dataElement: result,
              dataSource: [],
            },
          }).afterClosed().subscribe((result) => {
            this.openDialog(action, elementData);
          });
        }
      });
    } else if (action === 'MEPA') {   
      this._dialog.open(PaymentMethodsProviderComponent, {
        width: '500px',
        maxWidth: '500px',
        disableClose: true,
        data: elementData,
      });
    } else if (action === 'CATA') {
      this._dialog.open(CatalogsProviderComponent, {
        width: '800px',
        maxWidth: '800px',
        disableClose: true,
        data: elementData,
      });
    }
  }

  public async alert(type: string, dataElement?: ProviderData):Promise<void> {
    if (type === 'ELIM') {
      this._dialog.open(AlertComponent, {
        data: {
          icon: "warning",
          title: "Eliminar Proveedor",
          description: "¿Está seguro de eliminar el proveedor?",
        },
        disableClose: true,
        width: '400px'
      }).afterClosed().subscribe((result) => {
        if(result) {
          this.deteleProvider(dataElement!.NUMERO_PROVEEDOR);
        } 
      });


    }else if (type === 'REDI') {
      this._dialog.open(AlertComponent, {
        data: {
          icon: "warning",
          title: "Redireccionamiento",
          description: "Estas a punto de salir del portal SAM hacía el sitio web del proveedor ¿Deseas continuar?",
        },
        disableClose: true,
        width: '400px'
      }).afterClosed().subscribe((result) => {
        if(result) {
          window.open(dataElement!.SITIOWEB, '_blank');
        } 
      });


    } else if (type === 'SHEET') {
      this._dialog.open(GenerateSheetComponent, {
        data:  {
          title: `Generar ficha proveedor`,
          description: `¿Está seguro de generar la ficha del proveedor ${dataElement!.NUMERO_PROVEEDOR}?`,
          icon: 'warning',
        },
        disableClose: true,
        width: '400px'
      }).afterClosed().subscribe((result) => {
        if (result === 'XLS' && dataElement !== undefined ) {
          this.generateSheetXLS( dataElement.NUMERO_PROVEEDOR );
        } else if (result === 'PDF' && dataElement !== undefined ) {
          this.generateSheetPDF( dataElement.NUMERO_PROVEEDOR );
        }
      });
    }
  }

  public async deteleProvider(numeroProveedor:string){
    let objRequest:DeleteProvider = {
      line: this.resourcesService.getLineNumber(),
      user: this.resourcesService.getUser(),
      numero_proveedor: await this._encService.encrypt(numeroProveedor)
    }
    await lastValueFrom(this._providerService.deteleProvider(objRequest)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡El proveedor fue eliminado exitosamente!`);
          this.getAllProvider();
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.deteleProvider(numeroProveedor);
        }
      }
    );
  }

  public async generateSheetXLS(providerNumber: string) {
    this.isLoadingForm = true;
    const encProvider:string = await this._encService.encrypt(providerNumber);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._providerService.generateSheetProviderXLS(encProvider, 'P', user, line)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open(`${ responseData.response.url }`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateSheetXLS(providerNumber);
        }
      }
    );
    this.isLoadingForm = false;
  }

  public async generateSheetPDF(providerNumber: string) {
    this.isLoadingForm = true;
    const encProvider:string = await this._encService.encrypt(providerNumber);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._providerService.generateSheetProviderPDF(encProvider, 'P', user, line)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {          
          window.open(`${ responseData.response.url }`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateSheetPDF(providerNumber);
        }
      }
    );
    this.isLoadingForm = false;
  }
}
