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

@Component({
  selector: "app-new-investment-proposal",
  templateUrl: "./general-info.component.html",
  styleUrls: ["./general-info.component.scss"]
})
export class InvestmentProposalGeneralInfoComponent
  implements OnInit, OnChanges {
  general: GeneralInfo;
  complement: ComplementInfo;
  instrument: {};
  form: any;
  investmentProposalID: any = undefined;
  // 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;
  model: IMyDateModel = null;

  title: string = "Formulario propuesta de inversión";
  submitted: boolean = false;
  role_number: any;
  periodicities: any;
  rates: any;
  revenues: any;
  funds: any;
  instrumentTypes: any;
  generalInfoDontExists: boolean;
  plazos: any;
  base_types: any;
  financials: any;
  format_incomes: any;

  gInfo: any;
  gInstrument: any;
  gComplement: any;
  datez: any;
  instrumentName: any;
  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private formDataService: FormInvestmentProposalService,
    private catalogService: CatalogsService,
    private investmentsService: InvestmentsService,
    public datepipe: DatePipe
  ) {}

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

    if (this.investmentProposalID != undefined) {
      this.investmentsService
        .getProposalInvestment(this.investmentProposalID)
        .subscribe(
          res => {
            console.log("results");
            console.log(res);
            console.log("-------");
            console.log(this.formDataService.getFormData());
            this.gInfo = {
              asunto: res["result"]["asunto"],
              origenes_fondo:
                res["result"]["id_origen_fondo"] == null
                  ? ""
                  : res["result"]["id_origen_fondo"]["id_origen_fondo"],
              name: res["result"]["nombre_inversion"],
              //date: "",
              tipo_tasa: res["result"]["id_tipo_tasa"] || "",
              tipo_renta:
                res["result"]["id_tipo_renta"] == null
                  ? ""
                  : res["result"]["id_tipo_renta"]["id_tipo_renta"],
              periodicidad:
                res["result"]["id_periodicidad"] == null
                  ? ""
                  : res["result"]["id_periodicidad"]["id_periodicidad"],

              instrumentos:
                res["result"]["id_inversion_instrumento"][
                  "id_tipo_instrumento"
                ]["codigo"],
              base_anual:
                res["result"]["id_tipo_base"] == null
                  ? ""
                  : res["result"]["id_tipo_base"]["id_tipo_base"],
              casa:
                res["result"]["id_entidad"] == null
                  ? ""
                  : res["result"]["id_entidad"]["id_entidad_financiera"],
              formato_ingreso:
                res["result"]["id_formato_ingreso"] == null
                  ? ""
                  : res["result"]["id_formato_ingreso"]["id_formato_ingreso"]
            };

            this.gInstrument =
              res["result"]["id_inversion_instrumento"]["instrumento"];

            this.gInstrument["id_inversion_instrumento"] =
              res["result"]["id_inversion_instrumento"][
                "id_inversion_instrumento"
              ];

            this.gComplement = {
              tipo_mercado:
                res["result"]["id_tipo_mercado"] == null
                  ? ""
                  : res["result"]["id_tipo_mercado"]["id_tipo_mercado"],
              emisores:
                res["result"]["id_tipo_emisor"] == null
                  ? ""
                  : res["result"]["id_tipo_emisor"]["id_tipo_emisor"],
              empresa:
                res["result"]["id_empresa"] == null
                  ? ""
                  : res["result"]["id_empresa"]["id_empresa"],
              pais:
                res["result"]["id_pais"] == null
                  ? ""
                  : res["result"]["id_pais"]["id_pais"],
              plazo:
                res["result"]["id_plazo"] == null
                  ? ""
                  : res["result"]["id_plazo"]["id_plazo"],
              operaciones:
                res["result"]["id_tipo_operacion"] == null
                  ? ""
                  : res["result"]["id_tipo_operacion"]["id_tipo_operacion"],
              comentarios: res["result"]["comentario"],
              justificacion: res["result"]["justificacion"]
            };

            // Setear objeto dinamico con valores obtenidos del endpoint
            this.general = this.formDataService.getGeneralInfo();
            console.log("GENERAL");
            console.log(this.general);
            // Validar que el objeto dinamico contenga valores, si no, setear con valores obtenidos del endpoint
            if (
              Object.values(this.general).every(x => x === null || x === "")
            ) {
              console.log("I GOT HERE");
              this.formDataService.setGeneralInfo(this.gInfo);
              this.general = this.formDataService.getGeneralInfo();
              this.generalInfoDontExists = this.general == undefined;
              this.investmentProposalForm.setValue({
                asunto: this.gInfo.asunto,
                origenes_fondo: this.gInfo.origenes_fondo,
                name: this.gInfo.name,
                tipo_tasa: this.gInfo.tipo_tasa,
                tipo_renta: this.gInfo.tipo_renta,
                periodicidad: this.gInfo.periodicidad,

                instrumentos: this.gInfo.instrumentos,
                base_anual: this.gInfo.base_anual,
                casa: this.gInfo.casa,
                formato_ingreso: this.gInfo.formato_ingreso
              });
            }

            this.instrument = this.formDataService.getWork();
            console.log("inicializar instrumento");
            console.log(this.instrument);
            if (
              this.instrument == undefined ||
              Object.values(this.instrument).every(x => x === null || x === "")
            ) {
              this.formDataService.setWork(this.gInstrument);
              this.instrument = this.formDataService.getWork();
            }

            this.complement = this.formDataService.getComplementInfo();
            if (
              Object.values(this.complement).every(x => x === null || x === "")
            ) {
              this.formDataService.setComplementInfo(this.gComplement);
            }
          },
          err => {
            Swal.fire({
              icon: "error",
              title: "Error en el servidor",
              text: err.message
            });
          }
        );
    } else {
    }

    //this.datepipe.transform(new Date(), "yyyy-MM-dd");
    this.general = this.formDataService.getGeneralInfo();
    this.generalInfoDontExists = false;
    // Obtener catalogos

    this.catalogService.getPaymentTerms().subscribe(res => {
      this.plazos = res;
    });

    this.catalogService.getFinancialEntities().subscribe(res => {
      this.financials = res;
    });

    this.catalogService.getBaseTypes().subscribe(res => {
      this.base_types = res;
    });
    this.catalogService.getPeriodicities().subscribe(res => {
      this.periodicities = res;
    });

    this.catalogService.getRateTypes().subscribe(res => {
      this.rates = res;
    });
    this.catalogService.getRevenueTypes().subscribe(res => {
      this.revenues = res;
    });
    this.catalogService.getFundsOrigins().subscribe(res => {
      this.funds = res;
    });
    this.catalogService.getInstrumentTypes().subscribe(res => {
      this.instrumentTypes = res;
      console.log(this.generalInfoDontExists);
      if (this.generalInfoDontExists == false) {
        this.instrumentName = res.find(
          e => e.codigo == this.general.instrumentos
        );
        this.instrumentName =
          this.instrumentName != undefined ? this.instrumentName.nombre : "-";
      }
    });
    //getIncomeFormat
    this.catalogService.getIncomeFormat().subscribe(res => {
      this.format_incomes = res;
    });

    // Si el arreglo principal de objetos viene con todos sus elementos vacios, inicializo el formulario.
    //if (Object.values(this.general).every(x => x === null || x === "")) {
    this.callForm(this.generalInfoDontExists, this.general);
  }

  ngOnChanges() {
    console.log("CHANGES");
  }

  save(form: any): boolean {
    if (!form.valid) {
      return false;
    }
    this.formDataService.setGeneralInfo(this.investmentProposalForm.value);
    return true;
  }

  callForm(formExists: boolean, form: any) {
    this.investmentProposalForm = this.formBuilder.group({
      asunto: ["", Validators.required],
      origenes_fondo: ["", Validators.required],
      name: ["", Validators.required],
      //date: ["", Validators.required],
      tipo_tasa: ["", Validators.required],
      tipo_renta: ["", Validators.required],
      periodicidad: ["", Validators.required],

      base_anual: ["", Validators.required],
      casa: ["", Validators.required],
      instrumentos: ["", Validators.required],
      formato_ingreso: ["", Validators.required]
    });

    this.investmentProposalForm.setValue({
      asunto: form.asunto,
      origenes_fondo: form.origenes_fondo || "",
      name: form.name || "",
      //date: form.date.singleDate == undefined ? "" : form.date,
      tipo_tasa: form.tipo_tasa || "",
      tipo_renta: form.tipo_renta || "",
      periodicidad: form.periodicidad || "",

      instrumentos: form.instrumentos || "",
      base_anual: form.base_anual || "",
      casa: form.casa || "",
      formato_ingreso: form.formato_ingreso || ""
    });
  }

  goToNext(form: any) {
    this.submitted = true;
    if (this.save(form)) {
      // Navigate to the work page

      if (this.investmentProposalID != undefined) {
        this.router.navigate(["/investment-proposal/instrument-work"], {
          queryParams: { id: this.investmentProposalID },
          relativeTo: this.route
        });
        //this.router.navigateByUrl(         `/investment-proposal/${this.investmentProposalID}/instrument-work/`);
      } else {
        this.router.navigate(["/investment-proposal/instrument-work"]);
      }
    }
  }

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