import { Component, ViewChild, OnInit } from "@angular/core";
import { MatPaginator } from "@angular/material/paginator";
import { MatSort } from "@angular/material/sort";
import { MatTableDataSource } from "@angular/material/table";
import Swal from "sweetalert2";
import { CatalogsService } from "src/app/services/catalogs.service";
import { InvestmentsService } from "@app/services/investments.service";
import { AuthService } from "@app/services/auth2.service";
import { JwtHelperService } from "@auth0/angular-jwt";
import { InvestmentProposal } from "@app/models/investment-proposal";
import { from } from "rxjs";
import { FormInvestmentProposalService } from "@app/services/form-investment-proposal.service";
import { Router } from "@angular/router";

@Component({
  selector: "app-investment-proposals",
  templateUrl: "./investment-proposals.component.html",
  styleUrls: ["./investment-proposals.component.scss"]
})
export class InvestmentProposalsComponent implements OnInit {
  helper = new JwtHelperService();

  title: string = "Propuestas de inversión";

  displayedColumns: string[] = [
    "codigo_inversion",
    "asunto",
    "id_tipo_mercado",
    "id_inversion_instrumento",
    "id_estado_inversion",
    "id"
  ];
  //displayedColumns: string[] = ['state'];

  listProposals: InvestmentProposal[];
  dataSource = new MatTableDataSource(this.listProposals);

  resultsLength = 0;
  isLoadingResults = true;
  isRateLimitReached = false;
  userRole: any;

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: true }) sort: MatSort;
  role_number: any;

  constructor(
    private catalogService: CatalogsService,
    private investmentsService: InvestmentsService,
    private authService: AuthService,
    private formInvestmentProposal: FormInvestmentProposalService,
    private router: Router
  ) {
    const decodedToken = this.helper.decodeToken(
      this.authService.getJwtToken()
    );
    this.catalogService.getGenericURL("empresas").subscribe(ans => {
      console.log(ans);
      console.log("--empresas");
    });
    console.log(decodedToken);
    this.userRole = decodedToken.groups;
    //    console.log("User role");
    //  console.log(this.userRole);
    //console.log(this.userRole.length == 0);

    this.dataSource.filterPredicate = (data, filter) => {
      const dataStr =
        data.id_inversion_instrumento.id_tipo_instrumento.nombre +
        data.id_estado_inversion.nombre +
        data.codigo_inversion +
        data.nombre_inversion +
        data.asunto +
        data.comentario +
        data.justificacion;
      return dataStr.indexOf(filter) != -1;
    };

    Swal.fire({
      allowOutsideClick: false,
      icon: "info",
      text: "Espere por favor..."
    });
    Swal.showLoading();
  }

  ngOnInit() {
    this.investmentsService.getProposalInvestmentsList().subscribe(
      ans => {
        this.listProposals = ans.result;
        console.log(this.listProposals);
        this.dataSource.data = this.listProposals;

        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      },
      err => {
        Swal.fire({
          icon: "error",
          title: "Error en el servidor",
          text: err.message
        });
      }
    );

    setTimeout(() => {
      Swal.close();
    }, 1200);
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue;

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  view_investment_proposal(id: string) {
    this.formInvestmentProposal.resetFormData();
    Swal.fire({
      allowOutsideClick: false,
      icon: "info",
      text: "Espere por favor..."
    });
    Swal.showLoading();
    setTimeout(() => {
      this.router.navigate([`/investment-proposal/${id}`]);
    }, 1000);
  }

  modify_investment_proposal(id: string) {
    this.formInvestmentProposal.resetFormData();

    Swal.fire({
      allowOutsideClick: false,
      icon: "info",
      text: "Espere por favor..."
    });
    Swal.showLoading();
    setTimeout(() => {
      this.router.navigate(["/investment-proposal/general-info"], {
        queryParams: { id: id }
      });
    }, 1000);
  }

  create_investment_proposal() {
    this.formInvestmentProposal.resetFormData();

    Swal.fire({
      allowOutsideClick: false,
      icon: "info",
      text: "Espere por favor..."
    });
    Swal.showLoading();
    setTimeout(() => {
      this.router.navigate(["/investment-proposal/general-info"], {});
    }, 1000);
  }

  // Verifica permisos para mostrar boton de edicion y/o envio a revision,
  // segun los permisos del usuario y el estado de la propuesta
  can_modify_or_send_to_review(status: string) {
    if (status == "NUEVA" && (this.userRole.length == 0 || this.userRole)) {
      // TO DO ver que el codigo de los tipos de usuario
      return true;
    } else {
      return false;
    }
  }

  can_review(status: string) {
    if (status == "PENDI" && (this.userRole.length == 0 || this.userRole)) {
      // TO DO ver que el codigo de los tipos de usuario
      return true;
    } else {
      return false;
    }
  }

  can_write_payment_info(status: string) {
    if (status == "REVIS" && (this.userRole.length == 0 || this.userRole)) {
      // TO DO ver que el codigo de los tipos de usuario
      return true;
    } else {
      return false;
    }
  }

  sendToReview(investmentProposalID: number, investmentCode: string) {
    (async () => {
      const { value: comentario } = await Swal.fire({
        title: `<h3>Enviar a revisión propuesta de inversión ${investmentCode}</h3>`,
        icon: "info",
        input: "textarea",
        showCancelButton: true,
        confirmButtonText: "Enviar propuesta",
        cancelButtonText: "Cancelar",
        inputValidator: value => {
          if (!value) {
            return "Debe ingresar un comentario";
          }
        }
      });

      if (comentario) {
        let reviewProposal = {
          id_inversion: investmentProposalID,
          step: "next",
          comentario: comentario
        };

        this.investmentsService
          .sendReviewProposalInvestment(reviewProposal)
          .subscribe(
            success => {
              if (success) {
                Swal.fire({
                  allowOutsideClick: false,
                  icon: "success",
                  showCancelButton: false,
                  title: "Exito",
                  confirmButtonText: "La propuesta ha sido enviada a revisión"
                }).then(result => {
                  Swal.close();
                  window.location.reload();
                });
              }
            },
            err => {
              Swal.fire({
                icon: "error",
                title: "Error al guardar",
                text: err.message
              });
            }
          );
      }
    })();
  }

  userType(userRole: any) {
    switch (+userRole) {
      case 0:
        return "Invitado";
      case 1:
        return "Usuario";
      case 2:
        return "Administrador";
      case 3:
        return "Super Admin";
    }
  }
}
