import { Component, OnInit, ViewChild } from "@angular/core";
import { Router, ActivatedRoute } from "@angular/router";

import { ComplementInfo } from "@app/models/investment-proposal-form";
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 { IOption } from "ng-select";

@Component({
  selector: "app-complement-info",
  templateUrl: "./complement-info.component.html"
})
export class ComplementInfoComponent implements OnInit {
  title: string = "Formulario propuesta de inversión";
  complementInfo: ComplementInfo;
  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: Array<IOption>;
  periodicities: any;
  rate_agencies: any;
  scores: any;
  investmentProposalID: string;
  countries: any;
  companies: any;
  format_incomes: any;
  operations: any;
  payment_terms: any;

  complementInfoDontExists: boolean;
  companyValue: any;
  instrumentInfo: any;
  @ViewChild("emisorSelect", { static: false })
  public emisorSelect: any;

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

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

    this.complementInfo = this.formDataService.getComplementInfo();
    this.complementInfoDontExists = this.complementInfo == undefined;

    this.instrumentInfo = this.formDataService.getGeneralInfo().instrumentos;
    this.catalogService.getCatalogInfo("empresas").subscribe(res => {
      this.companies = res;

      if (this.investmentProposalID != undefined) {
        this.companyValue = this.companies.find(
          e => e.id_empresa == this.complementInfo.empresa
        );

        this.companyValue =
          this.companyValue != undefined ? this.companyValue.nombre : "-";
      }
    });
    this.catalogService.getCatalogInfo("paises").subscribe(res => {
      this.countries = res;
    });

    this.catalogService.getCatalogInfo("tipos-mercados").subscribe(res => {
      this.markets = res;
    });
    this.catalogService.getCatalogInfo("tipos-emisores").subscribe(res => {
      this.emitters = [];
      for (let property in res) {
        this.emitters.push({
          label: res[property]["nombre"],
          value: res[property]["id_tipo_emisor"].toString()
        });
      }

      if (this.complementInfo.emisores.toString() != "") {
        this.emisorSelect.select(this.complementInfo.emisores.toString());
      }
    });

    this.catalogService.getRateAgencies().subscribe(res => {
      this.rate_agencies = res;
    });

    this.catalogService.getScores().subscribe(res => {
      this.scores = res;
    });

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

    this.catalogService.getCatalogInfo("tipos-operaciones").subscribe(res => {
      this.operations = res;
    });

    this.investmentProposalForm = this.formBuilder.group({
      tipo_mercado: [
        this.complementInfoDontExists ? "" : this.complementInfo.tipo_mercado,
        [Validators.required]
      ],

      emisores: [
        this.complementInfoDontExists
          ? ""
          : this.complementInfo.emisores.toString(),
        [Validators.required]
      ],
      empresa: [
        this.complementInfoDontExists ? "" : this.complementInfo.empresa,
        [Validators.required]
      ],
      pais: [
        this.complementInfoDontExists ? "" : this.complementInfo.pais,
        [Validators.required]
      ],
      plazo: [
        this.complementInfoDontExists ? "" : this.complementInfo.plazo,
        [Validators.required]
      ],
      operaciones: [
        this.complementInfoDontExists ? "" : this.complementInfo.operaciones,
        [Validators.required]
      ],

      comentarios: [
        this.complementInfoDontExists ? "" : this.complementInfo.comentarios,
        []
      ],
      justificacion: [
        this.complementInfoDontExists ? "" : this.complementInfo.justificacion,
        []
      ]
    });

    // Set default values depending of the instrument
    if (
      this.complementInfoDontExists == true ||
      Object.values(this.complementInfo).every(x => x === null || x === "")
    ) {
      switch (this.instrumentInfo) {
        case "LETE":
          this.investmentProposalForm.patchValue({
            emisores: this.investmentProposalForm.value.emisores = "985",
            pais: this.investmentProposalForm.value.pais = 210
          });
          break;
        case "CETE":
          this.investmentProposalForm.patchValue({
            emisores: this.investmentProposalForm.value.emisores = "985",
            pais: this.investmentProposalForm.value.pais = 210,
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;

        case "VCN":
          this.investmentProposalForm.patchValue({
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;

        case "PBUR":
          this.investmentProposalForm.patchValue({
            pais: this.investmentProposalForm.value.pais = 210,
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;

        case "DAP":
          this.investmentProposalForm.patchValue({
            tipo_mercado: this.investmentProposalForm.value.tipo_mercado = 5,
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;

        case "BONO":
          this.investmentProposalForm.patchValue({
            pais: this.investmentProposalForm.value.pais = 210,
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;

        case "EURB":
          this.investmentProposalForm.patchValue({
            pais: this.investmentProposalForm.value.pais = 210,
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;

        case "CINV":
          this.investmentProposalForm.patchValue({
            pais: this.investmentProposalForm.value.pais = 210,
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;

        case "TIT":
          this.investmentProposalForm.patchValue({
            pais: this.investmentProposalForm.value.pais = 210,
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;

        case "FINV":
          this.investmentProposalForm.patchValue({
            tipo_mercado: this.investmentProposalForm.value.tipo_mercado = 5,
            pais: this.investmentProposalForm.value.pais = 210,
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;

        case "OPC":
          this.investmentProposalForm.patchValue({
            //tipo_mercado: this.investmentProposalForm.value.tipo_mercado = 0,
            pais: this.investmentProposalForm.value.pais = 233,
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;

        case "FUTU":
          this.investmentProposalForm.patchValue({
            //tipo_mercado: this.investmentProposalForm.value.tipo_mercado = 0,
            pais: this.investmentProposalForm.value.pais = 233,
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;

        case "PEMP":
          this.investmentProposalForm.patchValue({
            tipo_mercado: this.investmentProposalForm.value.tipo_mercado = 5,
            pais: this.investmentProposalForm.value.pais = 210,
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;

        case "PPER":
          this.investmentProposalForm.patchValue({
            tipo_mercado: this.investmentProposalForm.value.tipo_mercado = 5,
            pais: this.investmentProposalForm.value.pais = 210,
            operaciones: this.investmentProposalForm.value.operaciones = 2
          });
          break;
      }
    }
  }

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

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

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

  goToNext(form: any) {
    if (this.save(form)) {
      if (this.investmentProposalID != undefined) {
        this.router.navigate(["/investment-proposal/result"], {
          queryParams: { id: this.investmentProposalID }
        });
      } else {
        this.router.navigate(["/investment-proposal/result"]);
      }
    }
  }
}
