import { Component, OnInit, Input, ViewChild } from "@angular/core";
import { InstrumentComponent } from "@app/components/investment-proposals/instrument/instrument.component";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { IAngularMyDpOptions, IMyDateModel } from "angular-mydatepicker";
import { formatDate, DatePipe } from "@angular/common";
import { Router } from "@angular/router";
import { FormInvestmentProposalService } from "@app/services/form-investment-proposal.service";
import { CatalogsService } from "@app/services/catalogs.service";
import { InstrumentCalculations } from "@app/services/instrument-calculations.service";
import Swal from "sweetalert2";
import { GeneralInfo } from "@app/models/investment-proposal-form";
import { parse } from "date-fns";
import { MatPaginator } from "@angular/material/paginator";
import { MatSort } from "@angular/material/sort";
import { MatTableDataSource } from "@angular/material/table";

@Component({
  selector: "app-cete",
  templateUrl: "./cete.component.html"
})
export class CETE implements InstrumentComponent {
  title: string = "Cetes";
  @Input() data: any;
  @Input() summary: boolean;
  @Input() investmentID: string;

  displayedColumns: string[] = [
    "posicion",
    "plazo",
    "fecha_pago",
    "ingreso_bruto",
    "ingreso_neto"
  ];

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

  form: any;
  general: GeneralInfo;

  // 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"
  };
  investmentProposalForm: FormGroup;
  myDpOptions: IAngularMyDpOptions = {
    dateRange: false,
    dateFormat: "dd/mm/yyyy",
    dayLabels: this.daysLabels,
    monthLabels: this.monthsLabels
  };
  myDateInit: boolean = true;
  m_fecha_operacion: IMyDateModel;
  m_fecha_liquidacion: IMyDateModel;
  m_fecha_rendencion: IMyDateModel;

  submitted: boolean = false;
  instrument_exists: boolean;
  instrument_work: any = [];
  financials: any;
  base_types: any;

  ingreso_bruto: number = 0.0;
  ingreso_neto: number = 0.0;
  valor_transado: number = 0.0;
  precio_porcentaje: number = 0.0;
  rendimiento_neto: number = 0.0;
  total_pagar: number = 0.0;
  comision_bolsa: number = 0.0;
  comision_casa: number = 0.0;
  proyecciones: any;

  ceteObject: {};
  dataSource = new MatTableDataSource(this.proyecciones);
  dataSource2 = new MatTableDataSource(this.proyecciones);
  hasProjections: boolean;
  fecha_vencimiento: any;

  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private formDataService: FormInvestmentProposalService,
    private catalogService: CatalogsService,
    private instrumentCalcService: InstrumentCalculations,
    public datepipe: DatePipe
  ) {
    this.instrument_work = this.formDataService.getWork();
    this.instrument_exists = this.instrument_work == undefined;
    this.general = this.formDataService.getGeneralInfo();

    if (
      this.instrument_work != undefined &&
      (this.instrument_work.proyecciones != "" ||
        this.instrument_work != undefined)
    ) {
      this.hasProjections = true;
      this.dataSource2.data = this.instrument_work.proyecciones;
      this.dataSource2.paginator = this.paginator;
      this.dataSource2.sort = this.sort;
    } else {
      this.hasProjections = false;
    }

    this.investmentProposalForm = this.formBuilder.group({
      valor_nominal: [
        this.instrument_exists ? "" : this.instrument_work.valor_nominal,
        [
          Validators.required,
          Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/)
        ]
      ],

      plazo: [
        this.instrument_exists ? "" : this.instrument_work.plazo,
        [Validators.required, Validators.pattern(/^[+]?([0-9]+)$/)]
      ],
      comision_casa_porcentaje: [
        this.instrument_exists
          ? ""
          : this.instrument_work.comision_casa_porcentaje,
        [
          Validators.required,
          Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/)
        ]
      ],
      comision_bolsa_porcentaje: [
        this.instrument_exists
          ? ""
          : this.instrument_work.comision_bolsa_porcentaje,
        [
          Validators.required,
          Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/)
        ]
      ],
      rendimiento_bruto: [
        this.instrument_exists ? "" : this.instrument_work.rendimiento_bruto,
        [
          Validators.required,
          Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/)
        ]
      ],
      otros_costos: [
        this.instrument_exists ? 0 : this.instrument_work.rendimiento_bruto,
        [Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/)]
      ],
      fecha_liquidacion: [
        this.instrument_exists
          ? ""
          : {
              isRange: false,
              singleDate: {
                jsDate: parse(
                  this.instrument_work.fecha_liquidacion,
                  "dd/MM/yyyy",
                  new Date()
                ),
                formatted: this.instrument_work.fecha_liquidacion
              }
            },
        Validators.required
      ] /*
      fecha_vencimiento: [
        this.instrument_exists
          ? ""
          : {
              isRange: false,
              singleDate: {
                jsDate: parse(
                  this.instrument_work.fecha_vencimiento,
                  "dd/MM/yyyy",
                  new Date()
                ),
                formatted: this.instrument_work.fecha_vencimiento
              }
            },
        Validators.required
      ],*/,
      fecha_operacion: [
        this.instrument_exists
          ? ""
          : {
              isRange: false,
              singleDate: {
                jsDate: parse(
                  this.instrument_work.fecha_operacion,
                  "dd/MM/yyyy",
                  new Date()
                ),
                formatted: this.instrument_work.fecha_operacion
              }
            },
        Validators.required
      ],
      fecha_ultima_cupon: [
        this.instrument_exists
          ? ""
          : {
              isRange: false,
              singleDate: {
                jsDate: parse(
                  this.instrument_work.fecha_ultima_cupon,
                  "dd/MM/yyyy",
                  new Date()
                ),
                formatted: this.instrument_work.fecha_ultima_cupon
              }
            }
      ]
    });
  }

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

  save(form: any): boolean {
    if (!form.valid) {
      return false;
    }

    this.formDataService.setWork(this.ceteObject);
    return true;
  }

  getCalculations(form: any, saveForm: boolean) {
    this.submitted = true;
    console.log("formulario");
    console.log(form);
    if (!form.valid) {
      return false;
    }
    Swal.fire({
      allowOutsideClick: false,
      icon: "info",
      text: "Espere por favor..."
    });
    Swal.showLoading();
    this.instrumentCalcService
      .ceteCalc(
        "CETE", // Codigo del instrumento
        {
          id_tipo_base: +this.general.base_anual,
          id_formato_ingreso: +this.general.formato_ingreso,
          id_periodicidad: +this.general.periodicidad
        },
        {
          valor_nominal: +this.f.valor_nominal.value,
          comision_casa_porcentaje: this.f.comision_casa_porcentaje.value,
          comision_bolsa_porcentaje: this.f.comision_bolsa_porcentaje.value,
          plazo: +this.f.plazo.value,
          rendimiento_bruto: this.f.rendimiento_bruto.value,
          otros_costos: this.f.otros_costos.value,
          fecha_operacion: this.f.fecha_operacion.value.singleDate.formatted,
          fecha_liquidacion: this.f.fecha_liquidacion.value.singleDate
            .formatted,
          fecha_ultima_cupon: this.f.fecha_ultima_cupon.value.singleDate
            .formatted
          //fecha_vencimiento: this.f.fecha_vencimiento.value.singleDate.formatted
        }
      )
      .subscribe(
        ans => {
          this.ingreso_bruto = ans["result"]["ingreso_bruto"];
          this.ingreso_neto = ans["result"]["ingreso_neto"];
          this.valor_transado = ans["result"]["valor_transado"];
          this.precio_porcentaje = ans["result"]["precio_porcentaje"];
          this.rendimiento_neto = ans["result"]["rendimiento_neto"];
          this.total_pagar = ans["result"]["total_pagar"];
          this.comision_bolsa = ans["result"]["comision_bolsa"];
          this.comision_casa = ans["result"]["comision_casa"];
          this.proyecciones = ans["result"]["proyecciones"];
          this.fecha_vencimiento = ans["result"]["fecha_vencimiento"];

          this.dataSource.data = this.proyecciones;
          this.dataSource.paginator = this.paginator;
          this.dataSource.sort = this.sort;

          this.ceteObject = {
            valor_nominal: this.investmentProposalForm.value.valor_nominal,
            plazo: this.investmentProposalForm.value.plazo,
            comision_casa_porcentaje: this.investmentProposalForm.value
              .comision_casa_porcentaje,
            comision_bolsa_porcentaje: this.investmentProposalForm.value
              .comision_bolsa_porcentaje,
            rendimiento_bruto: this.investmentProposalForm.value
              .rendimiento_bruto,
            otros_costos: this.f.otros_costos.value,
            //renta_porcentaje: this.f.renta_porcentaje.value,
            //id_formato_ingreso: this.f.formato_ingreso.value,
            fecha_operacion: this.f.fecha_operacion.value.singleDate.formatted,
            fecha_liquidacion: this.f.fecha_liquidacion.value.singleDate
              .formatted,
            fecha_ultima_cupon: this.f.fecha_ultima_cupon.value.singleDate
              .formatted,
            fecha_vencimiento: this.fecha_vencimiento,
            ingreso_bruto: this.ingreso_bruto,
            ingreso_neto: this.ingreso_neto,
            valor_transado: this.valor_transado,
            precio_porcentaje: this.precio_porcentaje,
            rendimiento_neto: this.rendimiento_neto,
            total_pagar: this.total_pagar,
            comision_bolsa: this.comision_bolsa,
            comision_casa: this.comision_casa,
            proyecciones: this.proyecciones
          };

          this.formDataService.setWork(this.ceteObject);
          Swal.close();
          if (saveForm == true) {
            if (this.investmentID != undefined) {
              this.router.navigate(["/investment-proposal/complement-info"], {
                queryParams: { id: this.investmentID }
              });
            } else {
              this.router.navigate(["/investment-proposal/complement-info"]);
            }
          }
        },
        err => {
          Swal.fire({
            icon: "error",
            title: "Error en el servidor",
            text: "No su pudo obtener la informacion"
          });
          return false;
        }
      );
  }

  goToPrevious() {
    this.submitted = true;
    if (this.investmentID != undefined) {
      this.router.navigate(["/investment-proposal/general-info"], {
        queryParams: { id: this.investmentID }
      });
    } else {
      this.router.navigate(["/investment-proposal/general-info"]);
    }
  }

  goToNext(form: any) {
    this.getCalculations(form, true);
  }
}
