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: "./investments.component.html",
  styleUrls: ["./investments.component.scss"]
})
export class InvestmentsComponent implements OnInit {
  helper = new JwtHelperService();

  title: string = "Inversiones activas";

  displayedColumns: string[] = [
    "codigo_inversion",
    "asunto",
    "id_empresa",
    "id_inversion_instrumento",
    "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.userRole = decodedToken.groups;

    this.dataSource.filterPredicate = (data, filter) => {
      const dataStr =
        data.id_inversion_instrumento.id_tipo_instrumento.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("portafolio").subscribe(
      ans => {
        this.listProposals = ans.result;
        this.dataSource.data = this.listProposals;
        this.dataSource.paginator = this.paginator;
        this.dataSource.sortingDataAccessor = (item, property) => {
          switch (property) {
            case "id_inversion_instrumento":
              return item.id_inversion_instrumento.id_tipo_instrumento.nombre;
            case "id_estado_inversion":
              return item.id_estado_inversion.nombre;
            case "id_empresa":
              return item.id_empresa.nombre;
            default:
              return item[property];
          }
        };
        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);
  }

  instrument_has_costs(instrument: any) {
    switch (instrument.id_tipo_instrumento.codigo) {
      case "VCN":
      case "PBUR":
        if (instrument.id_inversion_instrumento.valor_par == true) {
          return true;
        } else {
          return false;
        }
        break;
      case "FINV":
      case "PEMP":
      case "PPER":
        return true;
      default:
        return false;
    }
  }

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

    setTimeout(() => {
      this.router.navigate([
        `/investment-${route}/${code.toLowerCase()}/${id}`
      ]);
    }, 1000);
  }
}
