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;

  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
      .getProposalInvestment(this.investmentProposalID)
      .subscribe(
        res => {
          this.inversionCode = res["result"]["codigo_inversion"];

          if (
            res["result"]["id_inversion_instrumento"]["id_tipo_instrumento"][
              "codigo"
            ] == "DAP"
          ) {
            this.inversionAmount =
              res["result"]["id_inversion_instrumento"]["instrumento"][
                "monto_inversion"
              ];
          } else {
            this.inversionAmount =
              res["result"]["id_inversion_instrumento"]["instrumento"][
                "total_pagar"
              ];
          }
          this.investmentProposalForm.setValue({
            monto: this.inversionAmount,
            tipo_pago: "",
            cuenta_bancaria: "",
            fecha_vencimiento: ""
          });
        },
        err => {
          Swal.fire({
            icon: "error",
            title: "Error en el servidor",
            text: err.message
          });
        }
      );

    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.investmentProposalForm = this.formBuilder.group({
      monto: [
        this.inversionAmount,
        [
          Validators.required,
          Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/)
        ]
      ],
      tipo_pago: ["", Validators.required],
      cuenta_bancaria: ["", Validators.required],
      fecha_vencimiento: ["", Validators.required]
    });
  }

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

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

  sendPaymentInfo(form: any) {
    this.submitted = true;
    console.log(form);
    if (!form.valid) {
      return false;
    }

    this.paymentProposal = {
      id_inversion: this.investmentProposalID,
      step: "next",
      comentario: "Informacion de pago"
    };

    this.paymentObject = {
      monto: this.investmentProposalForm.value.monto,
      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,
      id_inversion: this.investmentProposalID
    };

    this.investmentsService
      .sendPaymentInfoProposalInvestment(
        this.investmentProposalID,
        this.paymentObject
      )
      .subscribe(
        success => {
          this.investmentsService
            .sendProposalInvestmentToNextStep(this.paymentProposal)
            .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
          });
        }
      );
  }
}
