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_empresa",
    "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;
  test: string;
  userList: any;
  reviewProposal: { id_inversion: number; step: string; comentario: 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.toLowerCase() +
        data.id_estado_inversion.nombre.toLowerCase() +
        data.codigo_inversion.toLowerCase() +
        data.nombre_inversion.toLowerCase() +
        data.asunto.toLowerCase() +
        data.id_empresa.nombre.toLowerCase() +
        data.comentario.toLowerCase() +
        data.justificacion.toLowerCase();
      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;
        /*
        if (this.userType(this.userRole, "analistas")) {
          this.listProposals;
        } else if (this.userType(this.userRole, "contabilidad")) {
          this.listProposals = this.listProposals.filter(proposals =>
            ["COMPR", "LIQUI"].includes(
              proposals["id_estado_inversion"]["codigo"]
            )
          );
        } else if (this.userType(this.userRole, "autorizadores")) {
          this.listProposals = this.listProposals.filter(proposals =>
            ["REVIS", "APROB", "FINAL"].includes(
              proposals["id_estado_inversion"]["codigo"]
            )
          );
        } else if (this.userType(this.userRole, "supervisores")) {
          this.listProposals = this.listProposals.filter(proposals =>
            ["PENDI", "REVIS", "FINAL"].includes(
              proposals["id_estado_inversion"]["codigo"]
            )
          );
        }*/

        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();
    }, 2000);
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value.toLowerCase();
    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);
  }

  can_modify(status: string) {
    if (
      status == "NUEVA" ||
      status == "RECHA" ||
      status == "APROB" ||
      status == "LIQUI"
    ) {
      return true;
    } else {
      return false;
    }
  }

  // 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" || status == "RECHA") {
      return true;
    } else {
      return false;
    }
  }

  can_review(status: string) {
    if (status == "PENDI" || status == "NOAPR") {
      return true;
    } else {
      return false;
    }
  }

  can_approve(status: string) {
    if (status == "REVIS") {
      return true;
    } else {
      return false;
    }
  }

  can_write_payment_info(status: string) {
    if (status == "APROB") {
      return true;
    } else {
      return false;
    }
  }

  can_review_payment(status: string) {
    if (status == "COMPR") {
      return true;
    } else {
      return false;
    }
  }

  can_upload_payment(status: string) {
    if (status == "PGAPR") {
      return true;
    } else {
      return false;
    }
  }
  can_finish_proposal(status: string) {
    if (status == "LIQUI") {
      return true;
    } else {
      return false;
    }
  }

  sendToReview(investmentProposalID: number, investmentCode: string) {
    this.investmentsService
      .getAvailableUsers(investmentProposalID)
      .subscribe(res => {
        this.userList = res["usuarios_next"];
        this.test = "<div>Notificar a:</div>";

        if (this.userList.length > 0) {
          for (let i = 0; i < this.userList.length; i++) {
            this.test += `<div class='form-check form-check-inline'><input type='checkbox' class='form-check-input' id='${this.userList[i]}' name='users' value='${this.userList[i]}'><label class='form-check-label' for='${this.userList[i]}'>${this.userList[i]}</label></div>`;
          }
        }
      });
    this.reviewProposal = undefined;
    (async () => {
      Swal.fire({
        title: `<h3>Enviar a revisión propuesta de inversión ${investmentCode}</h3>`,
        icon: "info",
        html: `<p style="text-align:left;">Comentario:</p>`,
        input: "textarea",
        showCancelButton: true,
        confirmButtonText: "Enviar propuesta",
        cancelButtonText: "Cancelar",
        showLoaderOnConfirm: true,
        inputValidator: value => {
          if (!value) {
            return "Debe ingresar un comentario";
          }
        },

        preConfirm: comentario => {
          this.reviewProposal = {
            id_inversion: investmentProposalID,
            step: "next",
            comentario: comentario
          };
        },
        allowOutsideClick: () => !Swal.isLoading()
      }).then(result => {
        Swal.fire({
          title: `<h3>Enviar a revisión propuesta de inversión ${investmentCode}</h3>`,
          icon: "info",
          html: `${this.test}`,
          confirmButtonText: "Siguiente",
          showCancelButton: true,
          cancelButtonText: "Cancelar",
          showLoaderOnConfirm: true,

          preConfirm: () => {
            let array = [];

            for (let i = 0; i < this.userList.length; i++) {
              let html_input: HTMLInputElement = document.getElementById(
                this.userList[i]
              ) as HTMLInputElement;
              let html_value: string = html_input.value;
              if (html_input.checked == true) {
                array.push(html_value);
              }
            }

            this.reviewProposal["notificar"] = array.toString();

            this.investmentsService
              .sendReviewProposalInvestment(this.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
                  });
                }
              );
          }
        });
        //window.location.reload();
      });
    })();
  }

  //Enviar a revision la propuesta de inversion
  finishProposal(investmentProposalID: number, investmentCode: string) {
    this.investmentsService
      .getAvailableUsers(investmentProposalID)
      .subscribe(res => {
        this.userList = res["usuarios_next"];
        this.test = "";

        if (this.userList.length > 0) {
          for (let i = 0; i < this.userList.length; i++) {
            this.test += `<div class='form-check form-check-inline'><input type='checkbox' class='form-check-input' id='${this.userList[i]}' name='users' value='${this.userList[i]}'><label class='form-check-label' for='${this.userList[i]}'>${this.userList[i]}</label></div>`;
          }
        }
      });
    this.reviewProposal = undefined;
    (async () => {
      Swal.fire({
        title: `<h3>Finalizar propuesta de inversión: ${investmentCode}</h3>`,
        icon: "info",
        input: "textarea",
        html: `<p style="text-align:left;">Comentario:</p>`,
        showCancelButton: true,
        confirmButtonText: "Siguiente",
        cancelButtonText: "Cancelar",
        preConfirm: comentario => {
          this.reviewProposal = {
            id_inversion: investmentProposalID,
            step: "next",
            comentario: comentario
          };
        },
        allowOutsideClick: () => !Swal.isLoading()
      }).then(result => {
        Swal.fire({
          title: `<h3>Finalizar propuesta de inversión ${investmentCode}</h3>`,
          icon: "info",
          html: `${this.test}`,
          confirmButtonText: "Finalizar",
          showCancelButton: true,
          cancelButtonText: "Cancelar",
          showLoaderOnConfirm: true,

          preConfirm: () => {
            let array = [];

            for (let i = 0; i < this.userList.length; i++) {
              let html_input: HTMLInputElement = document.getElementById(
                this.userList[i]
              ) as HTMLInputElement;
              let html_value: string = html_input.value;
              if (html_input.checked == true) {
                array.push(html_value);
              }
            }

            this.reviewProposal["notificar"] = array.toString();

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

  userType(userRole: any, requiredRole: any) {
    if (userRole.length == 0) {
      return true;
    }

    return userRole.includes(requiredRole);
  }
}
