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

@Component({
  selector: 'app-providers',
  templateUrl: './providers.component.html',
  styleUrls: ['./providers.component.css']
})
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 dialog: MatDialog,
    public resourcesService: ResourcesService,
    private _providerService: ProviderService,
    private _socketService: SocketService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _router: Router,
    private _usersProfilesSevice: UsersProfilesService, 
  ) {
    this.arrPaymentMethod = [];
    this.displayedColumns = ['NUMERO_PROVEEDOR', 'RAZON_SOCIAL', 'USUARIO_PROVEEDOR', 'RFC', 'CORREO', '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(parseInt(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 panPerm1 = funPerm.children.filter(item => item.id == "S002V01F06DCMP" )[0];
                let panPerm2 = funPerm.children.filter(item => item.id == "S002V01F07DCCE")[0];
                this.conditionPaymentEnabled = panPerm1.access > 0 || panPerm2.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}`);
            }
          }, ( httpErrorResponse: HttpErrorResponse ) => this.resourcesService.checkErrors(httpErrorResponse)
        );
      }
    });
  }

  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.conditionPaymentEnabled = true;
    }
    if (this.idFunction === 'DCCE') {
      this.conditionPurchaseEnabled = true;
    }
    if (this.idFunction === 'CCPR') {
      this.webCatalogEnabled = true;
    }
  }

  public async getAllProvider(){
    this.isLoading = true;
    await lastValueFrom(this._providerService.getAllProvider()).then(
      (responseData : ResponseDataProvider) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    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 }
      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',
        disableClose: true,
        data: elementData.NUMERO_PROVEEDOR,
      });
    } else if(action === 'REFE') {
      this.dialog.open(ReferencesProviderComponent, {
        width: '1200px',
        disableClose: true,
        data: elementData,
      }).afterClosed().subscribe((result) => {
        if (result) {          
          this.dialog.open(ReferencesFormComponent, {
            width: '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',
        disableClose: true,
        data: elementData,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.dialog.open(ContactProviderFormComponent, {
            width: '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',
        disableClose: true,
        data: elementData,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.dialog.open(ConditionProviderFormComponent, {
            width: '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',
        disableClose: true,
        data: elementData,
      });
    } else if (action === 'CATA') {
      this.dialog.open(CatalogsProviderComponent, {
        width: '800px',
        disableClose: true,
        data: elementData,
      });
    } else if (action === 'ARTI') {
      let dataElement: ProviderData = elementData;
      let encProviderNumber: string = await this._encService.encrypt(dataElement.NUMERO_PROVEEDOR);
      this._router.navigate([`/sam/artitles-by-provider/${encProviderNumber}`]);
    }
  }

  public async deteleProvider(numeroProveedor:string){
    let objRequest:DeleteProvider = {
      line: '1',
      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}`);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  public setName(objProvider: ProviderData) {
    let name:string = `${objProvider.NOMBRE} ${objProvider.PRIMER_APELLIDO} ${objProvider.SEGUNDO_APELLIDO}`;
    return this.resourcesService.resizeText(name, 27);
  }

  public async alert(type: string, dataElement?: ProviderData):Promise<void> {
    let dataDialog: AlertData = {} as AlertData;
    if (type === 'ELIM') {
      dataDialog = {
        icon: "warning",
        title: "Eliminar Proveedor",
        description: "¿Está seguro de eliminar el proveedor?",
      };
    }else if (type === 'REDI') {
      dataDialog = {
        icon: "warning",
        title: "Redireccionamiento",
        description: "Estas a punto de salir del portal SAM hacía el sitio web del proveedor ¿Deseas continuar?",
      };
    } else if (type === 'SHEET') {
      dataDialog = {
        title: `Generar Ficha Proveedor`,
        description: `¿Está seguro de generar la ficha del proveedor ${dataElement!.NUMERO_PROVEEDOR}?`,
        icon: 'warning',
      };
    }

    this._dialog.open(AlertComponent, {
      data: dataDialog,
      disableClose: true,
      width: '400px'
    }).afterClosed().subscribe((result) => {
      if (type === 'ELIM' && result) {
        this.deteleProvider(dataElement!.NUMERO_PROVEEDOR);
      } else if(type === 'REDI' && result) {
        window.open(dataElement!.SITIOWEB, '_blank');
      } else if (type === 'SHEET' && result){
        this.generateSheet(dataElement!.NUMERO_PROVEEDOR)
      }
    });
  }

  public async generateSheet(providerNumber: string) {
    this.isLoadingForm = true;
    const encProvider:string = await this._encService.encrypt(providerNumber);
    await lastValueFrom(this._providerService.generateSheetProvider(encProvider)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          // window.open(`${apiUriJeanDownload}/GEAD/${responseData.response}`);
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }
}


