import { Component, ViewChild, OnInit } from "@angular/core";
import { MatPaginator } from "@angular/material/paginator";
import { MatSort } from "@angular/material/sort";
import { MatTableDataSource } from "@angular/material/table";
import Swal from "sweetalert2";
import { CatalogsService } from "src/app/services/catalogs.service";
import { IncomesService } from "@app/services/incomes.service";
import { AuthService } from "@app/services/auth2.service";
import { JwtHelperService } from "@auth0/angular-jwt";
import { InvestmentProposal } from "@app/models/investment-proposal";
import { from } from "rxjs";
import { FormInvestmentProposalService } from "@app/services/form-investment-proposal.service";
import { Router, ActivatedRoute } from "@angular/router";
import {
  FormBuilder,
  FormGroup,
  FormControl,
  FormArray,
  Validators
} from "@angular/forms";
import { IAngularMyDpOptions } from "angular-mydatepicker";

@Component({
  selector: "app-general-form-income",
  templateUrl: "./general-form.component.html",
  styleUrls: ["./general-form.component.scss"]
})
export class GeneralIncomeFormComponent implements OnInit {
  helper = new JwtHelperService();

  title: string = "Ingresos para depósito a plazo";

  displayedColumns: string[] = [
    "fecha_proyeccion_ingreso",
    "fecha_ingreso",
    "fecha_conciliacion",
    "capital",
    "ingreso_bruto",
    "renta"
  ];
  //displayedColumns: string[] = ['state'];

  // 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;

  listProposals: InvestmentProposal[];
  dataSource = new MatTableDataSource(this.listProposals);

  resultsLength = 0;
  isLoadingResults = true;
  isRateLimitReached = false;
  userRole: any;

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: true }) sort: MatSort;
  role_number: any;
  projectionID: string;

  form: FormArray;
  investmentProposalForm: FormGroup;

  proyecciones: any;
  proyeccionesProps = [];
  dataRetrieved: boolean = false;

  array1;
  array2;
  array3;
  investment: any;
  projection: any;
  projection_exists: boolean;
  instrumentCode: any;
  payment_types: any;
  funds: any;
  banks: any;
  accounts: any;
  payment_date: string = "";
  submitted: boolean;
  incomeObject: any;
  incomes: any;
  incomes_exists: boolean;
  idInversion: any;
  idInstrumentIncome: any;
  projectionDate: any;
  projectionRes: any;
  partial: boolean;
  idProjection: any;
  cantConciliate: boolean = true;
  conciliateObject: any;
  has_conciliate: boolean;
  showIncomeForm: boolean = false;
  accounts_origin: any;
  accounts_destination: any;

  constructor(
    private catalogService: CatalogsService,
    private incomesService: IncomesService,
    private authService: AuthService,
    private formInvestmentProposal: FormInvestmentProposalService,
    private router: Router,
    private route: ActivatedRoute,

    private formBuilder: FormBuilder
  ) {
    const decodedToken = this.helper.decodeToken(
      this.authService.getJwtToken()
    );
    this.userRole = decodedToken.groups;

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

  ngOnInit() {
    this.partial = false;

    const formDataObj = {};

    this.route.queryParams.subscribe(params => {
      // ALT
      this.idInversion = params["id_inversion"];
      this.idInstrumentIncome = params["id_proyeccion_ingreso_instrumento"];
      this.projectionDate = params["fecha_proyeccion_pago"];
      this.idProjection = params["id_proyeccion_ingreso"];
    });

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

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

    this.incomesService
      .getProjection(
        this.idInversion,
        this.idInstrumentIncome,
        this.projectionDate,
        this.idProjection
      )
      .subscribe(
        res => {
          this.projection_exists = true;
          this.projectionRes = res["result"][0];

          if (this.projectionRes.estado == "CONCILIADO") {
            this.has_conciliate = true;
          }

          if (this.projectionRes.estado == "NO CONCILIADO") {
            this.cantConciliate = false;
          }

          if (this.projectionRes.estado == "EN ESPERA") {
            // Estado
            this.showIncomeForm = true;
          }

          this.investmentProposalForm.setValue({
            capital: this.projectionRes.capital,
            ingreso_bruto: this.projectionRes.ingreso_bruto,
            renta: this.projectionRes.renta,
            ingreso_neto: this.projectionRes.ingreso_neto,
            tipo_pago: "",
            cuenta_bancaria: "",
            comentario: "",
            fecha_inicio: "",
            fecha_vencimiento: ""
          });
          Swal.close();
        },
        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.investmentProposalForm = this.formBuilder.group({
      capital: [
        "",
        [
          Validators.required,
          //Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/)
          Validators.pattern("^[0-9,.]+$")
        ]
      ],
      ingreso_bruto: [
        "",
        [
          Validators.required,
          //Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/)
          Validators.pattern("^[0-9,.]+$")
        ]
      ],
      renta: [
        "",
        [
          Validators.required,
          //Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/)
          Validators.pattern("^[0-9,.]+$")
        ]
      ],
      ingreso_neto: [
        "",
        [
          Validators.required,
          //Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/)
          Validators.pattern("^[0-9,.]+$")
        ]
      ],
      tipo_pago: ["", Validators.required],
      cuenta_bancaria: ["", Validators.required],
      //fecha_ingreso: ["", Validators.required],
      comentario: ["", Validators.required],
      fecha_inicio: [""],
      fecha_vencimiento: [""]
    });
  }

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

  toggle = () => {
    if (this.partial == false) {
      this.partial = true;
    } else {
      this.partial = false;
    }
  };

  submitIncome(form: any) {
    this.submitted = true;
    let inversionCapital = this.clearValor(form.value.capital, "decimal");
    let inversionBruto = this.clearValor(form.value.ingreso_bruto, "decimal");
    let inversionNeto = this.clearValor(form.value.ingreso_neto, "decimal");
    if (!form.valid) {
      return false;
    }

    this.incomeObject = {
      id_inversion_instrumento: this.projectionRes.id_inversion_instrumento,
      id_proyeccion_ingreso_instrumento: this.idInstrumentIncome,
      fecha_proyeccion_pago: this.projectionDate,

      capital: inversionCapital,
      ingreso_bruto: inversionBruto,
      renta: form.value.renta,
      ingreso_neto: inversionNeto,
      id_cuenta_bancaria: form.value.cuenta_bancaria,
      id_tipo_pago: form.value.tipo_pago,
      comentario: form.value.comentario
    };

    if (this.idProjection != undefined) {
      this.incomeObject["id_proyeccion_ingreso"] = this.idProjection;
    }

    if (this.partial == true) {
      this.incomeObject["fecha_inicio"] =
        form.value.fecha_inicio.singleDate.formatted;
      this.incomeObject["fecha_vencimiento"] =
        form.value.fecha_vencimiento.singleDate.formatted;
    }

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

    this.incomesService.createIncome(this.incomeObject).subscribe(
      success => {
        if (success) {
          Swal.fire({
            allowOutsideClick: false,
            icon: "success",
            showCancelButton: false,
            title: "Exito",
            confirmButtonText: "El ingreso ha sido guardado"
          }).then(result => {
            Swal.close();
            this.cantConciliate = false;
          });
        }
      },
      err => {
        Swal.fire({
          icon: "error",
          title: "Error al guardar",
          text: err.message
        });
      }
    );
  }

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

  public inputValidator(event: any) {
    //console.log(event.target.value);
    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
    }
  }
  conciliateIncome() {
    this.conciliateObject = {
      id_inversion_instrumento: this.projectionRes.id_inversion_instrumento,
      id_proyeccion_ingreso_instrumento: this.idInstrumentIncome,
      fecha_proyeccion_pago: this.projectionDate
    };
    if (this.idProjection != undefined) {
      this.conciliateObject["id_proyeccion_ingreso"] = this.idProjection;
    }

    this.incomesService.conciliateIncome(this.conciliateObject).subscribe(
      success => {
        if (success) {
          Swal.fire({
            allowOutsideClick: false,
            icon: "success",
            showCancelButton: false,
            title: "Exito",
            confirmButtonText: "El ingreso ha sido conciliado"
          }).then(result => {
            Swal.close();
            window.location.href = "#/investment-incomes";
          });
        }
      },
      err => {
        Swal.fire({
          icon: "error",
          title: "Error al guardar",
          text: err.message
        });
      }
    );
  }
}
