import { Component, OnInit } from "@angular/core";
import { FormInvestmentProposalService } from "@app/services/form-investment-proposal.service";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { CatalogsService } from "@app/services/catalogs.service";
import { IAngularMyDpOptions, IMyDateModel } from "angular-mydatepicker";
import { formatDate, DatePipe } from "@angular/common";
import { parse } from "date-fns";
import { Router, ActivatedRoute } from "@angular/router";
import { InvestmentsService } from "@app/services/investments.service";
import Swal from "sweetalert2";

@Component({
  selector: "app-payment-info",
  templateUrl: "./payment-info.component.html"
})
export class PaymentInfoComponent implements OnInit {
  title: string = "Formulario de información para el pago";

  form: any;

  // For daterange
  daysLabels: any = {
    su: "Dom",
    mo: "Lun",
    tu: "Mar",
    we: "Mie",
    th: "Jue",
    fr: "Vie",
    sa: "Sab"
  };
  monthsLabels: any = {
    1: "Ene",
    2: "Feb",
    3: "Mar",
    4: "Abr",
    5: "May",
    6: "Jun",
    7: "Jul",
    8: "Ago",
    9: "Sep",
    10: "Oct",
    11: "Nov",
    12: "Dic"
  };
  myDpOptions: IAngularMyDpOptions = {
    dateRange: false,
    dateFormat: "dd/mm/yyyy",
    dayLabels: this.daysLabels,
    monthLabels: this.monthsLabels
  };
  myDateInit: boolean = true;

  investmentProposalForm: FormGroup;
  submitted: boolean = false;
  role_number: any;
  markets: any;
  emitters: any;
  periodicities: any;
  rate_agencies: any;
  scores: any;
  investmentProposalID: string;
  funds: any;
  companies: any;
  format_incomes: any;
  operations: any;
  payment_terms: any;
  payment_types: any;
  inversionCode: any;
  paymentProposal: any;
  banks: any;
  accounts: any;
  paymentObject: Object;
  inversionAmount: any;
  reviewProposal: any;
  generated_inputs_next: any;
  userListNext: any;
  investmentService: any;
  payment_check: boolean;
  payment_transfer: boolean;
  accounts_destination: any;
  accounts_origin: any;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private formBuilder: FormBuilder,
    private formDataService: FormInvestmentProposalService,
    private catalogService: CatalogsService,
    private investmentsService: InvestmentsService
  ) {}

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.investmentProposalID = params["id"];
    });
    if (this.investmentProposalID == undefined)
      this.investmentProposalID = this.route.snapshot.queryParamMap.get("id");

    this.investmentsService
      .getAvailableUsers(this.investmentProposalID)
      .subscribe(res => {
        this.userListNext = res["usuarios_next"];
        this.generated_inputs_next = "";
        if (this.userListNext.length > 0) {
          for (let i = 0; i < this.userListNext.length; i++) {
            if (this.userListNext[i].default_email == true) {
              this.generated_inputs_next += `<div class='form-check form-check-inline'><input type='checkbox' class='form-check-input' id='next-${
                this.userListNext[i].name
              }' name='users' value='${this.userListNext[i].name}' checked='${
                this.userListNext[i].default_email == "true" ? true : false
              }'><label class='form-check-label' for='next-${
                this.userListNext[i].name
              }'>${this.userListNext[i].name}</label></div>`;
            } else {
              this.generated_inputs_next += `<div class='form-check form-check-inline'><input type='checkbox' class='form-check-input' id='next-${this.userListNext[i].name}' name='users' value='${this.userListNext[i].name}'><label class='form-check-label' for='next-${this.userListNext[i].name}'>${this.userListNext[i].name}</label></div>`;
            }
          }
        }
      });

    this.investmentsService
      .getProposalInvestment(this.investmentProposalID)
      .subscribe(
        res => {
          this.inversionCode = res["result"]["codigo_inversion"];

          if (
            res["result"]["id_inversion_instrumento"]["instrumento"][
              "monto_inversion"
            ] != undefined
          ) {
            this.inversionAmount =
              res["result"]["id_inversion_instrumento"]["instrumento"][
                "monto_inversion"
              ];
          } else if (
            res["result"]["id_inversion_instrumento"]["instrumento"][
              "total_pagar"
            ] != undefined
          ) {
            this.inversionAmount =
              res["result"]["id_inversion_instrumento"]["instrumento"][
                "total_pagar"
              ];
          } else if (
            res["result"]["id_inversion_instrumento"]["instrumento"][
              "monto_pagar"
            ] != undefined
          ) {
            this.inversionAmount =
              res["result"]["id_inversion_instrumento"]["instrumento"][
                "monto_pagar"
              ];
          } else if (
            res["result"]["id_inversion_instrumento"]["instrumento"][
              "monto_prestamo"
            ] != undefined
          ) {
            this.inversionAmount =
              res["result"]["id_inversion_instrumento"]["instrumento"][
                "monto_prestamo"
              ];
          }
          this.investmentProposalForm.setValue({
            monto:
              Math.round((this.inversionAmount + Number.EPSILON) * 100) / 100,
            tipo_pago: "",
            cuenta_bancaria: "",
            fecha_vencimiento: "",
            cuenta_bancaria_destino: "",
            emitir_nombre: res["result"]["emitir_a_nombre_de"]
          });
        },
        err => {
          Swal.fire({
            icon: "error",
            title: "Error en el servidor",
            text: err.message
          });
        }
      );

    this.catalogService
      .getBankAccounts("origen", this.investmentProposalID)
      .subscribe(res => {
        this.accounts_origin = res["result"];
      });

    this.catalogService
      .getBankAccounts("destino", this.investmentProposalID)
      .subscribe(res => {
        this.accounts_destination = res["result"];
      });

    this.catalogService.getPaymentTypes().subscribe(res => {
      this.payment_types = res;
    });
    this.catalogService.getCountries().subscribe(res => {
      this.funds = res;
    });

    /*this.catalogService.getCatalogInfo("bancos").subscribe(res => {
      this.banks = res;
      this.catalogService.getCatalogInfo("cuentas-bancarias").subscribe(res => {
        this.accounts = res;
      });
      //this.payment_types = res;
    });*/

    /*this.catalogService
      .getCatalogInfo("cuentas-bancaria-destino")
      .subscribe(res => {
        this.accounts_destination = res;
      });
      */
    this.investmentProposalForm = this.formBuilder.group({
      monto: [
        this.inversionAmount,
        [
          Validators.required,
          //Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/)
          Validators.pattern("^[0-9,.]+$")
        ]
      ],
      tipo_pago: ["", Validators.required],
      cuenta_bancaria: ["", Validators.required],
      fecha_vencimiento: ["", Validators.required],
      cuenta_bancaria_destino: [""],
      emitir_nombre: [""]
    });
  }

  onChangePaymentType(event: any) {
    if (event == 2) {
      this.payment_check = true;
      this.payment_transfer = false;
    } else if (event == 3) {
      this.payment_transfer = true;
      this.payment_check = false;
    } else {
      this.payment_check = false;
      this.payment_transfer = false;
    }
  }

  get f() {
    return this.investmentProposalForm.controls;
  }

  clearValor(value, tipoDato) {
    value = parseFloat(value.toString().replace(",", ""));
    return value;
  }

  public inputValidator(event: any) {
    const pattern = /^[0-9]*$/;
    //let inputChar = String.fromCharCode(event.charCode)

    if (!pattern.test(event.target.value)) {
      event.target.value = event.target.value.replace(/[^\d,.]+/g, "");
      // invalid character, prevent input
    }
  }

  nameBankAccounts(id: string) {
    let bank;
    bank = this.banks.find(e => e.id_banco == id);
    return bank.nombre;
  }

  sendPaymentInfo(form: any) {
    this.submitted = true;
    this.inversionAmount = this.clearValor(this.inversionAmount, "decimal");
    if (!form.valid) {
      return false;
    }

    this.reviewProposal = undefined;
    (async () => {
      Swal.fire({
        title: `<h3>Enviar información de pago</h3>`,
        icon: "info",
        html: `<p style="text-align:left;">Comentario:</p>`,
        input: "textarea",
        showCancelButton: true,
        confirmButtonText: "Siguiente",
        cancelButtonText: "Cancelar",
        showLoaderOnConfirm: true,
        //inputValidator: value => {
        //  if (!value) {
        //   return "Debe ingresar un comentario";
        //}
        //},

        preConfirm: comentario => {
          this.reviewProposal = {
            id_inversion: this.investmentProposalID,
            step: "next",
            comentario: comentario
          };
        },
        allowOutsideClick: () => !Swal.isLoading()
      }).then(result => {
        if (result.dismiss) {
          Swal.close();
        }

        Swal.fire({
          title: `<h3>Enviar información de pago</h3>`,
          icon: "info",
          html: `<div>Notificar a:</div>${this.generated_inputs_next}`,
          confirmButtonText: "Enviar información",
          showCancelButton: true,
          cancelButtonText: "Cancelar",
          showLoaderOnConfirm: true,

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

            for (let i = 0; i < this.userListNext.length; i++) {
              let html_input: HTMLInputElement = document.getElementById(
                "next-" + this.userListNext[i].name
              ) as HTMLInputElement;
              let html_value: string = html_input.value;
              if (html_input.checked == true) {
                array.push(html_value);
              }
            }
            // http://localhost:8001/api/cuentas-bancarias?tipo=origen&id_inversion=51

            this.reviewProposal["notificar"] = array.toString();
            this.paymentObject = {
              monto: this.inversionAmount,
              id_tipo_pago: +this.investmentProposalForm.value.tipo_pago,
              id_cuenta_bancaria: +this.investmentProposalForm.value
                .cuenta_bancaria,

              //fecha_pago: this.investmentProposalForm.value.fecha_pago.singleDate.formatted,
              fecha_vencimiento: this.investmentProposalForm.value
                .fecha_vencimiento.singleDate.formatted,
              emitir_nombre: this.investmentProposalForm.value.emitir_nombre,
              id_inversion: +this.investmentProposalID
            };

            if (+this.investmentProposalForm.value.tipo_pago == 3) {
              this.paymentObject["id_cuenta_bancaria_destino"] = +this
                .investmentProposalForm.value.cuenta_bancaria_destino;
            } else {
              this.paymentObject["id_cuenta_bancaria_destino"] = null;
            }
          }
        }).then(result1 => {
          if (result1.dismiss) {
            return false;
          }

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

          this.investmentsService
            .sendPaymentInfoProposalInvestment(
              this.investmentProposalID,
              this.paymentObject
            )
            .subscribe(
              success => {
                this.investmentsService
                  .sendProposalInvestmentToNextStep(this.reviewProposal)
                  .subscribe(
                    success => {
                      if (success) {
                        Swal.fire({
                          allowOutsideClick: false,
                          icon: "success",
                          showCancelButton: false,
                          title: "Exito",
                          confirmButtonText:
                            "La requisicion de pago ha sido generada"
                        }).then(result => {
                          Swal.close();
                          window.location.href = "#/investment-proposals";
                        });
                      }
                    },
                    err => {
                      Swal.fire({
                        icon: "error",
                        title: "Error al guardar",
                        text: err.message
                      });
                    }
                  );
              },
              err => {
                Swal.fire({
                  icon: "error",
                  title: "Error al guardar",
                  text: err.message
                });
              }
            );
        });

        //window.location.reload();
      });
    })();
  }
}
